2005-01-28 Havoc Pennington <hp@redhat.com>
[platform/upstream/dbus.git] / dbus / dbus-message.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-message.c  DBusMessage object
3  *
4  * Copyright (C) 2002, 2003, 2004, 2005  Red Hat Inc.
5  * Copyright (C) 2002, 2003  CodeFactory AB
6  *
7  * Licensed under the Academic Free License version 2.1
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  *
23  */
24
25 #include "dbus-internals.h"
26 #include "dbus-marshal-recursive.h"
27 #include "dbus-marshal-validate.h"
28 #include "dbus-marshal-byteswap.h"
29 #include "dbus-marshal-header.h"
30 #include "dbus-message-private.h"
31 #include "dbus-object-tree.h"
32 #include "dbus-memory.h"
33 #include "dbus-list.h"
34 #include <string.h>
35
36 /**
37  * @defgroup DBusMessageInternals DBusMessage implementation details
38  * @ingroup DBusInternals
39  * @brief DBusMessage private implementation details.
40  *
41  * The guts of DBusMessage and its methods.
42  *
43  * @{
44  */
45
46 /* Not thread locked, but strictly const/read-only so should be OK
47  */
48 /** An static string representing an empty signature */
49 _DBUS_STRING_DEFINE_STATIC(_dbus_empty_signature_str,  "");
50
51 /* these have wacky values to help trap uninitialized iterators;
52  * but has to fit in 3 bits
53  */
54 enum {
55   DBUS_MESSAGE_ITER_TYPE_READER = 3,
56   DBUS_MESSAGE_ITER_TYPE_WRITER = 7
57 };
58
59 /** typedef for internals of message iterator */
60 typedef struct DBusMessageRealIter DBusMessageRealIter;
61
62 /**
63  * @brief Internals of DBusMessageIter
64  *
65  * Object representing a position in a message. All fields are internal.
66  */
67 struct DBusMessageRealIter
68 {
69   DBusMessage *message; /**< Message used */
70   dbus_uint32_t changed_stamp : CHANGED_STAMP_BITS; /**< stamp to detect invalid iters */
71   dbus_uint32_t iter_type : 3;      /**< whether this is a reader or writer iter */
72   dbus_uint32_t sig_refcount : 8;   /**< depth of open_signature() */
73   union
74   {
75     DBusTypeWriter writer; /**< writer */
76     DBusTypeReader reader; /**< reader */
77   } u; /**< the type writer or reader that does all the work */
78 };
79
80 static void
81 get_const_signature (DBusHeader        *header,
82                      const DBusString **type_str_p,
83                      int               *type_pos_p)
84 {
85   if (_dbus_header_get_field_raw (header,
86                                   DBUS_HEADER_FIELD_SIGNATURE,
87                                   type_str_p,
88                                   type_pos_p))
89     {
90       *type_pos_p += 1; /* skip the signature length which is 1 byte */
91     }
92   else
93     {
94       *type_str_p = &_dbus_empty_signature_str;
95       *type_pos_p = 0;
96     }
97 }
98
99 /**
100  * Swaps the message to compiler byte order if required
101  *
102  * @param message the message
103  */
104 static void
105 _dbus_message_byteswap (DBusMessage *message)
106 {
107   const DBusString *type_str;
108   int type_pos;
109   
110   if (message->byte_order == DBUS_COMPILER_BYTE_ORDER)
111     return;
112
113   _dbus_verbose ("Swapping message into compiler byte order\n");
114   
115   get_const_signature (&message->header, &type_str, &type_pos);
116   
117   _dbus_marshal_byteswap (type_str, type_pos,
118                           message->byte_order,
119                           DBUS_COMPILER_BYTE_ORDER,
120                           &message->body, 0);
121
122   message->byte_order = DBUS_COMPILER_BYTE_ORDER;
123   
124   _dbus_header_byteswap (&message->header, DBUS_COMPILER_BYTE_ORDER);
125 }
126
127 #define ensure_byte_order(message)                      \
128  if (message->byte_order != DBUS_COMPILER_BYTE_ORDER)   \
129    _dbus_message_byteswap (message)
130
131 /**
132  * Gets the data to be sent over the network for this message.
133  * The header and then the body should be written out.
134  * This function is guaranteed to always return the same
135  * data once a message is locked (with _dbus_message_lock()).
136  *
137  * @param message the message.
138  * @param header return location for message header data.
139  * @param body return location for message body data.
140  */
141 void
142 _dbus_message_get_network_data (DBusMessage          *message,
143                                 const DBusString    **header,
144                                 const DBusString    **body)
145 {
146   _dbus_assert (message->locked);
147
148   *header = &message->header.data;
149   *body = &message->body;
150 }
151
152 /**
153  * Sets the serial number of a message.
154  * This can only be done once on a message.
155  *
156  * @param message the message
157  * @param serial the serial
158  */
159 void
160 _dbus_message_set_serial (DBusMessage   *message,
161                           dbus_uint32_t  serial)
162 {
163   _dbus_assert (message != NULL);
164   _dbus_assert (!message->locked);
165   _dbus_assert (dbus_message_get_serial (message) == 0);
166
167   _dbus_header_set_serial (&message->header, serial);
168 }
169
170 /**
171  * Adds a counter to be incremented immediately with the
172  * size of this message, and decremented by the size
173  * of this message when this message if finalized.
174  * The link contains a counter with its refcount already
175  * incremented, but the counter itself not incremented.
176  * Ownership of link and counter refcount is passed to
177  * the message.
178  *
179  * @param message the message
180  * @param link link with counter as data
181  */
182 void
183 _dbus_message_add_size_counter_link (DBusMessage  *message,
184                                      DBusList     *link)
185 {
186   /* right now we don't recompute the delta when message
187    * size changes, and that's OK for current purposes
188    * I think, but could be important to change later.
189    * Do recompute it whenever there are no outstanding counters,
190    * since it's basically free.
191    */
192   if (message->size_counters == NULL)
193     {
194       message->size_counter_delta =
195         _dbus_string_get_length (&message->header.data) +
196         _dbus_string_get_length (&message->body);
197
198 #if 0
199       _dbus_verbose ("message has size %ld\n",
200                      message->size_counter_delta);
201 #endif
202     }
203
204   _dbus_list_append_link (&message->size_counters, link);
205
206   _dbus_counter_adjust (link->data, message->size_counter_delta);
207 }
208
209 /**
210  * Adds a counter to be incremented immediately with the
211  * size of this message, and decremented by the size
212  * of this message when this message if finalized.
213  *
214  * @param message the message
215  * @param counter the counter
216  * @returns #FALSE if no memory
217  */
218 dbus_bool_t
219 _dbus_message_add_size_counter (DBusMessage *message,
220                                 DBusCounter *counter)
221 {
222   DBusList *link;
223
224   link = _dbus_list_alloc_link (counter);
225   if (link == NULL)
226     return FALSE;
227
228   _dbus_counter_ref (counter);
229   _dbus_message_add_size_counter_link (message, link);
230
231   return TRUE;
232 }
233
234 /**
235  * Removes a counter tracking the size of this message, and decrements
236  * the counter by the size of this message.
237  *
238  * @param message the message
239  * @param link_return return the link used
240  * @param counter the counter
241  */
242 void
243 _dbus_message_remove_size_counter (DBusMessage  *message,
244                                    DBusCounter  *counter,
245                                    DBusList    **link_return)
246 {
247   DBusList *link;
248
249   link = _dbus_list_find_last (&message->size_counters,
250                                counter);
251   _dbus_assert (link != NULL);
252
253   _dbus_list_unlink (&message->size_counters,
254                      link);
255   if (link_return)
256     *link_return = link;
257   else
258     _dbus_list_free_link (link);
259
260   _dbus_counter_adjust (counter, - message->size_counter_delta);
261
262   _dbus_counter_unref (counter);
263 }
264
265 /**
266  * Locks a message. Allows checking that applications don't keep a
267  * reference to a message in the outgoing queue and change it
268  * underneath us. Messages are locked when they enter the outgoing
269  * queue (dbus_connection_send_message()), and the library complains
270  * if the message is modified while locked.
271  *
272  * @param message the message to lock.
273  */
274 void
275 _dbus_message_lock (DBusMessage  *message)
276 {
277   if (!message->locked)
278     {
279       _dbus_header_update_lengths (&message->header,
280                                    _dbus_string_get_length (&message->body));
281
282       /* must have a signature if you have a body */
283       _dbus_assert (_dbus_string_get_length (&message->body) == 0 ||
284                     dbus_message_get_signature (message) != NULL);
285
286       message->locked = TRUE;
287     }
288 }
289
290 static dbus_bool_t
291 set_or_delete_string_field (DBusMessage *message,
292                             int          field,
293                             int          typecode,
294                             const char  *value)
295 {
296   if (value == NULL)
297     return _dbus_header_delete_field (&message->header, field);
298   else
299     return _dbus_header_set_field_basic (&message->header,
300                                          field,
301                                          typecode,
302                                          &value);
303 }
304
305 #if 0
306 /* Probably we don't need to use this */
307 /**
308  * Sets the signature of the message, i.e. the arguments in the
309  * message payload. The signature includes only "in" arguments for
310  * #DBUS_MESSAGE_TYPE_METHOD_CALL and only "out" arguments for
311  * #DBUS_MESSAGE_TYPE_METHOD_RETURN, so is slightly different from
312  * what you might expect (it does not include the signature of the
313  * entire C++-style method).
314  *
315  * The signature is a string made up of type codes such as
316  * #DBUS_TYPE_INT32. The string is terminated with nul (nul is also
317  * the value of #DBUS_TYPE_INVALID). The macros such as
318  * #DBUS_TYPE_INT32 evaluate to integers; to assemble a signature you
319  * may find it useful to use the string forms, such as
320  * #DBUS_TYPE_INT32_AS_STRING.
321  *
322  * An "unset" or #NULL signature is considered the same as an empty
323  * signature. In fact dbus_message_get_signature() will never return
324  * #NULL.
325  *
326  * @param message the message
327  * @param signature the type signature or #NULL to unset
328  * @returns #FALSE if no memory
329  */
330 static dbus_bool_t
331 _dbus_message_set_signature (DBusMessage *message,
332                              const char  *signature)
333 {
334   _dbus_return_val_if_fail (message != NULL, FALSE);
335   _dbus_return_val_if_fail (!message->locked, FALSE);
336   _dbus_return_val_if_fail (signature == NULL ||
337                             _dbus_check_is_valid_signature (signature));
338   /* can't delete the signature if you have a message body */
339   _dbus_return_val_if_fail (_dbus_string_get_length (&message->body) == 0 ||
340                             signature != NULL);
341
342   return set_or_delete_string_field (message,
343                                      DBUS_HEADER_FIELD_SIGNATURE,
344                                      DBUS_TYPE_SIGNATURE,
345                                      signature);
346 }
347 #endif
348
349 /** @} */
350
351 /**
352  * @defgroup DBusMessage DBusMessage
353  * @ingroup  DBus
354  * @brief Message to be sent or received over a DBusConnection.
355  *
356  * A DBusMessage is the most basic unit of communication over a
357  * DBusConnection. A DBusConnection represents a stream of messages
358  * received from a remote application, and a stream of messages
359  * sent to a remote application.
360  *
361  * @{
362  */
363
364 /**
365  * @typedef DBusMessage
366  *
367  * Opaque data type representing a message received from or to be
368  * sent to another application.
369  */
370
371 /**
372  * Returns the serial of a message or 0 if none has been specified.
373  * The message's serial number is provided by the application sending
374  * the message and is used to identify replies to this message.  All
375  * messages received on a connection will have a serial, but messages
376  * you haven't sent yet may return 0.
377  *
378  * @param message the message
379  * @returns the client serial
380  */
381 dbus_uint32_t
382 dbus_message_get_serial (DBusMessage *message)
383 {
384   _dbus_return_val_if_fail (message != NULL, 0);
385
386   return _dbus_header_get_serial (&message->header);
387 }
388
389 /**
390  * Sets the reply serial of a message (the client serial
391  * of the message this is a reply to).
392  *
393  * @param message the message
394  * @param reply_serial the client serial
395  * @returns #FALSE if not enough memory
396  */
397 dbus_bool_t
398 dbus_message_set_reply_serial (DBusMessage   *message,
399                                dbus_uint32_t  reply_serial)
400 {
401   _dbus_return_val_if_fail (message != NULL, FALSE);
402   _dbus_return_val_if_fail (!message->locked, FALSE);
403
404   return _dbus_header_set_field_basic (&message->header,
405                                        DBUS_HEADER_FIELD_REPLY_SERIAL,
406                                        DBUS_TYPE_UINT32,
407                                        &reply_serial);
408 }
409
410 /**
411  * Returns the serial that the message is a reply to or 0 if none.
412  *
413  * @param message the message
414  * @returns the reply serial
415  */
416 dbus_uint32_t
417 dbus_message_get_reply_serial  (DBusMessage *message)
418 {
419   dbus_uint32_t v_UINT32;
420
421   _dbus_return_val_if_fail (message != NULL, 0);
422
423   if (_dbus_header_get_field_basic (&message->header,
424                                     DBUS_HEADER_FIELD_REPLY_SERIAL,
425                                     DBUS_TYPE_UINT32,
426                                     &v_UINT32))
427     return v_UINT32;
428   else
429     return 0;
430 }
431
432 static void
433 free_size_counter (void *element,
434                    void *data)
435 {
436   DBusCounter *counter = element;
437   DBusMessage *message = data;
438
439   _dbus_counter_adjust (counter, - message->size_counter_delta);
440
441   _dbus_counter_unref (counter);
442 }
443
444 static void
445 dbus_message_finalize (DBusMessage *message)
446 {
447   _dbus_assert (message->refcount.value == 0);
448
449   /* This calls application callbacks! */
450   _dbus_data_slot_list_free (&message->slot_list);
451
452   _dbus_list_foreach (&message->size_counters,
453                       free_size_counter, message);
454   _dbus_list_clear (&message->size_counters);
455
456   _dbus_header_free (&message->header);
457   _dbus_string_free (&message->body);
458
459   dbus_free (message);
460 }
461
462 /* Message Cache
463  *
464  * We cache some DBusMessage to reduce the overhead of allocating
465  * them.  In my profiling this consistently made about an 8%
466  * difference.  It avoids the malloc for the message, the malloc for
467  * the slot list, the malloc for the header string and body string,
468  * and the associated free() calls. It does introduce another global
469  * lock which could be a performance issue in certain cases.
470  *
471  * For the echo client/server the round trip time goes from around
472  * .000077 to .000069 with the message cache on my laptop. The sysprof
473  * change is as follows (numbers are cumulative percentage):
474  *
475  *  with message cache implemented as array as it is now (0.000069 per):
476  *    new_empty_header           1.46
477  *      mutex_lock               0.56    # i.e. _DBUS_LOCK(message_cache)
478  *      mutex_unlock             0.25
479  *      self                     0.41
480  *    unref                      2.24
481  *      self                     0.68
482  *      list_clear               0.43
483  *      mutex_lock               0.33    # i.e. _DBUS_LOCK(message_cache)
484  *      mutex_unlock             0.25
485  *
486  *  with message cache implemented as list (0.000070 per roundtrip):
487  *    new_empty_header           2.72
488  *      list_pop_first           1.88
489  *    unref                      3.3
490  *      list_prepend             1.63
491  *
492  * without cache (0.000077 per roundtrip):
493  *    new_empty_header           6.7
494  *      string_init_preallocated 3.43
495  *        dbus_malloc            2.43
496  *      dbus_malloc0             2.59
497  *
498  *    unref                      4.02
499  *      string_free              1.82
500  *        dbus_free              1.63
501  *      dbus_free                0.71
502  *
503  * If you implement the message_cache with a list, the primary reason
504  * it's slower is that you add another thread lock (on the DBusList
505  * mempool).
506  */
507
508 /** Avoid caching huge messages */
509 #define MAX_MESSAGE_SIZE_TO_CACHE _DBUS_ONE_MEGABYTE
510
511 /** Avoid caching too many messages */
512 #define MAX_MESSAGE_CACHE_SIZE    5
513
514 _DBUS_DEFINE_GLOBAL_LOCK (message_cache);
515 static DBusMessage *message_cache[MAX_MESSAGE_CACHE_SIZE];
516 static int message_cache_count = 0;
517 static dbus_bool_t message_cache_shutdown_registered = FALSE;
518
519 static void
520 dbus_message_cache_shutdown (void *data)
521 {
522   int i;
523
524   _DBUS_LOCK (message_cache);
525
526   i = 0;
527   while (i < MAX_MESSAGE_CACHE_SIZE)
528     {
529       if (message_cache[i])
530         dbus_message_finalize (message_cache[i]);
531
532       ++i;
533     }
534
535   message_cache_count = 0;
536   message_cache_shutdown_registered = FALSE;
537
538   _DBUS_UNLOCK (message_cache);
539 }
540
541 /**
542  * Tries to get a message from the message cache.  The retrieved
543  * message will have junk in it, so it still needs to be cleared out
544  * in dbus_message_new_empty_header()
545  *
546  * @returns the message, or #NULL if none cached
547  */
548 static DBusMessage*
549 dbus_message_get_cached (void)
550 {
551   DBusMessage *message;
552   int i;
553
554   message = NULL;
555
556   _DBUS_LOCK (message_cache);
557
558   _dbus_assert (message_cache_count >= 0);
559
560   if (message_cache_count == 0)
561     {
562       _DBUS_UNLOCK (message_cache);
563       return NULL;
564     }
565
566   /* This is not necessarily true unless count > 0, and
567    * message_cache is uninitialized until the shutdown is
568    * registered
569    */
570   _dbus_assert (message_cache_shutdown_registered);
571
572   i = 0;
573   while (i < MAX_MESSAGE_CACHE_SIZE)
574     {
575       if (message_cache[i])
576         {
577           message = message_cache[i];
578           message_cache[i] = NULL;
579           message_cache_count -= 1;
580           break;
581         }
582       ++i;
583     }
584   _dbus_assert (message_cache_count >= 0);
585   _dbus_assert (i < MAX_MESSAGE_CACHE_SIZE);
586   _dbus_assert (message != NULL);
587
588   _DBUS_UNLOCK (message_cache);
589
590   _dbus_assert (message->refcount.value == 0);
591   _dbus_assert (message->size_counters == NULL);
592
593   return message;
594 }
595
596 /**
597  * Tries to cache a message, otherwise finalize it.
598  *
599  * @param message the message
600  */
601 static void
602 dbus_message_cache_or_finalize (DBusMessage *message)
603 {
604   dbus_bool_t was_cached;
605   int i;
606   
607   _dbus_assert (message->refcount.value == 0);
608
609   /* This calls application code and has to be done first thing
610    * without holding the lock
611    */
612   _dbus_data_slot_list_clear (&message->slot_list);
613
614   _dbus_list_foreach (&message->size_counters,
615                       free_size_counter, message);
616   _dbus_list_clear (&message->size_counters);
617
618   was_cached = FALSE;
619
620   _DBUS_LOCK (message_cache);
621
622   if (!message_cache_shutdown_registered)
623     {
624       _dbus_assert (message_cache_count == 0);
625
626       if (!_dbus_register_shutdown_func (dbus_message_cache_shutdown, NULL))
627         goto out;
628
629       i = 0;
630       while (i < MAX_MESSAGE_CACHE_SIZE)
631         {
632           message_cache[i] = NULL;
633           ++i;
634         }
635
636       message_cache_shutdown_registered = TRUE;
637     }
638
639   _dbus_assert (message_cache_count >= 0);
640
641   if ((_dbus_string_get_length (&message->header.data) +
642        _dbus_string_get_length (&message->body)) >
643       MAX_MESSAGE_SIZE_TO_CACHE)
644     goto out;
645
646   if (message_cache_count >= MAX_MESSAGE_CACHE_SIZE)
647     goto out;
648
649   /* Find empty slot */
650   i = 0;
651   while (message_cache[i] != NULL)
652     ++i;
653
654   _dbus_assert (i < MAX_MESSAGE_CACHE_SIZE);
655
656   _dbus_assert (message_cache[i] == NULL);
657   message_cache[i] = message;
658   message_cache_count += 1;
659   was_cached = TRUE;
660
661  out:
662   _DBUS_UNLOCK (message_cache);
663
664   if (!was_cached)
665     dbus_message_finalize (message);
666 }
667
668 static DBusMessage*
669 dbus_message_new_empty_header (void)
670 {
671   DBusMessage *message;
672   dbus_bool_t from_cache;
673
674   message = dbus_message_get_cached ();
675
676   if (message != NULL)
677     {
678       from_cache = TRUE;
679     }
680   else
681     {
682       from_cache = FALSE;
683       message = dbus_new (DBusMessage, 1);
684       if (message == NULL)
685         return NULL;
686 #ifndef DBUS_DISABLE_CHECKS
687       message->generation = _dbus_current_generation;
688 #endif
689     }
690   
691   message->refcount.value = 1;
692   message->byte_order = DBUS_COMPILER_BYTE_ORDER;
693   message->locked = FALSE;
694   message->size_counters = NULL;
695   message->size_counter_delta = 0;
696   message->changed_stamp = 0;
697
698   if (!from_cache)
699     _dbus_data_slot_list_init (&message->slot_list);
700
701   if (from_cache)
702     {
703       _dbus_header_reinit (&message->header, message->byte_order);
704       _dbus_string_set_length (&message->body, 0);
705     }
706   else
707     {
708       if (!_dbus_header_init (&message->header, message->byte_order))
709         {
710           dbus_free (message);
711           return NULL;
712         }
713
714       if (!_dbus_string_init_preallocated (&message->body, 32))
715         {
716           _dbus_header_free (&message->header);
717           dbus_free (message);
718           return NULL;
719         }
720     }
721
722   return message;
723 }
724
725 /**
726  * Constructs a new message of the given message type.
727  * Types include #DBUS_MESSAGE_TYPE_METHOD_CALL,
728  * #DBUS_MESSAGE_TYPE_SIGNAL, and so forth.
729  *
730  * @param message_type type of message
731  * @returns new message or #NULL If no memory
732  */
733 DBusMessage*
734 dbus_message_new (int message_type)
735 {
736   DBusMessage *message;
737
738   _dbus_return_val_if_fail (message_type != DBUS_MESSAGE_TYPE_INVALID, NULL);
739
740   message = dbus_message_new_empty_header ();
741   if (message == NULL)
742     return NULL;
743
744   if (!_dbus_header_create (&message->header,
745                             message_type,
746                             NULL, NULL, NULL, NULL, NULL))
747     {
748       dbus_message_unref (message);
749       return NULL;
750     }
751
752   return message;
753 }
754
755 /**
756  * Constructs a new message to invoke a method on a remote
757  * object. Returns #NULL if memory can't be allocated for the
758  * message. The destination may be #NULL in which case no destination
759  * is set; this is appropriate when using D-BUS in a peer-to-peer
760  * context (no message bus). The interface may be #NULL, which means
761  * that if multiple methods with the given name exist it is undefined
762  * which one will be invoked.
763   *
764  * @param destination name that the message should be sent to or #NULL
765  * @param path object path the message should be sent to
766  * @param interface interface to invoke method on
767  * @param method method to invoke
768  *
769  * @returns a new DBusMessage, free with dbus_message_unref()
770  * @see dbus_message_unref()
771  */
772 DBusMessage*
773 dbus_message_new_method_call (const char *destination,
774                               const char *path,
775                               const char *interface,
776                               const char *method)
777 {
778   DBusMessage *message;
779
780   _dbus_return_val_if_fail (path != NULL, NULL);
781   _dbus_return_val_if_fail (method != NULL, NULL);
782   _dbus_return_val_if_fail (destination == NULL ||
783                             _dbus_check_is_valid_bus_name (destination), NULL);
784   _dbus_return_val_if_fail (_dbus_check_is_valid_path (path), NULL);
785   _dbus_return_val_if_fail (interface == NULL ||
786                             _dbus_check_is_valid_interface (interface), NULL);
787   _dbus_return_val_if_fail (_dbus_check_is_valid_member (method), NULL);
788
789   message = dbus_message_new_empty_header ();
790   if (message == NULL)
791     return NULL;
792
793   if (!_dbus_header_create (&message->header,
794                             DBUS_MESSAGE_TYPE_METHOD_CALL,
795                             destination, path, interface, method, NULL))
796     {
797       dbus_message_unref (message);
798       return NULL;
799     }
800
801   return message;
802 }
803
804 /**
805  * Constructs a message that is a reply to a method call. Returns
806  * #NULL if memory can't be allocated for the message.
807  *
808  * @param method_call the message which the created
809  * message is a reply to.
810  * @returns a new DBusMessage, free with dbus_message_unref()
811  * @see dbus_message_new_method_call(), dbus_message_unref()
812  */
813 DBusMessage*
814 dbus_message_new_method_return (DBusMessage *method_call)
815 {
816   DBusMessage *message;
817   const char *sender;
818
819   _dbus_return_val_if_fail (method_call != NULL, NULL);
820
821   sender = dbus_message_get_sender (method_call);
822
823   /* sender is allowed to be null here in peer-to-peer case */
824
825   message = dbus_message_new_empty_header ();
826   if (message == NULL)
827     return NULL;
828
829   if (!_dbus_header_create (&message->header,
830                             DBUS_MESSAGE_TYPE_METHOD_RETURN,
831                             sender, NULL, NULL, NULL, NULL))
832     {
833       dbus_message_unref (message);
834       return NULL;
835     }
836
837   dbus_message_set_no_reply (message, TRUE);
838
839   if (!dbus_message_set_reply_serial (message,
840                                       dbus_message_get_serial (method_call)))
841     {
842       dbus_message_unref (message);
843       return NULL;
844     }
845
846   return message;
847 }
848
849 /**
850  * Constructs a new message representing a signal emission. Returns
851  * #NULL if memory can't be allocated for the message.  A signal is
852  * identified by its originating interface, and the name of the
853  * signal.
854  *
855  * @param path the path to the object emitting the signal
856  * @param interface the interface the signal is emitted from
857  * @param name name of the signal
858  * @returns a new DBusMessage, free with dbus_message_unref()
859  * @see dbus_message_unref()
860  */
861 DBusMessage*
862 dbus_message_new_signal (const char *path,
863                          const char *interface,
864                          const char *name)
865 {
866   DBusMessage *message;
867
868   _dbus_return_val_if_fail (path != NULL, NULL);
869   _dbus_return_val_if_fail (interface != NULL, NULL);
870   _dbus_return_val_if_fail (name != NULL, NULL);
871   _dbus_return_val_if_fail (_dbus_check_is_valid_path (path), NULL);
872   _dbus_return_val_if_fail (_dbus_check_is_valid_interface (interface), NULL);
873   _dbus_return_val_if_fail (_dbus_check_is_valid_member (name), NULL);
874
875   message = dbus_message_new_empty_header ();
876   if (message == NULL)
877     return NULL;
878
879   if (!_dbus_header_create (&message->header,
880                             DBUS_MESSAGE_TYPE_SIGNAL,
881                             NULL, path, interface, name, NULL))
882     {
883       dbus_message_unref (message);
884       return NULL;
885     }
886
887   dbus_message_set_no_reply (message, TRUE);
888
889   return message;
890 }
891
892 /**
893  * Creates a new message that is an error reply to a certain message.
894  * Error replies are possible in response to method calls primarily.
895  *
896  * @param reply_to the original message
897  * @param error_name the error name
898  * @param error_message the error message string or #NULL for none
899  * @returns a new error message
900  */
901 DBusMessage*
902 dbus_message_new_error (DBusMessage *reply_to,
903                         const char  *error_name,
904                         const char  *error_message)
905 {
906   DBusMessage *message;
907   const char *sender;
908   DBusMessageIter iter;
909
910   _dbus_return_val_if_fail (reply_to != NULL, NULL);
911   _dbus_return_val_if_fail (error_name != NULL, NULL);
912   _dbus_return_val_if_fail (_dbus_check_is_valid_error_name (error_name), NULL);
913
914   sender = dbus_message_get_sender (reply_to);
915
916   /* sender may be NULL for non-message-bus case or
917    * when the message bus is dealing with an unregistered
918    * connection.
919    */
920   message = dbus_message_new_empty_header ();
921   if (message == NULL)
922     return NULL;
923
924   if (!_dbus_header_create (&message->header,
925                             DBUS_MESSAGE_TYPE_ERROR,
926                             sender, NULL, NULL, NULL, error_name))
927     {
928       dbus_message_unref (message);
929       return NULL;
930     }
931
932   dbus_message_set_no_reply (message, TRUE);
933
934   if (!dbus_message_set_reply_serial (message,
935                                       dbus_message_get_serial (reply_to)))
936     {
937       dbus_message_unref (message);
938       return NULL;
939     }
940
941   if (error_message != NULL)
942     {
943       dbus_message_iter_init_append (message, &iter);
944       if (!dbus_message_iter_append_basic (&iter,
945                                            DBUS_TYPE_STRING,
946                                            &error_message))
947         {
948           dbus_message_unref (message);
949           return NULL;
950         }
951     }
952
953   return message;
954 }
955
956 /**
957  * Creates a new message that is an error reply to a certain message.
958  * Error replies are possible in response to method calls primarily.
959  *
960  * @param reply_to the original message
961  * @param error_name the error name
962  * @param error_format the error message format as with printf
963  * @param ... format string arguments
964  * @returns a new error message
965  */
966 DBusMessage*
967 dbus_message_new_error_printf (DBusMessage *reply_to,
968                                const char  *error_name,
969                                const char  *error_format,
970                                ...)
971 {
972   va_list args;
973   DBusString str;
974   DBusMessage *message;
975
976   _dbus_return_val_if_fail (reply_to != NULL, NULL);
977   _dbus_return_val_if_fail (error_name != NULL, NULL);
978   _dbus_return_val_if_fail (_dbus_check_is_valid_error_name (error_name), NULL);
979
980   if (!_dbus_string_init (&str))
981     return NULL;
982
983   va_start (args, error_format);
984
985   if (_dbus_string_append_printf_valist (&str, error_format, args))
986     message = dbus_message_new_error (reply_to, error_name,
987                                       _dbus_string_get_const_data (&str));
988   else
989     message = NULL;
990
991   _dbus_string_free (&str);
992
993   va_end (args);
994
995   return message;
996 }
997
998
999 /**
1000  * Creates a new message that is an exact replica of the message
1001  * specified, except that its refcount is set to 1, its message serial
1002  * is reset to 0, and if the original message was "locked" (in the
1003  * outgoing message queue and thus not modifiable) the new message
1004  * will not be locked.
1005  *
1006  * @param message the message.
1007  * @returns the new message.
1008  */
1009 DBusMessage *
1010 dbus_message_copy (const DBusMessage *message)
1011 {
1012   DBusMessage *retval;
1013
1014   _dbus_return_val_if_fail (message != NULL, NULL);
1015
1016   retval = dbus_new0 (DBusMessage, 1);
1017   if (retval == NULL)
1018     return NULL;
1019
1020   retval->refcount.value = 1;
1021   retval->byte_order = message->byte_order;
1022   retval->locked = FALSE;
1023 #ifndef DBUS_DISABLE_CHECKS
1024   retval->generation = message->generation;
1025 #endif
1026
1027   if (!_dbus_header_copy (&message->header, &retval->header))
1028     {
1029       dbus_free (retval);
1030       return NULL;
1031     }
1032
1033   if (!_dbus_string_init_preallocated (&retval->body,
1034                                        _dbus_string_get_length (&message->body)))
1035     {
1036       _dbus_header_free (&retval->header);
1037       dbus_free (retval);
1038       return NULL;
1039     }
1040
1041   if (!_dbus_string_copy (&message->body, 0,
1042                           &retval->body, 0))
1043     goto failed_copy;
1044
1045   return retval;
1046
1047  failed_copy:
1048   _dbus_header_free (&retval->header);
1049   _dbus_string_free (&retval->body);
1050   dbus_free (retval);
1051
1052   return NULL;
1053 }
1054
1055
1056 /**
1057  * Increments the reference count of a DBusMessage.
1058  *
1059  * @param message The message
1060  * @returns the message
1061  * @see dbus_message_unref
1062  */
1063 DBusMessage *
1064 dbus_message_ref (DBusMessage *message)
1065 {
1066   dbus_int32_t old_refcount;
1067
1068   _dbus_return_val_if_fail (message != NULL, NULL);
1069   _dbus_return_val_if_fail (message->generation == _dbus_current_generation, NULL);
1070
1071   old_refcount = _dbus_atomic_inc (&message->refcount);
1072   _dbus_assert (old_refcount >= 1);
1073
1074   return message;
1075 }
1076
1077 /**
1078  * Decrements the reference count of a DBusMessage.
1079  *
1080  * @param message The message
1081  * @see dbus_message_ref
1082  */
1083 void
1084 dbus_message_unref (DBusMessage *message)
1085 {
1086  dbus_int32_t old_refcount;
1087
1088   _dbus_return_if_fail (message != NULL);
1089   _dbus_return_if_fail (message->generation == _dbus_current_generation);
1090
1091   old_refcount = _dbus_atomic_dec (&message->refcount);
1092
1093   _dbus_assert (old_refcount >= 0);
1094
1095   if (old_refcount == 1)
1096     {
1097       /* Calls application callbacks! */
1098       dbus_message_cache_or_finalize (message);
1099     }
1100 }
1101
1102 /**
1103  * Gets the type of a message. Types include
1104  * #DBUS_MESSAGE_TYPE_METHOD_CALL, #DBUS_MESSAGE_TYPE_METHOD_RETURN,
1105  * #DBUS_MESSAGE_TYPE_ERROR, #DBUS_MESSAGE_TYPE_SIGNAL, but other
1106  * types are allowed and all code must silently ignore messages of
1107  * unknown type. DBUS_MESSAGE_TYPE_INVALID will never be returned,
1108  * however.
1109  *
1110  *
1111  * @param message the message
1112  * @returns the type of the message
1113  */
1114 int
1115 dbus_message_get_type (DBusMessage *message)
1116 {
1117   _dbus_return_val_if_fail (message != NULL, DBUS_MESSAGE_TYPE_INVALID);
1118
1119   return _dbus_header_get_message_type (&message->header);
1120 }
1121
1122 /**
1123  * Appends fields to a message given a variable argument list. The
1124  * variable argument list should contain the type of each argument
1125  * followed by the value to append. Appendable types are basic types,
1126  * and arrays of fixed-length basic types. To append variable-length
1127  * basic types, or any more complex value, you have to use an iterator
1128  * rather than this function.
1129  *
1130  * To append a basic type, specify its type code followed by the
1131  * value. For example:
1132  *
1133  * @code
1134  * DBUS_TYPE_INT32, 42,
1135  * DBUS_TYPE_STRING, "Hello World"
1136  * @endcode
1137  * or
1138  * @code
1139  * dbus_int32_t val = 42;
1140  * DBUS_TYPE_INT32, val
1141  * @endcode
1142  *
1143  * Be sure that your provided value is the right size. For example, this
1144  * won't work:
1145  * @code
1146  * DBUS_TYPE_INT64, 42
1147  * @endcode
1148  * Because the "42" will be a 32-bit integer. You need to cast to
1149  * 64-bit.
1150  *
1151  * To append an array of fixed-length basic types, pass in the
1152  * DBUS_TYPE_ARRAY typecode, the element typecode, the address of
1153  * the array pointer, and a 32-bit integer giving the number of
1154  * elements in the array. So for example:
1155  * @code
1156  * const dbus_int32_t array[] = { 1, 2, 3 };
1157  * const dbus_int32_t *v_ARRAY = array;
1158  * DBUS_TYPE_ARRAY, DBUS_TYPE_INT32, &v_ARRAY, 3
1159  * @endcode
1160  *
1161  * @warning in C, given "int array[]", "&array == array" (the
1162  * comp.lang.c FAQ says otherwise, but gcc and the FAQ don't agree).
1163  * So if you're using an array instead of a pointer you have to create
1164  * a pointer variable, assign the array to it, then take the address
1165  * of the pointer variable. For strings it works to write
1166  * const char *array = "Hello" and then use &array though.
1167  *
1168  * The last argument to this function must be #DBUS_TYPE_INVALID,
1169  * marking the end of the argument list.
1170  *
1171  * @todo support DBUS_TYPE_STRUCT and DBUS_TYPE_VARIANT and complex arrays
1172  *
1173  * @todo If this fails due to lack of memory, the message is hosed and
1174  * you have to start over building the whole message.
1175  *
1176  * @param message the message
1177  * @param first_arg_type type of the first argument
1178  * @param ... value of first argument, list of additional type-value pairs
1179  * @returns #TRUE on success
1180  */
1181 dbus_bool_t
1182 dbus_message_append_args (DBusMessage *message,
1183                           int          first_arg_type,
1184                           ...)
1185 {
1186   dbus_bool_t retval;
1187   va_list var_args;
1188
1189   _dbus_return_val_if_fail (message != NULL, FALSE);
1190
1191   va_start (var_args, first_arg_type);
1192   retval = dbus_message_append_args_valist (message,
1193                                             first_arg_type,
1194                                             var_args);
1195   va_end (var_args);
1196
1197   return retval;
1198 }
1199
1200 /**
1201  * This function takes a va_list for use by language bindings.
1202  * It's otherwise the same as dbus_message_append_args().
1203  *
1204  * @todo for now, if this function fails due to OOM it will leave
1205  * the message half-written and you have to discard the message
1206  * and start over.
1207  *
1208  * @see dbus_message_append_args.
1209  * @param message the message
1210  * @param first_arg_type type of first argument
1211  * @param var_args value of first argument, then list of type/value pairs
1212  * @returns #TRUE on success
1213  */
1214 dbus_bool_t
1215 dbus_message_append_args_valist (DBusMessage *message,
1216                                  int          first_arg_type,
1217                                  va_list      var_args)
1218 {
1219   int type;
1220   DBusMessageIter iter;
1221
1222   _dbus_return_val_if_fail (message != NULL, FALSE);
1223
1224   type = first_arg_type;
1225
1226   dbus_message_iter_init_append (message, &iter);
1227
1228   while (type != DBUS_TYPE_INVALID)
1229     {
1230       if (_dbus_type_is_basic (type))
1231         {
1232           const DBusBasicValue *value;
1233           value = va_arg (var_args, const DBusBasicValue*);
1234
1235           if (!dbus_message_iter_append_basic (&iter,
1236                                                type,
1237                                                value))
1238             goto failed;
1239         }
1240       else if (type == DBUS_TYPE_ARRAY)
1241         {
1242           int element_type;
1243           const DBusBasicValue **value;
1244           int n_elements;
1245           DBusMessageIter array;
1246           char buf[2];
1247
1248           element_type = va_arg (var_args, int);
1249
1250 #ifndef DBUS_DISABLE_CHECKS
1251           if (!_dbus_type_is_fixed (element_type))
1252             {
1253               _dbus_warn ("arrays of %s can't be appended with %s for now\n",
1254                           _dbus_type_to_string (element_type),
1255                           _DBUS_FUNCTION_NAME);
1256               goto failed;
1257             }
1258 #endif
1259
1260           value = va_arg (var_args, const DBusBasicValue**);
1261           n_elements = va_arg (var_args, int);
1262
1263           buf[0] = element_type;
1264           buf[1] = '\0';
1265           if (!dbus_message_iter_open_container (&iter,
1266                                                  DBUS_TYPE_ARRAY,
1267                                                  buf,
1268                                                  &array))
1269             goto failed;
1270
1271           if (!dbus_message_iter_append_fixed_array (&array,
1272                                                      element_type,
1273                                                      value,
1274                                                      n_elements))
1275             goto failed;
1276
1277           if (!dbus_message_iter_close_container (&iter, &array))
1278             goto failed;
1279         }
1280 #ifndef DBUS_DISABLE_CHECKS
1281       else
1282         {
1283           _dbus_warn ("type %s isn't supported yet in %s\n",
1284                       _dbus_type_to_string (type), _DBUS_FUNCTION_NAME);
1285           goto failed;
1286         }
1287 #endif
1288
1289       type = va_arg (var_args, int);
1290     }
1291
1292   return TRUE;
1293
1294  failed:
1295   return FALSE;
1296 }
1297
1298 /**
1299  * Gets arguments from a message given a variable argument list.  The
1300  * supported types include those supported by
1301  * dbus_message_append_args(); that is, basic types and arrays of
1302  * fixed-length basic types.  The arguments are the same as they would
1303  * be for dbus_message_iter_get_basic() or
1304  * dbus_message_iter_get_fixed_array().
1305  *
1306  * In addition to those types, arrays of string, object path, and
1307  * signature are supported; but these are returned as allocated memory
1308  * and must be freed with dbus_free_string_array(), while the other
1309  * types are returned as const references.
1310  *
1311  * The variable argument list should contain the type of the argument
1312  * followed by a pointer to where the value should be stored. The list
1313  * is terminated with #DBUS_TYPE_INVALID.
1314  *
1315  * The returned values are constant; do not free them. They point
1316  * into the #DBusMessage.
1317  *
1318  * If the requested arguments are not present, or do not have the
1319  * requested types, then an error will be set.
1320  *
1321  * @todo support DBUS_TYPE_STRUCT and DBUS_TYPE_VARIANT and complex arrays
1322  *
1323  * @param message the message
1324  * @param error error to be filled in on failure
1325  * @param first_arg_type the first argument type
1326  * @param ... location for first argument value, then list of type-location pairs
1327  * @returns #FALSE if the error was set
1328  */
1329 dbus_bool_t
1330 dbus_message_get_args (DBusMessage     *message,
1331                        DBusError       *error,
1332                        int              first_arg_type,
1333                        ...)
1334 {
1335   dbus_bool_t retval;
1336   va_list var_args;
1337
1338   _dbus_return_val_if_fail (message != NULL, FALSE);
1339   _dbus_return_val_if_error_is_set (error, FALSE);
1340
1341   va_start (var_args, first_arg_type);
1342   retval = dbus_message_get_args_valist (message, error, first_arg_type, var_args);
1343   va_end (var_args);
1344
1345   return retval;
1346 }
1347
1348 /**
1349  * This function takes a va_list for use by language bindings. It is
1350  * otherwise the same as dbus_message_get_args().
1351  *
1352  * @see dbus_message_get_args
1353  * @param message the message
1354  * @param error error to be filled in
1355  * @param first_arg_type type of the first argument
1356  * @param var_args return location for first argument, followed by list of type/location pairs
1357  * @returns #FALSE if error was set
1358  */
1359 dbus_bool_t
1360 dbus_message_get_args_valist (DBusMessage     *message,
1361                               DBusError       *error,
1362                               int              first_arg_type,
1363                               va_list          var_args)
1364 {
1365   DBusMessageIter iter;
1366
1367   _dbus_return_val_if_fail (message != NULL, FALSE);
1368   _dbus_return_val_if_error_is_set (error, FALSE);
1369
1370   dbus_message_iter_init (message, &iter);
1371   return _dbus_message_iter_get_args_valist (&iter, error, first_arg_type, var_args);
1372 }
1373
1374 static void
1375 _dbus_message_iter_init_common (DBusMessage         *message,
1376                                 DBusMessageRealIter *real,
1377                                 int                  iter_type)
1378 {
1379   _dbus_assert (sizeof (DBusMessageRealIter) <= sizeof (DBusMessageIter));
1380
1381   /* Since the iterator will read or write who-knows-what from the
1382    * message, we need to get in the right byte order
1383    */
1384   ensure_byte_order (message);
1385   
1386   real->message = message;
1387   real->changed_stamp = message->changed_stamp;
1388   real->iter_type = iter_type;
1389   real->sig_refcount = 0;
1390 }
1391
1392 /**
1393  * Initializes a #DBusMessageIter for reading the arguments of the
1394  * message passed in.
1395  *
1396  * @param message the message
1397  * @param iter pointer to an iterator to initialize
1398  * @returns #FALSE if the message has no arguments
1399  */
1400 dbus_bool_t
1401 dbus_message_iter_init (DBusMessage     *message,
1402                         DBusMessageIter *iter)
1403 {
1404   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
1405   const DBusString *type_str;
1406   int type_pos;
1407
1408   _dbus_return_val_if_fail (message != NULL, FALSE);
1409   _dbus_return_val_if_fail (iter != NULL, FALSE);
1410
1411   get_const_signature (&message->header, &type_str, &type_pos);
1412
1413   _dbus_message_iter_init_common (message, real,
1414                                   DBUS_MESSAGE_ITER_TYPE_READER);
1415
1416   _dbus_type_reader_init (&real->u.reader,
1417                           message->byte_order,
1418                           type_str, type_pos,
1419                           &message->body,
1420                           0);
1421
1422   return _dbus_type_reader_get_current_type (&real->u.reader) != DBUS_TYPE_INVALID;
1423 }
1424
1425 #ifndef DBUS_DISABLE_CHECKS
1426 static dbus_bool_t
1427 _dbus_message_iter_check (DBusMessageRealIter *iter)
1428 {
1429   if (iter == NULL)
1430     {
1431       _dbus_warn ("dbus message iterator is NULL\n");
1432       return FALSE;
1433     }
1434
1435   if (iter->iter_type == DBUS_MESSAGE_ITER_TYPE_READER)
1436     {
1437       if (iter->u.reader.byte_order != iter->message->byte_order)
1438         {
1439           _dbus_warn ("dbus message changed byte order since iterator was created\n");
1440           return FALSE;
1441         }
1442       /* because we swap the message into compiler order when you init an iter */
1443       _dbus_assert (iter->u.reader.byte_order == DBUS_COMPILER_BYTE_ORDER);
1444     }
1445   else if (iter->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER)
1446     {
1447       if (iter->u.writer.byte_order != iter->message->byte_order)
1448         {
1449           _dbus_warn ("dbus message changed byte order since append iterator was created\n");
1450           return FALSE;
1451         }
1452       /* because we swap the message into compiler order when you init an iter */
1453       _dbus_assert (iter->u.writer.byte_order == DBUS_COMPILER_BYTE_ORDER);
1454     }
1455   else
1456     {
1457       _dbus_warn ("dbus message iterator looks uninitialized or corrupted\n");
1458       return FALSE;
1459     }
1460
1461   if (iter->changed_stamp != iter->message->changed_stamp)
1462     {
1463       _dbus_warn ("dbus message iterator invalid because the message has been modified (or perhaps the iterator is just uninitialized)\n");
1464       return FALSE;
1465     }
1466
1467   return TRUE;
1468 }
1469 #endif /* DBUS_DISABLE_CHECKS */
1470
1471 /**
1472  * Checks if an iterator has any more fields.
1473  *
1474  * @param iter the message iter
1475  * @returns #TRUE if there are more fields
1476  * following
1477  */
1478 dbus_bool_t
1479 dbus_message_iter_has_next (DBusMessageIter *iter)
1480 {
1481   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
1482
1483   _dbus_return_val_if_fail (_dbus_message_iter_check (real), FALSE);
1484   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_READER, FALSE);
1485
1486   return _dbus_type_reader_has_next (&real->u.reader);
1487 }
1488
1489 /**
1490  * Moves the iterator to the next field, if any. If there's no next
1491  * field, returns #FALSE. If the iterator moves forward, returns
1492  * #TRUE.
1493  *
1494  * @param iter the message iter
1495  * @returns #TRUE if the iterator was moved to the next field
1496  */
1497 dbus_bool_t
1498 dbus_message_iter_next (DBusMessageIter *iter)
1499 {
1500   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
1501
1502   _dbus_return_val_if_fail (_dbus_message_iter_check (real), FALSE);
1503   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_READER, FALSE);
1504
1505   return _dbus_type_reader_next (&real->u.reader);
1506 }
1507
1508 /**
1509  * Returns the argument type of the argument that the message iterator
1510  * points to. If the iterator is at the end of the message, returns
1511  * #DBUS_TYPE_INVALID. You can thus write a loop as follows:
1512  *
1513  * @code
1514  * dbus_message_iter_init (&iter);
1515  * while ((current_type = dbus_message_iter_get_arg_type (&iter)) != DBUS_TYPE_INVALID)
1516  *   dbus_message_iter_next (&iter);
1517  * @endcode
1518  *
1519  * @param iter the message iter
1520  * @returns the argument type
1521  */
1522 int
1523 dbus_message_iter_get_arg_type (DBusMessageIter *iter)
1524 {
1525   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
1526
1527   _dbus_return_val_if_fail (_dbus_message_iter_check (real), DBUS_TYPE_INVALID);
1528   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_READER, FALSE);
1529
1530   return _dbus_type_reader_get_current_type (&real->u.reader);
1531 }
1532
1533 /**
1534  * Returns the element type of the array that the message iterator
1535  * points to. Note that you need to check that the iterator points to
1536  * an array prior to using this function.
1537  *
1538  * @param iter the message iter
1539  * @returns the array element type
1540  */
1541 int
1542 dbus_message_iter_get_element_type (DBusMessageIter *iter)
1543 {
1544   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
1545
1546   _dbus_return_val_if_fail (_dbus_message_iter_check (real), DBUS_TYPE_INVALID);
1547   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_READER, DBUS_TYPE_INVALID);
1548   _dbus_return_val_if_fail (dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_ARRAY, DBUS_TYPE_INVALID);
1549
1550   return _dbus_type_reader_get_element_type (&real->u.reader);
1551 }
1552
1553 /**
1554  * Recurses into a container value when reading values from a message,
1555  * initializing a sub-iterator to use for traversing the child values
1556  * of the container.
1557  *
1558  * Note that this recurses into a value, not a type, so you can only
1559  * recurse if the value exists. The main implication of this is that
1560  * if you have for example an empty array of array of int32, you can
1561  * recurse into the outermost array, but it will have no values, so
1562  * you won't be able to recurse further. There's no array of int32 to
1563  * recurse into.
1564  *
1565  * @param iter the message iterator
1566  * @param sub the sub-iterator to initialize
1567  */
1568 void
1569 dbus_message_iter_recurse (DBusMessageIter  *iter,
1570                            DBusMessageIter  *sub)
1571 {
1572   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
1573   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
1574
1575   _dbus_return_if_fail (_dbus_message_iter_check (real));
1576   _dbus_return_if_fail (sub != NULL);
1577
1578   *real_sub = *real;
1579   _dbus_type_reader_recurse (&real->u.reader, &real_sub->u.reader);
1580 }
1581
1582 /**
1583  * Reads a basic-typed value from the message iterator.
1584  * Basic types are the non-containers such as integer and string.
1585  *
1586  * The value argument should be the address of a location to store
1587  * the returned value. So for int32 it should be a "dbus_int32_t*"
1588  * and for string a "const char**". The returned value is
1589  * by reference and should not be freed.
1590  *
1591  * All returned values are guaranteed to fit in 8 bytes. So you can
1592  * write code like this:
1593  *
1594  * @code
1595  * #ifdef DBUS_HAVE_INT64
1596  * dbus_uint64_t value;
1597  * int type;
1598  * dbus_message_iter_get_basic (&read_iter, &value);
1599  * type = dbus_message_iter_get_arg_type (&read_iter);
1600  * dbus_message_iter_append_basic (&write_iter, type, &value);
1601  * #endif
1602  * @endcode
1603  *
1604  * To avoid the #DBUS_HAVE_INT64 conditional, create a struct or
1605  * something that occupies at least 8 bytes, e.g. you could use a
1606  * struct with two int32 values in it. dbus_uint64_t is just one
1607  * example of a type that's large enough to hold any possible value.
1608  *
1609  * Be sure you have somehow checked that
1610  * dbus_message_iter_get_arg_type() matches the type you are
1611  * expecting, or you'll crash when you try to use an integer as a
1612  * string or something.
1613  *
1614  * @param iter the iterator
1615  * @param value location to store the value
1616  */
1617 void
1618 dbus_message_iter_get_basic (DBusMessageIter  *iter,
1619                              void             *value)
1620 {
1621   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
1622
1623   _dbus_return_if_fail (_dbus_message_iter_check (real));
1624   _dbus_return_if_fail (value != NULL);
1625
1626   _dbus_type_reader_read_basic (&real->u.reader,
1627                                 value);
1628 }
1629
1630 /**
1631  * Reads a block of fixed-length values from the message iterator.
1632  * Fixed-length values are those basic types that are not string-like,
1633  * such as integers, bool, double. The block read will be from the
1634  * current position in the array until the end of the array.
1635  *
1636  * The value argument should be the address of a location to store the
1637  * returned array. So for int32 it should be a "const dbus_int32_t**"
1638  * The returned value is by reference and should not be freed.
1639  *
1640  * @param iter the iterator
1641  * @param value location to store the block
1642  * @param n_elements number of elements in the block
1643  */
1644 void
1645 dbus_message_iter_get_fixed_array (DBusMessageIter  *iter,
1646                                    void             *value,
1647                                    int              *n_elements)
1648 {
1649   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
1650
1651   _dbus_return_if_fail (_dbus_message_iter_check (real));
1652   _dbus_return_if_fail (value != NULL);
1653   _dbus_return_if_fail (_dbus_type_is_fixed (_dbus_type_reader_get_element_type (&real->u.reader)));
1654
1655   _dbus_type_reader_read_fixed_multi (&real->u.reader,
1656                                       value, n_elements);
1657 }
1658
1659 /**
1660  * This function takes a va_list for use by language bindings and is
1661  * otherwise the same as dbus_message_iter_get_args().
1662  * dbus_message_get_args() is the place to go for complete
1663  * documentation.
1664  *
1665  * @see dbus_message_get_args
1666  * @param iter the message iter
1667  * @param error error to be filled in
1668  * @param first_arg_type type of the first argument
1669  * @param var_args return location for first argument, followed by list of type/location pairs
1670  * @returns #FALSE if error was set
1671  */
1672 dbus_bool_t
1673 _dbus_message_iter_get_args_valist (DBusMessageIter *iter,
1674                                     DBusError       *error,
1675                                     int              first_arg_type,
1676                                     va_list          var_args)
1677 {
1678   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
1679   int spec_type, msg_type, i;
1680   dbus_bool_t retval;
1681
1682   _dbus_assert (_dbus_message_iter_check (real));
1683
1684   retval = FALSE;
1685
1686   spec_type = first_arg_type;
1687   i = 0;
1688
1689   while (spec_type != DBUS_TYPE_INVALID)
1690     {
1691       msg_type = dbus_message_iter_get_arg_type (iter);
1692
1693       if (msg_type != spec_type)
1694         {
1695           dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
1696                           "Argument %d is specified to be of type \"%s\", but "
1697                           "is actually of type \"%s\"\n", i,
1698                           _dbus_type_to_string (spec_type),
1699                           _dbus_type_to_string (msg_type));
1700
1701           goto out;
1702         }
1703
1704       if (_dbus_type_is_basic (spec_type))
1705         {
1706           DBusBasicValue *ptr;
1707
1708           ptr = va_arg (var_args, DBusBasicValue*);
1709
1710           _dbus_assert (ptr != NULL);
1711
1712           _dbus_type_reader_read_basic (&real->u.reader,
1713                                         ptr);
1714         }
1715       else if (spec_type == DBUS_TYPE_ARRAY)
1716         {
1717           int element_type;
1718           int spec_element_type;
1719           const DBusBasicValue **ptr;
1720           int *n_elements_p;
1721           DBusTypeReader array;
1722
1723           spec_element_type = va_arg (var_args, int);
1724           element_type = _dbus_type_reader_get_element_type (&real->u.reader);
1725
1726           if (spec_element_type != element_type)
1727             {
1728               dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
1729                               "Argument %d is specified to be an array of \"%s\", but "
1730                               "is actually an array of \"%s\"\n",
1731                               i,
1732                               _dbus_type_to_string (spec_element_type),
1733                               _dbus_type_to_string (element_type));
1734
1735               goto out;
1736             }
1737
1738           if (_dbus_type_is_fixed (spec_element_type))
1739             {
1740               ptr = va_arg (var_args, const DBusBasicValue**);
1741               n_elements_p = va_arg (var_args, int*);
1742
1743               _dbus_assert (ptr != NULL);
1744               _dbus_assert (n_elements_p != NULL);
1745
1746               _dbus_type_reader_recurse (&real->u.reader, &array);
1747
1748               _dbus_type_reader_read_fixed_multi (&array,
1749                                                   ptr, n_elements_p);
1750             }
1751           else if (spec_element_type == DBUS_TYPE_STRING ||
1752                    spec_element_type == DBUS_TYPE_SIGNATURE ||
1753                    spec_element_type == DBUS_TYPE_OBJECT_PATH)
1754             {
1755               char ***str_array_p;
1756               int i;
1757               char **str_array;
1758
1759               str_array_p = va_arg (var_args, char***);
1760               n_elements_p = va_arg (var_args, int*);
1761
1762               _dbus_assert (str_array_p != NULL);
1763               _dbus_assert (n_elements_p != NULL);
1764
1765               /* Count elements in the array */
1766               _dbus_type_reader_recurse (&real->u.reader, &array);
1767
1768               i = 0;
1769               if (_dbus_type_reader_has_next (&array))
1770                 {
1771                   while (_dbus_type_reader_next (&array))
1772                     ++i;
1773                 }
1774
1775               str_array = dbus_new0 (char*, i + 1);
1776               if (str_array == NULL)
1777                 {
1778                   _DBUS_SET_OOM (error);
1779                   goto out;
1780                 }
1781
1782               /* Now go through and dup each string */
1783               _dbus_type_reader_recurse (&real->u.reader, &array);
1784
1785               i = 0;
1786               if (_dbus_type_reader_has_next (&array))
1787                 {
1788                   do
1789                     {
1790                       const char *s;
1791                       _dbus_type_reader_read_basic (&array,
1792                                                     &s);
1793
1794                       str_array[i] = _dbus_strdup (s);
1795                       if (str_array[i] == NULL)
1796                         {
1797                           dbus_free_string_array (str_array);
1798                           _DBUS_SET_OOM (error);
1799                           goto out;
1800                         }
1801
1802                       ++i;
1803                     }
1804                   while (_dbus_type_reader_next (&array));
1805                 }
1806
1807               *str_array_p = str_array;
1808               *n_elements_p = i;
1809             }
1810 #ifndef DBUS_DISABLE_CHECKS
1811           else
1812             {
1813               _dbus_warn ("you can't read arrays of container types (struct, variant, array) with %s for now\n",
1814                           _DBUS_FUNCTION_NAME);
1815               goto out;
1816             }
1817 #endif
1818         }
1819 #ifndef DBUS_DISABLE_CHECKS
1820       else
1821         {
1822           _dbus_warn ("you can only read arrays and basic types with %s for now\n",
1823                       _DBUS_FUNCTION_NAME);
1824           goto out;
1825         }
1826 #endif
1827
1828       spec_type = va_arg (var_args, int);
1829       if (!_dbus_type_reader_next (&real->u.reader) && spec_type != DBUS_TYPE_INVALID)
1830         {
1831           dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
1832                           "Message has only %d arguments, but more were expected", i);
1833           goto out;
1834         }
1835
1836       i++;
1837     }
1838
1839   retval = TRUE;
1840
1841  out:
1842
1843   return retval;
1844 }
1845
1846 /**
1847  * Initializes a #DBusMessageIter for appending arguments to the end
1848  * of a message.
1849  *
1850  * @todo If appending any of the arguments fails due to lack of
1851  * memory, generally the message is hosed and you have to start over
1852  * building the whole message.
1853  *
1854  * @param message the message
1855  * @param iter pointer to an iterator to initialize
1856  */
1857 void
1858 dbus_message_iter_init_append (DBusMessage     *message,
1859                                DBusMessageIter *iter)
1860 {
1861   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
1862
1863   _dbus_return_if_fail (message != NULL);
1864   _dbus_return_if_fail (iter != NULL);
1865
1866   _dbus_message_iter_init_common (message, real,
1867                                   DBUS_MESSAGE_ITER_TYPE_WRITER);
1868
1869   /* We create the signature string and point iterators at it "on demand"
1870    * when a value is actually appended. That means that init() never fails
1871    * due to OOM.
1872    */
1873   _dbus_type_writer_init_types_delayed (&real->u.writer,
1874                                         message->byte_order,
1875                                         &message->body,
1876                                         _dbus_string_get_length (&message->body));
1877 }
1878
1879 /**
1880  * Creates a temporary signature string containing the current
1881  * signature, stores it in the iterator, and points the iterator to
1882  * the end of it. Used any time we write to the message.
1883  *
1884  * @param real an iterator without a type_str
1885  * @returns #FALSE if no memory
1886  */
1887 static dbus_bool_t
1888 _dbus_message_iter_open_signature (DBusMessageRealIter *real)
1889 {
1890   DBusString *str;
1891   const DBusString *current_sig;
1892   int current_sig_pos;
1893
1894   _dbus_assert (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
1895
1896   if (real->u.writer.type_str != NULL)
1897     {
1898       _dbus_assert (real->sig_refcount > 0);
1899       real->sig_refcount += 1;
1900       return TRUE;
1901     }
1902
1903   str = dbus_new (DBusString, 1);
1904   if (str == NULL)
1905     return FALSE;
1906
1907   if (!_dbus_header_get_field_raw (&real->message->header,
1908                                    DBUS_HEADER_FIELD_SIGNATURE,
1909                                    &current_sig, &current_sig_pos))
1910     current_sig = NULL;
1911
1912   if (current_sig)
1913     {
1914       int current_len;
1915
1916       current_len = _dbus_string_get_byte (current_sig, current_sig_pos);
1917       current_sig_pos += 1; /* move on to sig data */
1918
1919       if (!_dbus_string_init_preallocated (str, current_len + 4))
1920         {
1921           dbus_free (str);
1922           return FALSE;
1923         }
1924
1925       if (!_dbus_string_copy_len (current_sig, current_sig_pos, current_len,
1926                                   str, 0))
1927         {
1928           _dbus_string_free (str);
1929           dbus_free (str);
1930           return FALSE;
1931         }
1932     }
1933   else
1934     {
1935       if (!_dbus_string_init_preallocated (str, 4))
1936         {
1937           dbus_free (str);
1938           return FALSE;
1939         }
1940     }
1941
1942   real->sig_refcount = 1;
1943
1944   _dbus_type_writer_add_types (&real->u.writer,
1945                                str, _dbus_string_get_length (str));
1946   return TRUE;
1947 }
1948
1949 /**
1950  * Sets the new signature as the message signature, frees the
1951  * signature string, and marks the iterator as not having a type_str
1952  * anymore. Frees the signature even if it fails, so you can't
1953  * really recover from failure. Kinda busted.
1954  *
1955  * @param real an iterator without a type_str
1956  * @returns #FALSE if no memory
1957  */
1958 static dbus_bool_t
1959 _dbus_message_iter_close_signature (DBusMessageRealIter *real)
1960 {
1961   DBusString *str;
1962   const char *v_STRING;
1963   dbus_bool_t retval;
1964
1965   _dbus_assert (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
1966   _dbus_assert (real->u.writer.type_str != NULL);
1967   _dbus_assert (real->sig_refcount > 0);
1968
1969   real->sig_refcount -= 1;
1970
1971   if (real->sig_refcount > 0)
1972     return TRUE;
1973   _dbus_assert (real->sig_refcount == 0);
1974
1975   retval = TRUE;
1976
1977   str = real->u.writer.type_str;
1978
1979   v_STRING = _dbus_string_get_const_data (str);
1980   if (!_dbus_header_set_field_basic (&real->message->header,
1981                                      DBUS_HEADER_FIELD_SIGNATURE,
1982                                      DBUS_TYPE_SIGNATURE,
1983                                      &v_STRING))
1984     retval = FALSE;
1985
1986   _dbus_type_writer_remove_types (&real->u.writer);
1987   _dbus_string_free (str);
1988   dbus_free (str);
1989
1990   return retval;
1991 }
1992
1993 #ifndef DBUS_DISABLE_CHECKS
1994 static dbus_bool_t
1995 _dbus_message_iter_append_check (DBusMessageRealIter *iter)
1996 {
1997   if (!_dbus_message_iter_check (iter))
1998     return FALSE;
1999
2000   if (iter->message->locked)
2001     {
2002       _dbus_warn ("dbus append iterator can't be used: message is locked (has already been sent)\n");
2003       return FALSE;
2004     }
2005
2006   return TRUE;
2007 }
2008 #endif /* DBUS_DISABLE_CHECKS */
2009
2010 /**
2011  * Appends a basic-typed value to the message. The basic types are the
2012  * non-container types such as integer and string.
2013  *
2014  * The "value" argument should be the address of a basic-typed value.
2015  * So for string, const char**. For integer, dbus_int32_t*.
2016  *
2017  * @todo If this fails due to lack of memory, the message is hosed and
2018  * you have to start over building the whole message.
2019  *
2020  * @param iter the append iterator
2021  * @param type the type of the value
2022  * @param value the address of the value
2023  * @returns #FALSE if not enough memory
2024  */
2025 dbus_bool_t
2026 dbus_message_iter_append_basic (DBusMessageIter *iter,
2027                                 int              type,
2028                                 const void      *value)
2029 {
2030   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2031   dbus_bool_t ret;
2032
2033   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
2034   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2035   _dbus_return_val_if_fail (_dbus_type_is_basic (type), FALSE);
2036   _dbus_return_val_if_fail (value != NULL, FALSE);
2037
2038   if (!_dbus_message_iter_open_signature (real))
2039     return FALSE;
2040
2041   ret = _dbus_type_writer_write_basic (&real->u.writer, type, value);
2042
2043   if (!_dbus_message_iter_close_signature (real))
2044     ret = FALSE;
2045
2046   return ret;
2047 }
2048
2049 /**
2050  * Appends a block of fixed-length values to an array. The
2051  * fixed-length types are all basic types that are not string-like. So
2052  * int32, double, bool, etc. You must call
2053  * dbus_message_iter_open_container() to open an array of values
2054  * before calling this function. You may call this function multiple
2055  * times (and intermixed with calls to
2056  * dbus_message_iter_append_basic()) for the same array.
2057  *
2058  * The "value" argument should be the address of the array.  So for
2059  * integer, "dbus_int32_t**" is expected for example.
2060  *
2061  * @warning in C, given "int array[]", "&array == array" (the
2062  * comp.lang.c FAQ says otherwise, but gcc and the FAQ don't agree).
2063  * So if you're using an array instead of a pointer you have to create
2064  * a pointer variable, assign the array to it, then take the address
2065  * of the pointer variable.
2066  * @code
2067  * const dbus_int32_t array[] = { 1, 2, 3 };
2068  * const dbus_int32_t *v_ARRAY = array;
2069  * if (!dbus_message_iter_append_fixed_array (&iter, DBUS_TYPE_INT32, &v_ARRAY, 3))
2070  *   fprintf (stderr, "No memory!\n");
2071  * @endcode
2072  * For strings it works to write const char *array = "Hello" and then
2073  * use &array though.
2074  *
2075  * @todo If this fails due to lack of memory, the message is hosed and
2076  * you have to start over building the whole message.
2077  *
2078  * @param iter the append iterator
2079  * @param element_type the type of the array elements
2080  * @param value the address of the array
2081  * @param n_elements the number of elements to append
2082  * @returns #FALSE if not enough memory
2083  */
2084 dbus_bool_t
2085 dbus_message_iter_append_fixed_array (DBusMessageIter *iter,
2086                                       int              element_type,
2087                                       const void      *value,
2088                                       int              n_elements)
2089 {
2090   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2091   dbus_bool_t ret;
2092
2093   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
2094   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2095   _dbus_return_val_if_fail (_dbus_type_is_fixed (element_type), FALSE);
2096   _dbus_return_val_if_fail (real->u.writer.container_type == DBUS_TYPE_ARRAY, FALSE);
2097   _dbus_return_val_if_fail (value != NULL, FALSE);
2098   _dbus_return_val_if_fail (n_elements >= 0, FALSE);
2099   _dbus_return_val_if_fail (n_elements <=
2100                             DBUS_MAXIMUM_ARRAY_LENGTH / _dbus_type_get_alignment (element_type),
2101                             FALSE);
2102
2103   ret = _dbus_type_writer_write_fixed_multi (&real->u.writer, element_type, value, n_elements);
2104
2105   return ret;
2106 }
2107
2108 /**
2109  * Appends a container-typed value to the message; you are required to
2110  * append the contents of the container using the returned
2111  * sub-iterator, and then call
2112  * dbus_message_iter_close_container(). Container types are for
2113  * example struct, variant, and array. For variants, the
2114  * contained_signature should be the type of the single value inside
2115  * the variant. For structs and dict entries, contained_signature
2116  * should be #NULL; it will be set to whatever types you write into
2117  * the struct.  For arrays, contained_signature should be the type of
2118  * the array elements.
2119  *
2120  * @todo If this fails due to lack of memory, the message is hosed and
2121  * you have to start over building the whole message.
2122  *
2123  * @param iter the append iterator
2124  * @param type the type of the value
2125  * @param contained_signature the type of container contents
2126  * @param sub sub-iterator to initialize
2127  * @returns #FALSE if not enough memory
2128  */
2129 dbus_bool_t
2130 dbus_message_iter_open_container (DBusMessageIter *iter,
2131                                   int              type,
2132                                   const char      *contained_signature,
2133                                   DBusMessageIter *sub)
2134 {
2135   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2136   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
2137   DBusString contained_str;
2138
2139   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
2140   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2141   _dbus_return_val_if_fail (_dbus_type_is_container (type), FALSE);
2142   _dbus_return_val_if_fail (sub != NULL, FALSE);
2143   _dbus_return_val_if_fail ((type == DBUS_TYPE_STRUCT &&
2144                              contained_signature == NULL) ||
2145                             (type == DBUS_TYPE_DICT_ENTRY &&
2146                              contained_signature == NULL) ||
2147                             contained_signature != NULL, FALSE);
2148   _dbus_return_val_if_fail (type != DBUS_TYPE_DICT_ENTRY ||
2149                             dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_ARRAY,
2150                             FALSE);
2151   
2152 #if 0
2153   /* FIXME this would fail if the contained_signature is a dict entry,
2154    * since dict entries are invalid signatures standalone (they must be in
2155    * an array)
2156    */
2157   _dbus_return_val_if_fail (contained_signature == NULL ||
2158                             _dbus_check_is_valid_signature (contained_signature));
2159 #endif
2160
2161   if (!_dbus_message_iter_open_signature (real))
2162     return FALSE;
2163
2164   _dbus_string_init_const (&contained_str, contained_signature);
2165
2166   *real_sub = *real;
2167   return _dbus_type_writer_recurse (&real->u.writer,
2168                                     type,
2169                                     &contained_str, 0,
2170                                     &real_sub->u.writer);
2171 }
2172
2173
2174 /**
2175  * Closes a container-typed value appended to the message; may write
2176  * out more information to the message known only after the entire
2177  * container is written, and may free resources created by
2178  * dbus_message_iter_open_container().
2179  *
2180  * @todo If this fails due to lack of memory, the message is hosed and
2181  * you have to start over building the whole message.
2182  *
2183  * @param iter the append iterator
2184  * @param sub sub-iterator to close
2185  * @returns #FALSE if not enough memory
2186  */
2187 dbus_bool_t
2188 dbus_message_iter_close_container (DBusMessageIter *iter,
2189                                    DBusMessageIter *sub)
2190 {
2191   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2192   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
2193   dbus_bool_t ret;
2194
2195   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
2196   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2197   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real_sub), FALSE);
2198   _dbus_return_val_if_fail (real_sub->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2199
2200   ret = _dbus_type_writer_unrecurse (&real->u.writer,
2201                                      &real_sub->u.writer);
2202
2203   if (!_dbus_message_iter_close_signature (real))
2204     ret = FALSE;
2205
2206   return ret;
2207 }
2208
2209 /**
2210  * Sets a flag indicating that the message does not want a reply; if
2211  * this flag is set, the other end of the connection may (but is not
2212  * required to) optimize by not sending method return or error
2213  * replies. If this flag is set, there is no way to know whether the
2214  * message successfully arrived at the remote end. Normally you know a
2215  * message was received when you receive the reply to it.
2216  *
2217  * @param message the message
2218  * @param no_reply #TRUE if no reply is desired
2219  */
2220 void
2221 dbus_message_set_no_reply (DBusMessage *message,
2222                            dbus_bool_t  no_reply)
2223 {
2224   _dbus_return_if_fail (message != NULL);
2225   _dbus_return_if_fail (!message->locked);
2226
2227   _dbus_header_toggle_flag (&message->header,
2228                             DBUS_HEADER_FLAG_NO_REPLY_EXPECTED,
2229                             no_reply);
2230 }
2231
2232 /**
2233  * Returns #TRUE if the message does not expect
2234  * a reply.
2235  *
2236  * @param message the message
2237  * @returns #TRUE if the message sender isn't waiting for a reply
2238  */
2239 dbus_bool_t
2240 dbus_message_get_no_reply (DBusMessage *message)
2241 {
2242   _dbus_return_val_if_fail (message != NULL, FALSE);
2243
2244   return _dbus_header_get_flag (&message->header,
2245                                 DBUS_HEADER_FLAG_NO_REPLY_EXPECTED);
2246 }
2247
2248 /**
2249  * Sets a flag indicating that an owner for the destination name will
2250  * be automatically started before the message is delivered. When this
2251  * flag is set, the message is held until a name owner finishes
2252  * starting up, or fails to start up. In case of failure, the reply
2253  * will be an error.
2254  *
2255  * @param message the message
2256  * @param auto_start #TRUE if auto-starting is desired
2257  */
2258 void
2259 dbus_message_set_auto_start (DBusMessage *message,
2260                              dbus_bool_t  auto_start)
2261 {
2262   _dbus_return_if_fail (message != NULL);
2263   _dbus_return_if_fail (!message->locked);
2264
2265   _dbus_header_toggle_flag (&message->header,
2266                             DBUS_HEADER_FLAG_NO_AUTO_START,
2267                             !auto_start);
2268 }
2269
2270 /**
2271  * Returns #TRUE if the message will cause an owner for
2272  * destination name to be auto-started.
2273  *
2274  * @param message the message
2275  * @returns #TRUE if the message will use auto-start
2276  */
2277 dbus_bool_t
2278 dbus_message_get_auto_start (DBusMessage *message)
2279 {
2280   _dbus_return_val_if_fail (message != NULL, FALSE);
2281
2282   return !_dbus_header_get_flag (&message->header,
2283                                  DBUS_HEADER_FLAG_NO_AUTO_START);
2284 }
2285
2286
2287 /**
2288  * Sets the object path this message is being sent to (for
2289  * DBUS_MESSAGE_TYPE_METHOD_CALL) or the one a signal is being
2290  * emitted from (for DBUS_MESSAGE_TYPE_SIGNAL).
2291  *
2292  * @param message the message
2293  * @param object_path the path or #NULL to unset
2294  * @returns #FALSE if not enough memory
2295  */
2296 dbus_bool_t
2297 dbus_message_set_path (DBusMessage   *message,
2298                        const char    *object_path)
2299 {
2300   _dbus_return_val_if_fail (message != NULL, FALSE);
2301   _dbus_return_val_if_fail (!message->locked, FALSE);
2302   _dbus_return_val_if_fail (object_path == NULL ||
2303                             _dbus_check_is_valid_path (object_path),
2304                             FALSE);
2305
2306   return set_or_delete_string_field (message,
2307                                      DBUS_HEADER_FIELD_PATH,
2308                                      DBUS_TYPE_OBJECT_PATH,
2309                                      object_path);
2310 }
2311
2312 /**
2313  * Gets the object path this message is being sent to (for
2314  * DBUS_MESSAGE_TYPE_METHOD_CALL) or being emitted from (for
2315  * DBUS_MESSAGE_TYPE_SIGNAL). Returns #NULL if none.
2316  *
2317  * @param message the message
2318  * @returns the path (should not be freed) or #NULL
2319  */
2320 const char*
2321 dbus_message_get_path (DBusMessage   *message)
2322 {
2323   const char *v;
2324
2325   _dbus_return_val_if_fail (message != NULL, NULL);
2326
2327   v = NULL; /* in case field doesn't exist */
2328   _dbus_header_get_field_basic (&message->header,
2329                                 DBUS_HEADER_FIELD_PATH,
2330                                 DBUS_TYPE_OBJECT_PATH,
2331                                 &v);
2332   return v;
2333 }
2334
2335 /**
2336  * Gets the object path this message is being sent to
2337  * (for DBUS_MESSAGE_TYPE_METHOD_CALL) or being emitted
2338  * from (for DBUS_MESSAGE_TYPE_SIGNAL) in a decomposed
2339  * format (one array element per path component).
2340  * Free the returned array with dbus_free_string_array().
2341  *
2342  * An empty but non-NULL path array means the path "/".
2343  * So the path "/foo/bar" becomes { "foo", "bar", NULL }
2344  * and the path "/" becomes { NULL }.
2345  *
2346  * @todo this could be optimized by using the len from the message
2347  * instead of calling strlen() again
2348  *
2349  * @param message the message
2350  * @param path place to store allocated array of path components; #NULL set here if no path field exists
2351  * @returns #FALSE if no memory to allocate the array
2352  */
2353 dbus_bool_t
2354 dbus_message_get_path_decomposed (DBusMessage   *message,
2355                                   char        ***path)
2356 {
2357   const char *v;
2358
2359   _dbus_return_val_if_fail (message != NULL, FALSE);
2360   _dbus_return_val_if_fail (path != NULL, FALSE);
2361
2362   *path = NULL;
2363
2364   v = dbus_message_get_path (message);
2365   if (v != NULL)
2366     {
2367       if (!_dbus_decompose_path (v, strlen (v),
2368                                  path, NULL))
2369         return FALSE;
2370     }
2371   return TRUE;
2372 }
2373
2374 /**
2375  * Sets the interface this message is being sent to
2376  * (for DBUS_MESSAGE_TYPE_METHOD_CALL) or
2377  * the interface a signal is being emitted from
2378  * (for DBUS_MESSAGE_TYPE_SIGNAL).
2379  *
2380  * @param message the message
2381  * @param interface the interface or #NULL to unset
2382  * @returns #FALSE if not enough memory
2383  */
2384 dbus_bool_t
2385 dbus_message_set_interface (DBusMessage  *message,
2386                             const char   *interface)
2387 {
2388   _dbus_return_val_if_fail (message != NULL, FALSE);
2389   _dbus_return_val_if_fail (!message->locked, FALSE);
2390   _dbus_return_val_if_fail (interface == NULL ||
2391                             _dbus_check_is_valid_interface (interface),
2392                             FALSE);
2393
2394   return set_or_delete_string_field (message,
2395                                      DBUS_HEADER_FIELD_INTERFACE,
2396                                      DBUS_TYPE_STRING,
2397                                      interface);
2398 }
2399
2400 /**
2401  * Gets the interface this message is being sent to
2402  * (for DBUS_MESSAGE_TYPE_METHOD_CALL) or being emitted
2403  * from (for DBUS_MESSAGE_TYPE_SIGNAL).
2404  * The interface name is fully-qualified (namespaced).
2405  * Returns #NULL if none.
2406  *
2407  * @param message the message
2408  * @returns the message interface (should not be freed) or #NULL
2409  */
2410 const char*
2411 dbus_message_get_interface (DBusMessage *message)
2412 {
2413   const char *v;
2414
2415   _dbus_return_val_if_fail (message != NULL, NULL);
2416
2417   v = NULL; /* in case field doesn't exist */
2418   _dbus_header_get_field_basic (&message->header,
2419                                 DBUS_HEADER_FIELD_INTERFACE,
2420                                 DBUS_TYPE_STRING,
2421                                 &v);
2422   return v;
2423 }
2424
2425 /**
2426  * Sets the interface member being invoked
2427  * (DBUS_MESSAGE_TYPE_METHOD_CALL) or emitted
2428  * (DBUS_MESSAGE_TYPE_SIGNAL).
2429  * The interface name is fully-qualified (namespaced).
2430  *
2431  * @param message the message
2432  * @param member the member or #NULL to unset
2433  * @returns #FALSE if not enough memory
2434  */
2435 dbus_bool_t
2436 dbus_message_set_member (DBusMessage  *message,
2437                          const char   *member)
2438 {
2439   _dbus_return_val_if_fail (message != NULL, FALSE);
2440   _dbus_return_val_if_fail (!message->locked, FALSE);
2441   _dbus_return_val_if_fail (member == NULL ||
2442                             _dbus_check_is_valid_member (member),
2443                             FALSE);
2444
2445   return set_or_delete_string_field (message,
2446                                      DBUS_HEADER_FIELD_MEMBER,
2447                                      DBUS_TYPE_STRING,
2448                                      member);
2449 }
2450
2451 /**
2452  * Gets the interface member being invoked
2453  * (DBUS_MESSAGE_TYPE_METHOD_CALL) or emitted
2454  * (DBUS_MESSAGE_TYPE_SIGNAL). Returns #NULL if none.
2455  *
2456  * @param message the message
2457  * @returns the member name (should not be freed) or #NULL
2458  */
2459 const char*
2460 dbus_message_get_member (DBusMessage *message)
2461 {
2462   const char *v;
2463
2464   _dbus_return_val_if_fail (message != NULL, NULL);
2465
2466   v = NULL; /* in case field doesn't exist */
2467   _dbus_header_get_field_basic (&message->header,
2468                                 DBUS_HEADER_FIELD_MEMBER,
2469                                 DBUS_TYPE_STRING,
2470                                 &v);
2471   return v;
2472 }
2473
2474 /**
2475  * Sets the name of the error (DBUS_MESSAGE_TYPE_ERROR).
2476  * The name is fully-qualified (namespaced).
2477  *
2478  * @param message the message
2479  * @param error_name the name or #NULL to unset
2480  * @returns #FALSE if not enough memory
2481  */
2482 dbus_bool_t
2483 dbus_message_set_error_name (DBusMessage  *message,
2484                              const char   *error_name)
2485 {
2486   _dbus_return_val_if_fail (message != NULL, FALSE);
2487   _dbus_return_val_if_fail (!message->locked, FALSE);
2488   _dbus_return_val_if_fail (error_name == NULL ||
2489                             _dbus_check_is_valid_error_name (error_name),
2490                             FALSE);
2491
2492   return set_or_delete_string_field (message,
2493                                      DBUS_HEADER_FIELD_ERROR_NAME,
2494                                      DBUS_TYPE_STRING,
2495                                      error_name);
2496 }
2497
2498 /**
2499  * Gets the error name (DBUS_MESSAGE_TYPE_ERROR only)
2500  * or #NULL if none.
2501  *
2502  * @param message the message
2503  * @returns the error name (should not be freed) or #NULL
2504  */
2505 const char*
2506 dbus_message_get_error_name (DBusMessage *message)
2507 {
2508   const char *v;
2509
2510   _dbus_return_val_if_fail (message != NULL, NULL);
2511
2512   v = NULL; /* in case field doesn't exist */
2513   _dbus_header_get_field_basic (&message->header,
2514                                 DBUS_HEADER_FIELD_ERROR_NAME,
2515                                 DBUS_TYPE_STRING,
2516                                 &v);
2517   return v;
2518 }
2519
2520 /**
2521  * Sets the message's destination. The destination is the name of
2522  * another connection on the bus and may be either the unique name
2523  * assigned by the bus to each connection, or a well-known name
2524  * specified in advance.
2525  *
2526  * @param message the message
2527  * @param destination the destination name or #NULL to unset
2528  * @returns #FALSE if not enough memory
2529  */
2530 dbus_bool_t
2531 dbus_message_set_destination (DBusMessage  *message,
2532                               const char   *destination)
2533 {
2534   _dbus_return_val_if_fail (message != NULL, FALSE);
2535   _dbus_return_val_if_fail (!message->locked, FALSE);
2536   _dbus_return_val_if_fail (destination == NULL ||
2537                             _dbus_check_is_valid_bus_name (destination),
2538                             FALSE);
2539
2540   return set_or_delete_string_field (message,
2541                                      DBUS_HEADER_FIELD_DESTINATION,
2542                                      DBUS_TYPE_STRING,
2543                                      destination);
2544 }
2545
2546 /**
2547  * Gets the destination of a message or #NULL if there is none set.
2548  *
2549  * @param message the message
2550  * @returns the message destination (should not be freed) or #NULL
2551  */
2552 const char*
2553 dbus_message_get_destination (DBusMessage *message)
2554 {
2555   const char *v;
2556
2557   _dbus_return_val_if_fail (message != NULL, NULL);
2558
2559   v = NULL; /* in case field doesn't exist */
2560   _dbus_header_get_field_basic (&message->header,
2561                                 DBUS_HEADER_FIELD_DESTINATION,
2562                                 DBUS_TYPE_STRING,
2563                                 &v);
2564   return v;
2565 }
2566
2567 /**
2568  * Sets the message sender.
2569  *
2570  * @param message the message
2571  * @param sender the sender or #NULL to unset
2572  * @returns #FALSE if not enough memory
2573  */
2574 dbus_bool_t
2575 dbus_message_set_sender (DBusMessage  *message,
2576                          const char   *sender)
2577 {
2578   _dbus_return_val_if_fail (message != NULL, FALSE);
2579   _dbus_return_val_if_fail (!message->locked, FALSE);
2580   _dbus_return_val_if_fail (sender == NULL ||
2581                             _dbus_check_is_valid_bus_name (sender),
2582                             FALSE);
2583
2584   return set_or_delete_string_field (message,
2585                                      DBUS_HEADER_FIELD_SENDER,
2586                                      DBUS_TYPE_STRING,
2587                                      sender);
2588 }
2589
2590 /**
2591  * Gets the unique name of the connection which originated this
2592  * message, or #NULL if unknown or inapplicable. The sender is filled
2593  * in by the message bus.
2594  *
2595  * @param message the message
2596  * @returns the unique name of the sender or #NULL
2597  */
2598 const char*
2599 dbus_message_get_sender (DBusMessage *message)
2600 {
2601   const char *v;
2602
2603   _dbus_return_val_if_fail (message != NULL, NULL);
2604
2605   v = NULL; /* in case field doesn't exist */
2606   _dbus_header_get_field_basic (&message->header,
2607                                 DBUS_HEADER_FIELD_SENDER,
2608                                 DBUS_TYPE_STRING,
2609                                 &v);
2610   return v;
2611 }
2612
2613 /**
2614  * Gets the type signature of the message, i.e. the arguments in the
2615  * message payload. The signature includes only "in" arguments for
2616  * #DBUS_MESSAGE_TYPE_METHOD_CALL and only "out" arguments for
2617  * #DBUS_MESSAGE_TYPE_METHOD_RETURN, so is slightly different from
2618  * what you might expect (it does not include the signature of the
2619  * entire C++-style method).
2620  *
2621  * The signature is a string made up of type codes such as
2622  * #DBUS_TYPE_INT32. The string is terminated with nul (nul is also
2623  * the value of #DBUS_TYPE_INVALID).
2624  *
2625  * @param message the message
2626  * @returns the type signature
2627  */
2628 const char*
2629 dbus_message_get_signature (DBusMessage *message)
2630 {
2631   const DBusString *type_str;
2632   int type_pos;
2633
2634   _dbus_return_val_if_fail (message != NULL, NULL);
2635
2636   get_const_signature (&message->header, &type_str, &type_pos);
2637
2638   return _dbus_string_get_const_data_len (type_str, type_pos, 0);
2639 }
2640
2641 static dbus_bool_t
2642 _dbus_message_has_type_interface_member (DBusMessage *message,
2643                                          int          type,
2644                                          const char  *interface,
2645                                          const char  *member)
2646 {
2647   const char *n;
2648
2649   _dbus_assert (message != NULL);
2650   _dbus_assert (interface != NULL);
2651   _dbus_assert (member != NULL);
2652
2653   if (dbus_message_get_type (message) != type)
2654     return FALSE;
2655
2656   /* Optimize by checking the short member name first
2657    * instead of the longer interface name
2658    */
2659
2660   n = dbus_message_get_member (message);
2661
2662   if (n && strcmp (n, member) == 0)
2663     {
2664       n = dbus_message_get_interface (message);
2665
2666       if (n == NULL || strcmp (n, interface) == 0)
2667         return TRUE;
2668     }
2669
2670   return FALSE;
2671 }
2672
2673 /**
2674  * Checks whether the message is a method call with the given
2675  * interface and member fields.  If the message is not
2676  * #DBUS_MESSAGE_TYPE_METHOD_CALL, or has a different interface or
2677  * member field, returns #FALSE. If the interface field is missing,
2678  * then it will be assumed equal to the provided interface.  The D-BUS
2679  * protocol allows method callers to leave out the interface name.
2680  *
2681  * @param message the message
2682  * @param interface the name to check (must not be #NULL)
2683  * @param method the name to check (must not be #NULL)
2684  *
2685  * @returns #TRUE if the message is the specified method call
2686  */
2687 dbus_bool_t
2688 dbus_message_is_method_call (DBusMessage *message,
2689                              const char  *interface,
2690                              const char  *method)
2691 {
2692   _dbus_return_val_if_fail (message != NULL, FALSE);
2693   _dbus_return_val_if_fail (interface != NULL, FALSE);
2694   _dbus_return_val_if_fail (method != NULL, FALSE);
2695   /* don't check that interface/method are valid since it would be
2696    * expensive, and not catch many common errors
2697    */
2698
2699   return _dbus_message_has_type_interface_member (message,
2700                                                   DBUS_MESSAGE_TYPE_METHOD_CALL,
2701                                                   interface, method);
2702 }
2703
2704 /**
2705  * Checks whether the message is a signal with the given interface and
2706  * member fields.  If the message is not #DBUS_MESSAGE_TYPE_SIGNAL, or
2707  * has a different interface or member field, returns #FALSE.  If the
2708  * interface field in the message is missing, it is assumed to match
2709  * any interface you pass in to this function.
2710  *
2711  * @param message the message
2712  * @param interface the name to check (must not be #NULL)
2713  * @param signal_name the name to check (must not be #NULL)
2714  *
2715  * @returns #TRUE if the message is the specified signal
2716  */
2717 dbus_bool_t
2718 dbus_message_is_signal (DBusMessage *message,
2719                         const char  *interface,
2720                         const char  *signal_name)
2721 {
2722   _dbus_return_val_if_fail (message != NULL, FALSE);
2723   _dbus_return_val_if_fail (interface != NULL, FALSE);
2724   _dbus_return_val_if_fail (signal_name != NULL, FALSE);
2725   /* don't check that interface/name are valid since it would be
2726    * expensive, and not catch many common errors
2727    */
2728
2729   return _dbus_message_has_type_interface_member (message,
2730                                                   DBUS_MESSAGE_TYPE_SIGNAL,
2731                                                   interface, signal_name);
2732 }
2733
2734 /**
2735  * Checks whether the message is an error reply with the given error
2736  * name.  If the message is not #DBUS_MESSAGE_TYPE_ERROR, or has a
2737  * different name, returns #FALSE.
2738  *
2739  * @param message the message
2740  * @param error_name the name to check (must not be #NULL)
2741  *
2742  * @returns #TRUE if the message is the specified error
2743  */
2744 dbus_bool_t
2745 dbus_message_is_error (DBusMessage *message,
2746                        const char  *error_name)
2747 {
2748   const char *n;
2749
2750   _dbus_return_val_if_fail (message != NULL, FALSE);
2751   _dbus_return_val_if_fail (error_name != NULL, FALSE);
2752   /* don't check that error_name is valid since it would be expensive,
2753    * and not catch many common errors
2754    */
2755
2756   if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_ERROR)
2757     return FALSE;
2758
2759   n = dbus_message_get_error_name (message);
2760
2761   if (n && strcmp (n, error_name) == 0)
2762     return TRUE;
2763   else
2764     return FALSE;
2765 }
2766
2767 /**
2768  * Checks whether the message was sent to the given name.  If the
2769  * message has no destination specified or has a different
2770  * destination, returns #FALSE.
2771  *
2772  * @param message the message
2773  * @param name the name to check (must not be #NULL)
2774  *
2775  * @returns #TRUE if the message has the given destination name
2776  */
2777 dbus_bool_t
2778 dbus_message_has_destination (DBusMessage  *message,
2779                               const char   *name)
2780 {
2781   const char *s;
2782
2783   _dbus_return_val_if_fail (message != NULL, FALSE);
2784   _dbus_return_val_if_fail (name != NULL, FALSE);
2785   /* don't check that name is valid since it would be expensive, and
2786    * not catch many common errors
2787    */
2788
2789   s = dbus_message_get_destination (message);
2790
2791   if (s && strcmp (s, name) == 0)
2792     return TRUE;
2793   else
2794     return FALSE;
2795 }
2796
2797 /**
2798  * Checks whether the message has the given unique name as its sender.
2799  * If the message has no sender specified or has a different sender,
2800  * returns #FALSE. Note that a peer application will always have the
2801  * unique name of the connection as the sender. So you can't use this
2802  * function to see whether a sender owned a well-known name.
2803  *
2804  * Messages from the bus itself will have #DBUS_SERVICE_ORG_FREEDESKTOP_DBUS
2805  * as the sender.
2806  *
2807  * @param message the message
2808  * @param name the name to check (must not be #NULL)
2809  *
2810  * @returns #TRUE if the message has the given sender
2811  */
2812 dbus_bool_t
2813 dbus_message_has_sender (DBusMessage  *message,
2814                          const char   *name)
2815 {
2816   const char *s;
2817
2818   _dbus_return_val_if_fail (message != NULL, FALSE);
2819   _dbus_return_val_if_fail (name != NULL, FALSE);
2820   /* don't check that name is valid since it would be expensive, and
2821    * not catch many common errors
2822    */
2823
2824   s = dbus_message_get_sender (message);
2825
2826   if (s && strcmp (s, name) == 0)
2827     return TRUE;
2828   else
2829     return FALSE;
2830 }
2831
2832 /**
2833  * Checks whether the message has the given signature; see
2834  * dbus_message_get_signature() for more details on what the signature
2835  * looks like.
2836  *
2837  * @param message the message
2838  * @param signature typecode array
2839  * @returns #TRUE if message has the given signature
2840 */
2841 dbus_bool_t
2842 dbus_message_has_signature (DBusMessage   *message,
2843                             const char    *signature)
2844 {
2845   const char *s;
2846
2847   _dbus_return_val_if_fail (message != NULL, FALSE);
2848   _dbus_return_val_if_fail (signature != NULL, FALSE);
2849   /* don't check that signature is valid since it would be expensive,
2850    * and not catch many common errors
2851    */
2852
2853   s = dbus_message_get_signature (message);
2854
2855   if (s && strcmp (s, signature) == 0)
2856     return TRUE;
2857   else
2858     return FALSE;
2859 }
2860
2861 /**
2862  * Sets a #DBusError based on the contents of the given
2863  * message. The error is only set if the message
2864  * is an error message, as in DBUS_MESSAGE_TYPE_ERROR.
2865  * The name of the error is set to the name of the message,
2866  * and the error message is set to the first argument
2867  * if the argument exists and is a string.
2868  *
2869  * The return value indicates whether the error was set (the error is
2870  * set if and only if the message is an error message).  So you can
2871  * check for an error reply and convert it to DBusError in one go:
2872  * @code
2873  *  if (dbus_set_error_from_message (error, reply))
2874  *    return error;
2875  *  else
2876  *    process reply;
2877  * @endcode
2878  *
2879  * @param error the error to set
2880  * @param message the message to set it from
2881  * @returns #TRUE if dbus_message_get_is_error() returns #TRUE for the message
2882  */
2883 dbus_bool_t
2884 dbus_set_error_from_message (DBusError   *error,
2885                              DBusMessage *message)
2886 {
2887   const char *str;
2888
2889   _dbus_return_val_if_fail (message != NULL, FALSE);
2890   _dbus_return_val_if_error_is_set (error, FALSE);
2891
2892   if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_ERROR)
2893     return FALSE;
2894
2895   str = NULL;
2896   dbus_message_get_args (message, NULL,
2897                          DBUS_TYPE_STRING, &str,
2898                          DBUS_TYPE_INVALID);
2899
2900   dbus_set_error (error, dbus_message_get_error_name (message),
2901                   str ? "%s" : NULL, str);
2902
2903   return TRUE;
2904 }
2905
2906 /** @} */
2907
2908 /**
2909  * @addtogroup DBusMessageInternals
2910  *
2911  * @{
2912  */
2913
2914 /**
2915  * The initial buffer size of the message loader.
2916  *
2917  * @todo this should be based on min header size plus some average
2918  * body size, or something. Or rather, the min header size only, if we
2919  * want to try to read only the header, store that in a DBusMessage,
2920  * then read only the body and store that, etc., depends on
2921  * how we optimize _dbus_message_loader_get_buffer() and what
2922  * the exact message format is.
2923  */
2924 #define INITIAL_LOADER_DATA_LEN 32
2925
2926 /**
2927  * Creates a new message loader. Returns #NULL if memory can't
2928  * be allocated.
2929  *
2930  * @returns new loader, or #NULL.
2931  */
2932 DBusMessageLoader*
2933 _dbus_message_loader_new (void)
2934 {
2935   DBusMessageLoader *loader;
2936
2937   loader = dbus_new0 (DBusMessageLoader, 1);
2938   if (loader == NULL)
2939     return NULL;
2940   
2941   loader->refcount = 1;
2942
2943   loader->corrupted = FALSE;
2944   loader->corruption_reason = DBUS_VALID;
2945   
2946   /* Try to cap message size at something that won't *totally* hose
2947    * the system if we have a couple of them.
2948    */
2949   loader->max_message_size = _DBUS_ONE_MEGABYTE * 32;
2950
2951   if (!_dbus_string_init (&loader->data))
2952     {
2953       dbus_free (loader);
2954       return NULL;
2955     }
2956
2957   /* preallocate the buffer for speed, ignore failure */
2958   _dbus_string_set_length (&loader->data, INITIAL_LOADER_DATA_LEN);
2959   _dbus_string_set_length (&loader->data, 0);
2960
2961   return loader;
2962 }
2963
2964 /**
2965  * Increments the reference count of the loader.
2966  *
2967  * @param loader the loader.
2968  * @returns the loader
2969  */
2970 DBusMessageLoader *
2971 _dbus_message_loader_ref (DBusMessageLoader *loader)
2972 {
2973   loader->refcount += 1;
2974
2975   return loader;
2976 }
2977
2978 /**
2979  * Decrements the reference count of the loader and finalizes the
2980  * loader when the count reaches zero.
2981  *
2982  * @param loader the loader.
2983  */
2984 void
2985 _dbus_message_loader_unref (DBusMessageLoader *loader)
2986 {
2987   loader->refcount -= 1;
2988   if (loader->refcount == 0)
2989     {
2990       _dbus_list_foreach (&loader->messages,
2991                           (DBusForeachFunction) dbus_message_unref,
2992                           NULL);
2993       _dbus_list_clear (&loader->messages);
2994       _dbus_string_free (&loader->data);
2995       dbus_free (loader);
2996     }
2997 }
2998
2999 /**
3000  * Gets the buffer to use for reading data from the network.  Network
3001  * data is read directly into an allocated buffer, which is then used
3002  * in the DBusMessage, to avoid as many extra memcpy's as possible.
3003  * The buffer must always be returned immediately using
3004  * _dbus_message_loader_return_buffer(), even if no bytes are
3005  * successfully read.
3006  *
3007  * @todo this function can be a lot more clever. For example
3008  * it can probably always return a buffer size to read exactly
3009  * the body of the next message, thus avoiding any memory wastage
3010  * or reallocs.
3011  *
3012  * @todo we need to enforce a max length on strings in header fields.
3013  *
3014  * @param loader the message loader.
3015  * @param buffer the buffer
3016  */
3017 void
3018 _dbus_message_loader_get_buffer (DBusMessageLoader  *loader,
3019                                  DBusString        **buffer)
3020 {
3021   _dbus_assert (!loader->buffer_outstanding);
3022
3023   *buffer = &loader->data;
3024
3025   loader->buffer_outstanding = TRUE;
3026 }
3027
3028 /**
3029  * Returns a buffer obtained from _dbus_message_loader_get_buffer(),
3030  * indicating to the loader how many bytes of the buffer were filled
3031  * in. This function must always be called, even if no bytes were
3032  * successfully read.
3033  *
3034  * @param loader the loader.
3035  * @param buffer the buffer.
3036  * @param bytes_read number of bytes that were read into the buffer.
3037  */
3038 void
3039 _dbus_message_loader_return_buffer (DBusMessageLoader  *loader,
3040                                     DBusString         *buffer,
3041                                     int                 bytes_read)
3042 {
3043   _dbus_assert (loader->buffer_outstanding);
3044   _dbus_assert (buffer == &loader->data);
3045
3046   loader->buffer_outstanding = FALSE;
3047 }
3048
3049 /*
3050  * FIXME when we move the header out of the buffer, that memmoves all
3051  * buffered messages. Kind of crappy.
3052  *
3053  * Also we copy the header and body, which is kind of crappy.  To
3054  * avoid this, we have to allow header and body to be in a single
3055  * memory block, which is good for messages we read and bad for
3056  * messages we are creating. But we could move_len() the buffer into
3057  * this single memory block, and move_len() will just swap the buffers
3058  * if you're moving the entire buffer replacing the dest string.
3059  *
3060  * We could also have the message loader tell the transport how many
3061  * bytes to read; so it would first ask for some arbitrary number like
3062  * 256, then if the message was incomplete it would use the
3063  * header/body len to ask for exactly the size of the message (or
3064  * blocks the size of a typical kernel buffer for the socket). That
3065  * way we don't get trailing bytes in the buffer that have to be
3066  * memmoved. Though I suppose we also don't have a chance of reading a
3067  * bunch of small messages at once, so the optimization may be stupid.
3068  *
3069  * Another approach would be to keep a "start" index into
3070  * loader->data and only delete it occasionally, instead of after
3071  * each message is loaded.
3072  *
3073  * load_message() returns FALSE if not enough memory OR the loader was corrupted
3074  */
3075 static dbus_bool_t
3076 load_message (DBusMessageLoader *loader,
3077               DBusMessage       *message,
3078               int                byte_order,
3079               int                fields_array_len,
3080               int                header_len,
3081               int                body_len)
3082 {
3083   dbus_bool_t oom;
3084   DBusValidity validity;
3085   const DBusString *type_str;
3086   int type_pos;
3087   DBusValidationMode mode;
3088
3089   mode = DBUS_VALIDATION_MODE_DATA_IS_UNTRUSTED;
3090   
3091   oom = FALSE;
3092
3093 #if 0
3094   _dbus_verbose_bytes_of_string (&loader->data, 0, header_len /* + body_len */);
3095 #endif
3096
3097   /* 1. VALIDATE AND COPY OVER HEADER */
3098   _dbus_assert (_dbus_string_get_length (&message->header.data) == 0);
3099   _dbus_assert ((header_len + body_len) <= _dbus_string_get_length (&loader->data));
3100
3101   if (!_dbus_header_load (&message->header,
3102                           mode,
3103                           &validity,
3104                           byte_order,
3105                           fields_array_len,
3106                           header_len,
3107                           body_len,
3108                           &loader->data, 0,
3109                           _dbus_string_get_length (&loader->data)))
3110     {
3111       _dbus_verbose ("Failed to load header for new message code %d\n", validity);
3112       if (validity == DBUS_VALID)
3113         oom = TRUE;
3114       else
3115         {
3116           loader->corrupted = TRUE;
3117           loader->corruption_reason = validity;
3118         }
3119       goto failed;
3120     }
3121
3122   _dbus_assert (validity == DBUS_VALID);
3123
3124   message->byte_order = byte_order;
3125
3126   /* 2. VALIDATE BODY */
3127   if (mode != DBUS_VALIDATION_MODE_WE_TRUST_THIS_DATA_ABSOLUTELY)
3128     {
3129       get_const_signature (&message->header, &type_str, &type_pos);
3130       
3131       /* Because the bytes_remaining arg is NULL, this validates that the
3132        * body is the right length
3133        */
3134       validity = _dbus_validate_body_with_reason (type_str,
3135                                                   type_pos,
3136                                                   byte_order,
3137                                                   NULL,
3138                                                   &loader->data,
3139                                                   header_len,
3140                                                   body_len);
3141       if (validity != DBUS_VALID)
3142         {
3143           _dbus_verbose ("Failed to validate message body code %d\n", validity);
3144
3145           loader->corrupted = TRUE;
3146           loader->corruption_reason = validity;
3147           
3148           goto failed;
3149         }
3150     }
3151
3152   /* 3. COPY OVER BODY AND QUEUE MESSAGE */
3153
3154   if (!_dbus_list_append (&loader->messages, message))
3155     {
3156       _dbus_verbose ("Failed to append new message to loader queue\n");
3157       oom = TRUE;
3158       goto failed;
3159     }
3160
3161   _dbus_assert (_dbus_string_get_length (&message->body) == 0);
3162   _dbus_assert (_dbus_string_get_length (&loader->data) >=
3163                 (header_len + body_len));
3164
3165   if (!_dbus_string_copy_len (&loader->data, header_len, body_len, &message->body, 0))
3166     {
3167       _dbus_verbose ("Failed to move body into new message\n");
3168       oom = TRUE;
3169       goto failed;
3170     }
3171
3172   _dbus_string_delete (&loader->data, 0, header_len + body_len);
3173
3174   _dbus_assert (_dbus_string_get_length (&message->header.data) == header_len);
3175   _dbus_assert (_dbus_string_get_length (&message->body) == body_len);
3176
3177   _dbus_verbose ("Loaded message %p\n", message);
3178
3179   _dbus_assert (!oom);
3180   _dbus_assert (!loader->corrupted);
3181   _dbus_assert (loader->messages != NULL);
3182   _dbus_assert (_dbus_list_find_last (&loader->messages, message) != NULL);
3183
3184   return TRUE;
3185
3186  failed:
3187
3188   /* Clean up */
3189
3190   /* does nothing if the message isn't in the list */
3191   _dbus_list_remove_last (&loader->messages, message);
3192   
3193   if (oom)
3194     _dbus_assert (!loader->corrupted);
3195   else
3196     _dbus_assert (loader->corrupted);
3197
3198   _dbus_verbose_bytes_of_string (&loader->data, 0, _dbus_string_get_length (&loader->data));
3199
3200   return FALSE;
3201 }
3202
3203 /**
3204  * Converts buffered data into messages, if we have enough data.  If
3205  * we don't have enough data, does nothing.
3206  *
3207  * @todo we need to check that the proper named header fields exist
3208  * for each message type.
3209  *
3210  * @todo If a message has unknown type, we should probably eat it
3211  * right here rather than passing it out to applications.  However
3212  * it's not an error to see messages of unknown type.
3213  *
3214  * @param loader the loader.
3215  * @returns #TRUE if we had enough memory to finish.
3216  */
3217 dbus_bool_t
3218 _dbus_message_loader_queue_messages (DBusMessageLoader *loader)
3219 {
3220   while (!loader->corrupted &&
3221          _dbus_string_get_length (&loader->data) >= DBUS_MINIMUM_HEADER_SIZE)
3222     {
3223       DBusValidity validity;
3224       int byte_order, fields_array_len, header_len, body_len;
3225
3226       if (_dbus_header_have_message_untrusted (loader->max_message_size,
3227                                                &validity,
3228                                                &byte_order,
3229                                                &fields_array_len,
3230                                                &header_len,
3231                                                &body_len,
3232                                                &loader->data, 0,
3233                                                _dbus_string_get_length (&loader->data)))
3234         {
3235           DBusMessage *message;
3236
3237           _dbus_assert (validity == DBUS_VALID);
3238
3239           message = dbus_message_new_empty_header ();
3240           if (message == NULL)
3241             return FALSE;
3242
3243           if (!load_message (loader, message,
3244                              byte_order, fields_array_len,
3245                              header_len, body_len))
3246             {
3247               dbus_message_unref (message);
3248               /* load_message() returns false if corrupted or OOM; if
3249                * corrupted then return TRUE for not OOM
3250                */
3251               return loader->corrupted;
3252             }
3253
3254           _dbus_assert (loader->messages != NULL);
3255           _dbus_assert (_dbus_list_find_last (&loader->messages, message) != NULL);
3256         }
3257       else
3258         {
3259           _dbus_verbose ("Initial peek at header says we don't have a whole message yet, or data broken with invalid code %d\n",
3260                          validity);
3261           if (validity != DBUS_VALID)
3262             {
3263               loader->corrupted = TRUE;
3264               loader->corruption_reason = validity;
3265             }
3266           return TRUE;
3267         }
3268     }
3269
3270   return TRUE;
3271 }
3272
3273 /**
3274  * Peeks at first loaded message, returns #NULL if no messages have
3275  * been queued.
3276  *
3277  * @param loader the loader.
3278  * @returns the next message, or #NULL if none.
3279  */
3280 DBusMessage*
3281 _dbus_message_loader_peek_message (DBusMessageLoader *loader)
3282 {
3283   if (loader->messages)
3284     return loader->messages->data;
3285   else
3286     return NULL;
3287 }
3288
3289 /**
3290  * Pops a loaded message (passing ownership of the message
3291  * to the caller). Returns #NULL if no messages have been
3292  * queued.
3293  *
3294  * @param loader the loader.
3295  * @returns the next message, or #NULL if none.
3296  */
3297 DBusMessage*
3298 _dbus_message_loader_pop_message (DBusMessageLoader *loader)
3299 {
3300   return _dbus_list_pop_first (&loader->messages);
3301 }
3302
3303 /**
3304  * Pops a loaded message inside a list link (passing ownership of the
3305  * message and link to the caller). Returns #NULL if no messages have
3306  * been loaded.
3307  *
3308  * @param loader the loader.
3309  * @returns the next message link, or #NULL if none.
3310  */
3311 DBusList*
3312 _dbus_message_loader_pop_message_link (DBusMessageLoader *loader)
3313 {
3314   return _dbus_list_pop_first_link (&loader->messages);
3315 }
3316
3317 /**
3318  * Returns a popped message link, used to undo a pop.
3319  *
3320  * @param loader the loader
3321  * @param link the link with a message in it
3322  */
3323 void
3324 _dbus_message_loader_putback_message_link (DBusMessageLoader  *loader,
3325                                            DBusList           *link)
3326 {
3327   _dbus_list_prepend_link (&loader->messages, link);
3328 }
3329
3330 /**
3331  * Checks whether the loader is confused due to bad data.
3332  * If messages are received that are invalid, the
3333  * loader gets confused and gives up permanently.
3334  * This state is called "corrupted."
3335  *
3336  * @param loader the loader
3337  * @returns #TRUE if the loader is hosed.
3338  */
3339 dbus_bool_t
3340 _dbus_message_loader_get_is_corrupted (DBusMessageLoader *loader)
3341 {
3342   _dbus_assert ((loader->corrupted && loader->corruption_reason != DBUS_VALID) ||
3343                 (!loader->corrupted && loader->corruption_reason == DBUS_VALID));
3344   return loader->corrupted;
3345 }
3346
3347 /**
3348  * Sets the maximum size message we allow.
3349  *
3350  * @param loader the loader
3351  * @param size the max message size in bytes
3352  */
3353 void
3354 _dbus_message_loader_set_max_message_size (DBusMessageLoader  *loader,
3355                                            long                size)
3356 {
3357   if (size > DBUS_MAXIMUM_MESSAGE_LENGTH)
3358     {
3359       _dbus_verbose ("clamping requested max message size %ld to %d\n",
3360                      size, DBUS_MAXIMUM_MESSAGE_LENGTH);
3361       size = DBUS_MAXIMUM_MESSAGE_LENGTH;
3362     }
3363   loader->max_message_size = size;
3364 }
3365
3366 /**
3367  * Gets the maximum allowed message size in bytes.
3368  *
3369  * @param loader the loader
3370  * @returns max size in bytes
3371  */
3372 long
3373 _dbus_message_loader_get_max_message_size (DBusMessageLoader  *loader)
3374 {
3375   return loader->max_message_size;
3376 }
3377
3378 static DBusDataSlotAllocator slot_allocator;
3379 _DBUS_DEFINE_GLOBAL_LOCK (message_slots);
3380
3381 /**
3382  * Allocates an integer ID to be used for storing application-specific
3383  * data on any DBusMessage. The allocated ID may then be used
3384  * with dbus_message_set_data() and dbus_message_get_data().
3385  * The passed-in slot must be initialized to -1, and is filled in
3386  * with the slot ID. If the passed-in slot is not -1, it's assumed
3387  * to be already allocated, and its refcount is incremented.
3388  *
3389  * The allocated slot is global, i.e. all DBusMessage objects will
3390  * have a slot with the given integer ID reserved.
3391  *
3392  * @param slot_p address of a global variable storing the slot
3393  * @returns #FALSE on failure (no memory)
3394  */
3395 dbus_bool_t
3396 dbus_message_allocate_data_slot (dbus_int32_t *slot_p)
3397 {
3398   return _dbus_data_slot_allocator_alloc (&slot_allocator,
3399                                           _DBUS_LOCK_NAME (message_slots),
3400                                           slot_p);
3401 }
3402
3403 /**
3404  * Deallocates a global ID for message data slots.
3405  * dbus_message_get_data() and dbus_message_set_data() may no
3406  * longer be used with this slot.  Existing data stored on existing
3407  * DBusMessage objects will be freed when the message is
3408  * finalized, but may not be retrieved (and may only be replaced if
3409  * someone else reallocates the slot).  When the refcount on the
3410  * passed-in slot reaches 0, it is set to -1.
3411  *
3412  * @param slot_p address storing the slot to deallocate
3413  */
3414 void
3415 dbus_message_free_data_slot (dbus_int32_t *slot_p)
3416 {
3417   _dbus_return_if_fail (*slot_p >= 0);
3418
3419   _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
3420 }
3421
3422 /**
3423  * Stores a pointer on a DBusMessage, along
3424  * with an optional function to be used for freeing
3425  * the data when the data is set again, or when
3426  * the message is finalized. The slot number
3427  * must have been allocated with dbus_message_allocate_data_slot().
3428  *
3429  * @param message the message
3430  * @param slot the slot number
3431  * @param data the data to store
3432  * @param free_data_func finalizer function for the data
3433  * @returns #TRUE if there was enough memory to store the data
3434  */
3435 dbus_bool_t
3436 dbus_message_set_data (DBusMessage     *message,
3437                        dbus_int32_t     slot,
3438                        void            *data,
3439                        DBusFreeFunction free_data_func)
3440 {
3441   DBusFreeFunction old_free_func;
3442   void *old_data;
3443   dbus_bool_t retval;
3444
3445   _dbus_return_val_if_fail (message != NULL, FALSE);
3446   _dbus_return_val_if_fail (slot >= 0, FALSE);
3447
3448   retval = _dbus_data_slot_list_set (&slot_allocator,
3449                                      &message->slot_list,
3450                                      slot, data, free_data_func,
3451                                      &old_free_func, &old_data);
3452
3453   if (retval)
3454     {
3455       /* Do the actual free outside the message lock */
3456       if (old_free_func)
3457         (* old_free_func) (old_data);
3458     }
3459
3460   return retval;
3461 }
3462
3463 /**
3464  * Retrieves data previously set with dbus_message_set_data().
3465  * The slot must still be allocated (must not have been freed).
3466  *
3467  * @param message the message
3468  * @param slot the slot to get data from
3469  * @returns the data, or #NULL if not found
3470  */
3471 void*
3472 dbus_message_get_data (DBusMessage   *message,
3473                        dbus_int32_t   slot)
3474 {
3475   void *res;
3476
3477   _dbus_return_val_if_fail (message != NULL, NULL);
3478
3479   res = _dbus_data_slot_list_get (&slot_allocator,
3480                                   &message->slot_list,
3481                                   slot);
3482
3483   return res;
3484 }
3485
3486 /**
3487  * Utility function to convert a machine-readable (not translated)
3488  * string into a D-BUS message type.
3489  *
3490  * @code
3491  *   "method_call"    -> DBUS_MESSAGE_TYPE_METHOD_CALL
3492  *   "method_return"  -> DBUS_MESSAGE_TYPE_METHOD_RETURN
3493  *   "signal"         -> DBUS_MESSAGE_TYPE_SIGNAL
3494  *   "error"          -> DBUS_MESSAGE_TYPE_ERROR
3495  *   anything else    -> DBUS_MESSAGE_TYPE_INVALID
3496  * @endcode
3497  *
3498  */
3499 int
3500 dbus_message_type_from_string (const char *type_str)
3501 {
3502   if (strcmp (type_str, "method_call") == 0)
3503     return DBUS_MESSAGE_TYPE_METHOD_CALL;
3504   if (strcmp (type_str, "method_return") == 0)
3505     return DBUS_MESSAGE_TYPE_METHOD_RETURN;
3506   else if (strcmp (type_str, "signal") == 0)
3507     return DBUS_MESSAGE_TYPE_SIGNAL;
3508   else if (strcmp (type_str, "error") == 0)
3509     return DBUS_MESSAGE_TYPE_ERROR;
3510   else
3511     return DBUS_MESSAGE_TYPE_INVALID;
3512 }
3513
3514 /**
3515  * Utility function to convert a D-BUS message type into a
3516  * machine-readable string (not translated).
3517  *
3518  * @code
3519  *   DBUS_MESSAGE_TYPE_METHOD_CALL    -> "method_call"
3520  *   DBUS_MESSAGE_TYPE_METHOD_RETURN  -> "method_return"
3521  *   DBUS_MESSAGE_TYPE_SIGNAL         -> "signal"
3522  *   DBUS_MESSAGE_TYPE_ERROR          -> "error"
3523  *   DBUS_MESSAGE_TYPE_INVALID        -> "invalid"
3524  * @endcode
3525  *
3526  */
3527 const char *
3528 dbus_message_type_to_string (int type)
3529 {
3530   switch (type)
3531     {
3532     case DBUS_MESSAGE_TYPE_METHOD_CALL:
3533       return "method_call";
3534     case DBUS_MESSAGE_TYPE_METHOD_RETURN:
3535       return "method_return";
3536     case DBUS_MESSAGE_TYPE_SIGNAL:
3537       return "signal";
3538     case DBUS_MESSAGE_TYPE_ERROR:
3539       return "error";
3540     default:
3541       return "invalid";
3542     }
3543 }
3544
3545 /** @} */
3546
3547 /* tests in dbus-message-util.c */