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