* dbus/dbus-marshal-validate.h: Added a new validation
[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  * Gets the object path this message is being sent to
2435  * (for DBUS_MESSAGE_TYPE_METHOD_CALL) or being emitted
2436  * from (for DBUS_MESSAGE_TYPE_SIGNAL) in a decomposed
2437  * format (one array element per path component).
2438  * Free the returned array with dbus_free_string_array().
2439  *
2440  * An empty but non-NULL path array means the path "/".
2441  * So the path "/foo/bar" becomes { "foo", "bar", NULL }
2442  * and the path "/" becomes { NULL }.
2443  *
2444  * @todo this could be optimized by using the len from the message
2445  * instead of calling strlen() again
2446  *
2447  * @param message the message
2448  * @param path place to store allocated array of path components; #NULL set here if no path field exists
2449  * @returns #FALSE if no memory to allocate the array
2450  */
2451 dbus_bool_t
2452 dbus_message_get_path_decomposed (DBusMessage   *message,
2453                                   char        ***path)
2454 {
2455   const char *v;
2456
2457   _dbus_return_val_if_fail (message != NULL, FALSE);
2458   _dbus_return_val_if_fail (path != NULL, FALSE);
2459
2460   *path = NULL;
2461
2462   v = dbus_message_get_path (message);
2463   if (v != NULL)
2464     {
2465       if (!_dbus_decompose_path (v, strlen (v),
2466                                  path, NULL))
2467         return FALSE;
2468     }
2469   return TRUE;
2470 }
2471
2472 /**
2473  * Sets the interface this message is being sent to
2474  * (for DBUS_MESSAGE_TYPE_METHOD_CALL) or
2475  * the interface a signal is being emitted from
2476  * (for DBUS_MESSAGE_TYPE_SIGNAL).
2477  *
2478  * @param message the message
2479  * @param interface the interface or #NULL to unset
2480  * @returns #FALSE if not enough memory
2481  */
2482 dbus_bool_t
2483 dbus_message_set_interface (DBusMessage  *message,
2484                             const char   *interface)
2485 {
2486   _dbus_return_val_if_fail (message != NULL, FALSE);
2487   _dbus_return_val_if_fail (!message->locked, FALSE);
2488   _dbus_return_val_if_fail (interface == NULL ||
2489                             _dbus_check_is_valid_interface (interface),
2490                             FALSE);
2491
2492   return set_or_delete_string_field (message,
2493                                      DBUS_HEADER_FIELD_INTERFACE,
2494                                      DBUS_TYPE_STRING,
2495                                      interface);
2496 }
2497
2498 /**
2499  * Gets the interface this message is being sent to
2500  * (for DBUS_MESSAGE_TYPE_METHOD_CALL) or being emitted
2501  * from (for DBUS_MESSAGE_TYPE_SIGNAL).
2502  * The interface name is fully-qualified (namespaced).
2503  * Returns #NULL if none.
2504  *
2505  * @param message the message
2506  * @returns the message interface (should not be freed) or #NULL
2507  */
2508 const char*
2509 dbus_message_get_interface (DBusMessage *message)
2510 {
2511   const char *v;
2512
2513   _dbus_return_val_if_fail (message != NULL, NULL);
2514
2515   v = NULL; /* in case field doesn't exist */
2516   _dbus_header_get_field_basic (&message->header,
2517                                 DBUS_HEADER_FIELD_INTERFACE,
2518                                 DBUS_TYPE_STRING,
2519                                 &v);
2520   return v;
2521 }
2522
2523 /**
2524  * Sets the interface member being invoked
2525  * (DBUS_MESSAGE_TYPE_METHOD_CALL) or emitted
2526  * (DBUS_MESSAGE_TYPE_SIGNAL).
2527  * The interface name is fully-qualified (namespaced).
2528  *
2529  * @param message the message
2530  * @param member the member or #NULL to unset
2531  * @returns #FALSE if not enough memory
2532  */
2533 dbus_bool_t
2534 dbus_message_set_member (DBusMessage  *message,
2535                          const char   *member)
2536 {
2537   _dbus_return_val_if_fail (message != NULL, FALSE);
2538   _dbus_return_val_if_fail (!message->locked, FALSE);
2539   _dbus_return_val_if_fail (member == NULL ||
2540                             _dbus_check_is_valid_member (member),
2541                             FALSE);
2542
2543   return set_or_delete_string_field (message,
2544                                      DBUS_HEADER_FIELD_MEMBER,
2545                                      DBUS_TYPE_STRING,
2546                                      member);
2547 }
2548
2549 /**
2550  * Gets the interface member being invoked
2551  * (DBUS_MESSAGE_TYPE_METHOD_CALL) or emitted
2552  * (DBUS_MESSAGE_TYPE_SIGNAL). Returns #NULL if none.
2553  *
2554  * @param message the message
2555  * @returns the member name (should not be freed) or #NULL
2556  */
2557 const char*
2558 dbus_message_get_member (DBusMessage *message)
2559 {
2560   const char *v;
2561
2562   _dbus_return_val_if_fail (message != NULL, NULL);
2563
2564   v = NULL; /* in case field doesn't exist */
2565   _dbus_header_get_field_basic (&message->header,
2566                                 DBUS_HEADER_FIELD_MEMBER,
2567                                 DBUS_TYPE_STRING,
2568                                 &v);
2569   return v;
2570 }
2571
2572 /**
2573  * Sets the name of the error (DBUS_MESSAGE_TYPE_ERROR).
2574  * The name is fully-qualified (namespaced).
2575  *
2576  * @param message the message
2577  * @param error_name the name or #NULL to unset
2578  * @returns #FALSE if not enough memory
2579  */
2580 dbus_bool_t
2581 dbus_message_set_error_name (DBusMessage  *message,
2582                              const char   *error_name)
2583 {
2584   _dbus_return_val_if_fail (message != NULL, FALSE);
2585   _dbus_return_val_if_fail (!message->locked, FALSE);
2586   _dbus_return_val_if_fail (error_name == NULL ||
2587                             _dbus_check_is_valid_error_name (error_name),
2588                             FALSE);
2589
2590   return set_or_delete_string_field (message,
2591                                      DBUS_HEADER_FIELD_ERROR_NAME,
2592                                      DBUS_TYPE_STRING,
2593                                      error_name);
2594 }
2595
2596 /**
2597  * Gets the error name (DBUS_MESSAGE_TYPE_ERROR only)
2598  * or #NULL if none.
2599  *
2600  * @param message the message
2601  * @returns the error name (should not be freed) or #NULL
2602  */
2603 const char*
2604 dbus_message_get_error_name (DBusMessage *message)
2605 {
2606   const char *v;
2607
2608   _dbus_return_val_if_fail (message != NULL, NULL);
2609
2610   v = NULL; /* in case field doesn't exist */
2611   _dbus_header_get_field_basic (&message->header,
2612                                 DBUS_HEADER_FIELD_ERROR_NAME,
2613                                 DBUS_TYPE_STRING,
2614                                 &v);
2615   return v;
2616 }
2617
2618 /**
2619  * Sets the message's destination. The destination is the name of
2620  * another connection on the bus and may be either the unique name
2621  * assigned by the bus to each connection, or a well-known name
2622  * specified in advance.
2623  *
2624  * @param message the message
2625  * @param destination the destination name or #NULL to unset
2626  * @returns #FALSE if not enough memory
2627  */
2628 dbus_bool_t
2629 dbus_message_set_destination (DBusMessage  *message,
2630                               const char   *destination)
2631 {
2632   _dbus_return_val_if_fail (message != NULL, FALSE);
2633   _dbus_return_val_if_fail (!message->locked, FALSE);
2634   _dbus_return_val_if_fail (destination == NULL ||
2635                             _dbus_check_is_valid_bus_name (destination),
2636                             FALSE);
2637
2638   return set_or_delete_string_field (message,
2639                                      DBUS_HEADER_FIELD_DESTINATION,
2640                                      DBUS_TYPE_STRING,
2641                                      destination);
2642 }
2643
2644 /**
2645  * Gets the destination of a message or #NULL if there is none set.
2646  *
2647  * @param message the message
2648  * @returns the message destination (should not be freed) or #NULL
2649  */
2650 const char*
2651 dbus_message_get_destination (DBusMessage *message)
2652 {
2653   const char *v;
2654
2655   _dbus_return_val_if_fail (message != NULL, NULL);
2656
2657   v = NULL; /* in case field doesn't exist */
2658   _dbus_header_get_field_basic (&message->header,
2659                                 DBUS_HEADER_FIELD_DESTINATION,
2660                                 DBUS_TYPE_STRING,
2661                                 &v);
2662   return v;
2663 }
2664
2665 /**
2666  * Sets the message sender.
2667  *
2668  * @param message the message
2669  * @param sender the sender or #NULL to unset
2670  * @returns #FALSE if not enough memory
2671  */
2672 dbus_bool_t
2673 dbus_message_set_sender (DBusMessage  *message,
2674                          const char   *sender)
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 (sender == NULL ||
2679                             _dbus_check_is_valid_bus_name (sender),
2680                             FALSE);
2681
2682   return set_or_delete_string_field (message,
2683                                      DBUS_HEADER_FIELD_SENDER,
2684                                      DBUS_TYPE_STRING,
2685                                      sender);
2686 }
2687
2688 /**
2689  * Gets the unique name of the connection which originated this
2690  * message, or #NULL if unknown or inapplicable. The sender is filled
2691  * in by the message bus.
2692  *
2693  * @param message the message
2694  * @returns the unique name of the sender or #NULL
2695  */
2696 const char*
2697 dbus_message_get_sender (DBusMessage *message)
2698 {
2699   const char *v;
2700
2701   _dbus_return_val_if_fail (message != NULL, NULL);
2702
2703   v = NULL; /* in case field doesn't exist */
2704   _dbus_header_get_field_basic (&message->header,
2705                                 DBUS_HEADER_FIELD_SENDER,
2706                                 DBUS_TYPE_STRING,
2707                                 &v);
2708   return v;
2709 }
2710
2711 /**
2712  * Gets the type signature of the message, i.e. the arguments in the
2713  * message payload. The signature includes only "in" arguments for
2714  * #DBUS_MESSAGE_TYPE_METHOD_CALL and only "out" arguments for
2715  * #DBUS_MESSAGE_TYPE_METHOD_RETURN, so is slightly different from
2716  * what you might expect (it does not include the signature of the
2717  * entire C++-style method).
2718  *
2719  * The signature is a string made up of type codes such as
2720  * #DBUS_TYPE_INT32. The string is terminated with nul (nul is also
2721  * the value of #DBUS_TYPE_INVALID).
2722  *
2723  * @param message the message
2724  * @returns the type signature
2725  */
2726 const char*
2727 dbus_message_get_signature (DBusMessage *message)
2728 {
2729   const DBusString *type_str;
2730   int type_pos;
2731
2732   _dbus_return_val_if_fail (message != NULL, NULL);
2733
2734   get_const_signature (&message->header, &type_str, &type_pos);
2735
2736   return _dbus_string_get_const_data_len (type_str, type_pos, 0);
2737 }
2738
2739 static dbus_bool_t
2740 _dbus_message_has_type_interface_member (DBusMessage *message,
2741                                          int          type,
2742                                          const char  *interface,
2743                                          const char  *member)
2744 {
2745   const char *n;
2746
2747   _dbus_assert (message != NULL);
2748   _dbus_assert (interface != NULL);
2749   _dbus_assert (member != NULL);
2750
2751   if (dbus_message_get_type (message) != type)
2752     return FALSE;
2753
2754   /* Optimize by checking the short member name first
2755    * instead of the longer interface name
2756    */
2757
2758   n = dbus_message_get_member (message);
2759
2760   if (n && strcmp (n, member) == 0)
2761     {
2762       n = dbus_message_get_interface (message);
2763
2764       if (n == NULL || strcmp (n, interface) == 0)
2765         return TRUE;
2766     }
2767
2768   return FALSE;
2769 }
2770
2771 /**
2772  * Checks whether the message is a method call with the given
2773  * interface and member fields.  If the message is not
2774  * #DBUS_MESSAGE_TYPE_METHOD_CALL, or has a different interface or
2775  * member field, returns #FALSE. If the interface field is missing,
2776  * then it will be assumed equal to the provided interface.  The D-BUS
2777  * protocol allows method callers to leave out the interface name.
2778  *
2779  * @param message the message
2780  * @param interface the name to check (must not be #NULL)
2781  * @param method the name to check (must not be #NULL)
2782  *
2783  * @returns #TRUE if the message is the specified method call
2784  */
2785 dbus_bool_t
2786 dbus_message_is_method_call (DBusMessage *message,
2787                              const char  *interface,
2788                              const char  *method)
2789 {
2790   _dbus_return_val_if_fail (message != NULL, FALSE);
2791   _dbus_return_val_if_fail (interface != NULL, FALSE);
2792   _dbus_return_val_if_fail (method != NULL, FALSE);
2793   /* don't check that interface/method are valid since it would be
2794    * expensive, and not catch many common errors
2795    */
2796
2797   return _dbus_message_has_type_interface_member (message,
2798                                                   DBUS_MESSAGE_TYPE_METHOD_CALL,
2799                                                   interface, method);
2800 }
2801
2802 /**
2803  * Checks whether the message is a signal with the given interface and
2804  * member fields.  If the message is not #DBUS_MESSAGE_TYPE_SIGNAL, or
2805  * has a different interface or member field, returns #FALSE.  If the
2806  * interface field in the message is missing, it is assumed to match
2807  * any interface you pass in to this function.
2808  *
2809  * @param message the message
2810  * @param interface the name to check (must not be #NULL)
2811  * @param signal_name the name to check (must not be #NULL)
2812  *
2813  * @returns #TRUE if the message is the specified signal
2814  */
2815 dbus_bool_t
2816 dbus_message_is_signal (DBusMessage *message,
2817                         const char  *interface,
2818                         const char  *signal_name)
2819 {
2820   _dbus_return_val_if_fail (message != NULL, FALSE);
2821   _dbus_return_val_if_fail (interface != NULL, FALSE);
2822   _dbus_return_val_if_fail (signal_name != NULL, FALSE);
2823   /* don't check that interface/name are valid since it would be
2824    * expensive, and not catch many common errors
2825    */
2826
2827   return _dbus_message_has_type_interface_member (message,
2828                                                   DBUS_MESSAGE_TYPE_SIGNAL,
2829                                                   interface, signal_name);
2830 }
2831
2832 /**
2833  * Checks whether the message is an error reply with the given error
2834  * name.  If the message is not #DBUS_MESSAGE_TYPE_ERROR, or has a
2835  * different name, returns #FALSE.
2836  *
2837  * @param message the message
2838  * @param error_name the name to check (must not be #NULL)
2839  *
2840  * @returns #TRUE if the message is the specified error
2841  */
2842 dbus_bool_t
2843 dbus_message_is_error (DBusMessage *message,
2844                        const char  *error_name)
2845 {
2846   const char *n;
2847
2848   _dbus_return_val_if_fail (message != NULL, FALSE);
2849   _dbus_return_val_if_fail (error_name != NULL, FALSE);
2850   /* don't check that error_name is valid since it would be expensive,
2851    * and not catch many common errors
2852    */
2853
2854   if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_ERROR)
2855     return FALSE;
2856
2857   n = dbus_message_get_error_name (message);
2858
2859   if (n && strcmp (n, error_name) == 0)
2860     return TRUE;
2861   else
2862     return FALSE;
2863 }
2864
2865 /**
2866  * Checks whether the message was sent to the given name.  If the
2867  * message has no destination specified or has a different
2868  * destination, returns #FALSE.
2869  *
2870  * @param message the message
2871  * @param name the name to check (must not be #NULL)
2872  *
2873  * @returns #TRUE if the message has the given destination name
2874  */
2875 dbus_bool_t
2876 dbus_message_has_destination (DBusMessage  *message,
2877                               const char   *name)
2878 {
2879   const char *s;
2880
2881   _dbus_return_val_if_fail (message != NULL, FALSE);
2882   _dbus_return_val_if_fail (name != NULL, FALSE);
2883   /* don't check that name is valid since it would be expensive, and
2884    * not catch many common errors
2885    */
2886
2887   s = dbus_message_get_destination (message);
2888
2889   if (s && strcmp (s, name) == 0)
2890     return TRUE;
2891   else
2892     return FALSE;
2893 }
2894
2895 /**
2896  * Checks whether the message has the given unique name as its sender.
2897  * If the message has no sender specified or has a different sender,
2898  * returns #FALSE. Note that a peer application will always have the
2899  * unique name of the connection as the sender. So you can't use this
2900  * function to see whether a sender owned a well-known name.
2901  *
2902  * Messages from the bus itself will have #DBUS_SERVICE_DBUS
2903  * as the sender.
2904  *
2905  * @param message the message
2906  * @param name the name to check (must not be #NULL)
2907  *
2908  * @returns #TRUE if the message has the given sender
2909  */
2910 dbus_bool_t
2911 dbus_message_has_sender (DBusMessage  *message,
2912                          const char   *name)
2913 {
2914   const char *s;
2915
2916   _dbus_return_val_if_fail (message != NULL, FALSE);
2917   _dbus_return_val_if_fail (name != NULL, FALSE);
2918   /* don't check that name is valid since it would be expensive, and
2919    * not catch many common errors
2920    */
2921
2922   s = dbus_message_get_sender (message);
2923
2924   if (s && strcmp (s, name) == 0)
2925     return TRUE;
2926   else
2927     return FALSE;
2928 }
2929
2930 /**
2931  * Checks whether the message has the given signature; see
2932  * dbus_message_get_signature() for more details on what the signature
2933  * looks like.
2934  *
2935  * @param message the message
2936  * @param signature typecode array
2937  * @returns #TRUE if message has the given signature
2938 */
2939 dbus_bool_t
2940 dbus_message_has_signature (DBusMessage   *message,
2941                             const char    *signature)
2942 {
2943   const char *s;
2944
2945   _dbus_return_val_if_fail (message != NULL, FALSE);
2946   _dbus_return_val_if_fail (signature != NULL, FALSE);
2947   /* don't check that signature is valid since it would be expensive,
2948    * and not catch many common errors
2949    */
2950
2951   s = dbus_message_get_signature (message);
2952
2953   if (s && strcmp (s, signature) == 0)
2954     return TRUE;
2955   else
2956     return FALSE;
2957 }
2958
2959 /**
2960  * Sets a #DBusError based on the contents of the given
2961  * message. The error is only set if the message
2962  * is an error message, as in DBUS_MESSAGE_TYPE_ERROR.
2963  * The name of the error is set to the name of the message,
2964  * and the error message is set to the first argument
2965  * if the argument exists and is a string.
2966  *
2967  * The return value indicates whether the error was set (the error is
2968  * set if and only if the message is an error message).  So you can
2969  * check for an error reply and convert it to DBusError in one go:
2970  * @code
2971  *  if (dbus_set_error_from_message (error, reply))
2972  *    return error;
2973  *  else
2974  *    process reply;
2975  * @endcode
2976  *
2977  * @param error the error to set
2978  * @param message the message to set it from
2979  * @returns #TRUE if dbus_message_get_is_error() returns #TRUE for the message
2980  */
2981 dbus_bool_t
2982 dbus_set_error_from_message (DBusError   *error,
2983                              DBusMessage *message)
2984 {
2985   const char *str;
2986
2987   _dbus_return_val_if_fail (message != NULL, FALSE);
2988   _dbus_return_val_if_error_is_set (error, FALSE);
2989
2990   if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_ERROR)
2991     return FALSE;
2992
2993   str = NULL;
2994   dbus_message_get_args (message, NULL,
2995                          DBUS_TYPE_STRING, &str,
2996                          DBUS_TYPE_INVALID);
2997
2998   dbus_set_error (error, dbus_message_get_error_name (message),
2999                   str ? "%s" : NULL, str);
3000
3001   return TRUE;
3002 }
3003
3004 /** @} */
3005
3006 /**
3007  * @addtogroup DBusMessageInternals
3008  *
3009  * @{
3010  */
3011
3012 /**
3013  * The initial buffer size of the message loader.
3014  *
3015  * @todo this should be based on min header size plus some average
3016  * body size, or something. Or rather, the min header size only, if we
3017  * want to try to read only the header, store that in a DBusMessage,
3018  * then read only the body and store that, etc., depends on
3019  * how we optimize _dbus_message_loader_get_buffer() and what
3020  * the exact message format is.
3021  */
3022 #define INITIAL_LOADER_DATA_LEN 32
3023
3024 /**
3025  * Creates a new message loader. Returns #NULL if memory can't
3026  * be allocated.
3027  *
3028  * @returns new loader, or #NULL.
3029  */
3030 DBusMessageLoader*
3031 _dbus_message_loader_new (void)
3032 {
3033   DBusMessageLoader *loader;
3034
3035   loader = dbus_new0 (DBusMessageLoader, 1);
3036   if (loader == NULL)
3037     return NULL;
3038   
3039   loader->refcount = 1;
3040
3041   loader->corrupted = FALSE;
3042   loader->corruption_reason = DBUS_VALID;
3043
3044   /* this can be configured by the app, but defaults to the protocol max */
3045   loader->max_message_size = DBUS_MAXIMUM_MESSAGE_LENGTH;
3046
3047   if (!_dbus_string_init (&loader->data))
3048     {
3049       dbus_free (loader);
3050       return NULL;
3051     }
3052
3053   /* preallocate the buffer for speed, ignore failure */
3054   _dbus_string_set_length (&loader->data, INITIAL_LOADER_DATA_LEN);
3055   _dbus_string_set_length (&loader->data, 0);
3056
3057   return loader;
3058 }
3059
3060 /**
3061  * Increments the reference count of the loader.
3062  *
3063  * @param loader the loader.
3064  * @returns the loader
3065  */
3066 DBusMessageLoader *
3067 _dbus_message_loader_ref (DBusMessageLoader *loader)
3068 {
3069   loader->refcount += 1;
3070
3071   return loader;
3072 }
3073
3074 /**
3075  * Decrements the reference count of the loader and finalizes the
3076  * loader when the count reaches zero.
3077  *
3078  * @param loader the loader.
3079  */
3080 void
3081 _dbus_message_loader_unref (DBusMessageLoader *loader)
3082 {
3083   loader->refcount -= 1;
3084   if (loader->refcount == 0)
3085     {
3086       _dbus_list_foreach (&loader->messages,
3087                           (DBusForeachFunction) dbus_message_unref,
3088                           NULL);
3089       _dbus_list_clear (&loader->messages);
3090       _dbus_string_free (&loader->data);
3091       dbus_free (loader);
3092     }
3093 }
3094
3095 /**
3096  * Gets the buffer to use for reading data from the network.  Network
3097  * data is read directly into an allocated buffer, which is then used
3098  * in the DBusMessage, to avoid as many extra memcpy's as possible.
3099  * The buffer must always be returned immediately using
3100  * _dbus_message_loader_return_buffer(), even if no bytes are
3101  * successfully read.
3102  *
3103  * @todo this function can be a lot more clever. For example
3104  * it can probably always return a buffer size to read exactly
3105  * the body of the next message, thus avoiding any memory wastage
3106  * or reallocs.
3107  *
3108  * @todo we need to enforce a max length on strings in header fields.
3109  *
3110  * @param loader the message loader.
3111  * @param buffer the buffer
3112  */
3113 void
3114 _dbus_message_loader_get_buffer (DBusMessageLoader  *loader,
3115                                  DBusString        **buffer)
3116 {
3117   _dbus_assert (!loader->buffer_outstanding);
3118
3119   *buffer = &loader->data;
3120
3121   loader->buffer_outstanding = TRUE;
3122 }
3123
3124 /**
3125  * Returns a buffer obtained from _dbus_message_loader_get_buffer(),
3126  * indicating to the loader how many bytes of the buffer were filled
3127  * in. This function must always be called, even if no bytes were
3128  * successfully read.
3129  *
3130  * @param loader the loader.
3131  * @param buffer the buffer.
3132  * @param bytes_read number of bytes that were read into the buffer.
3133  */
3134 void
3135 _dbus_message_loader_return_buffer (DBusMessageLoader  *loader,
3136                                     DBusString         *buffer,
3137                                     int                 bytes_read)
3138 {
3139   _dbus_assert (loader->buffer_outstanding);
3140   _dbus_assert (buffer == &loader->data);
3141
3142   loader->buffer_outstanding = FALSE;
3143 }
3144
3145 /*
3146  * FIXME when we move the header out of the buffer, that memmoves all
3147  * buffered messages. Kind of crappy.
3148  *
3149  * Also we copy the header and body, which is kind of crappy.  To
3150  * avoid this, we have to allow header and body to be in a single
3151  * memory block, which is good for messages we read and bad for
3152  * messages we are creating. But we could move_len() the buffer into
3153  * this single memory block, and move_len() will just swap the buffers
3154  * if you're moving the entire buffer replacing the dest string.
3155  *
3156  * We could also have the message loader tell the transport how many
3157  * bytes to read; so it would first ask for some arbitrary number like
3158  * 256, then if the message was incomplete it would use the
3159  * header/body len to ask for exactly the size of the message (or
3160  * blocks the size of a typical kernel buffer for the socket). That
3161  * way we don't get trailing bytes in the buffer that have to be
3162  * memmoved. Though I suppose we also don't have a chance of reading a
3163  * bunch of small messages at once, so the optimization may be stupid.
3164  *
3165  * Another approach would be to keep a "start" index into
3166  * loader->data and only delete it occasionally, instead of after
3167  * each message is loaded.
3168  *
3169  * load_message() returns FALSE if not enough memory OR the loader was corrupted
3170  */
3171 static dbus_bool_t
3172 load_message (DBusMessageLoader *loader,
3173               DBusMessage       *message,
3174               int                byte_order,
3175               int                fields_array_len,
3176               int                header_len,
3177               int                body_len)
3178 {
3179   dbus_bool_t oom;
3180   DBusValidity validity;
3181   const DBusString *type_str;
3182   int type_pos;
3183   DBusValidationMode mode;
3184
3185   mode = DBUS_VALIDATION_MODE_DATA_IS_UNTRUSTED;
3186   
3187   oom = FALSE;
3188
3189 #if 0
3190   _dbus_verbose_bytes_of_string (&loader->data, 0, header_len /* + body_len */);
3191 #endif
3192
3193   /* 1. VALIDATE AND COPY OVER HEADER */
3194   _dbus_assert (_dbus_string_get_length (&message->header.data) == 0);
3195   _dbus_assert ((header_len + body_len) <= _dbus_string_get_length (&loader->data));
3196
3197   if (!_dbus_header_load (&message->header,
3198                           mode,
3199                           &validity,
3200                           byte_order,
3201                           fields_array_len,
3202                           header_len,
3203                           body_len,
3204                           &loader->data, 0,
3205                           _dbus_string_get_length (&loader->data)))
3206     {
3207       _dbus_verbose ("Failed to load header for new message code %d\n", validity);
3208
3209       /* assert here so we can catch any code that still uses DBUS_VALID to indicate
3210          oom errors.  They should use DBUS_VALIDITY_UNKNOWN_OOM_ERROR instead */
3211       _dbus_assert (validity != DBUS_VALID);
3212
3213       if (validity == DBUS_VALIDITY_UNKNOWN_OOM_ERROR)
3214         oom = TRUE;
3215       else
3216         {
3217           loader->corrupted = TRUE;
3218           loader->corruption_reason = validity;
3219         }
3220       goto failed;
3221     }
3222
3223   _dbus_assert (validity == DBUS_VALID);
3224
3225   message->byte_order = byte_order;
3226
3227   /* 2. VALIDATE BODY */
3228   if (mode != DBUS_VALIDATION_MODE_WE_TRUST_THIS_DATA_ABSOLUTELY)
3229     {
3230       get_const_signature (&message->header, &type_str, &type_pos);
3231       
3232       /* Because the bytes_remaining arg is NULL, this validates that the
3233        * body is the right length
3234        */
3235       validity = _dbus_validate_body_with_reason (type_str,
3236                                                   type_pos,
3237                                                   byte_order,
3238                                                   NULL,
3239                                                   &loader->data,
3240                                                   header_len,
3241                                                   body_len);
3242       if (validity != DBUS_VALID)
3243         {
3244           _dbus_verbose ("Failed to validate message body code %d\n", validity);
3245
3246           loader->corrupted = TRUE;
3247           loader->corruption_reason = validity;
3248           
3249           goto failed;
3250         }
3251     }
3252
3253   /* 3. COPY OVER BODY AND QUEUE MESSAGE */
3254
3255   if (!_dbus_list_append (&loader->messages, message))
3256     {
3257       _dbus_verbose ("Failed to append new message to loader queue\n");
3258       oom = TRUE;
3259       goto failed;
3260     }
3261
3262   _dbus_assert (_dbus_string_get_length (&message->body) == 0);
3263   _dbus_assert (_dbus_string_get_length (&loader->data) >=
3264                 (header_len + body_len));
3265
3266   if (!_dbus_string_copy_len (&loader->data, header_len, body_len, &message->body, 0))
3267     {
3268       _dbus_verbose ("Failed to move body into new message\n");
3269       oom = TRUE;
3270       goto failed;
3271     }
3272
3273   _dbus_string_delete (&loader->data, 0, header_len + body_len);
3274
3275   _dbus_assert (_dbus_string_get_length (&message->header.data) == header_len);
3276   _dbus_assert (_dbus_string_get_length (&message->body) == body_len);
3277
3278   _dbus_verbose ("Loaded message %p\n", message);
3279
3280   _dbus_assert (!oom);
3281   _dbus_assert (!loader->corrupted);
3282   _dbus_assert (loader->messages != NULL);
3283   _dbus_assert (_dbus_list_find_last (&loader->messages, message) != NULL);
3284
3285   return TRUE;
3286
3287  failed:
3288
3289   /* Clean up */
3290
3291   /* does nothing if the message isn't in the list */
3292   _dbus_list_remove_last (&loader->messages, message);
3293   
3294   if (oom)
3295     _dbus_assert (!loader->corrupted);
3296   else
3297     _dbus_assert (loader->corrupted);
3298
3299   _dbus_verbose_bytes_of_string (&loader->data, 0, _dbus_string_get_length (&loader->data));
3300
3301   return FALSE;
3302 }
3303
3304 /**
3305  * Converts buffered data into messages, if we have enough data.  If
3306  * we don't have enough data, does nothing.
3307  *
3308  * @todo we need to check that the proper named header fields exist
3309  * for each message type.
3310  *
3311  * @todo If a message has unknown type, we should probably eat it
3312  * right here rather than passing it out to applications.  However
3313  * it's not an error to see messages of unknown type.
3314  *
3315  * @param loader the loader.
3316  * @returns #TRUE if we had enough memory to finish.
3317  */
3318 dbus_bool_t
3319 _dbus_message_loader_queue_messages (DBusMessageLoader *loader)
3320 {
3321   while (!loader->corrupted &&
3322          _dbus_string_get_length (&loader->data) >= DBUS_MINIMUM_HEADER_SIZE)
3323     {
3324       DBusValidity validity;
3325       int byte_order, fields_array_len, header_len, body_len;
3326
3327       if (_dbus_header_have_message_untrusted (loader->max_message_size,
3328                                                &validity,
3329                                                &byte_order,
3330                                                &fields_array_len,
3331                                                &header_len,
3332                                                &body_len,
3333                                                &loader->data, 0,
3334                                                _dbus_string_get_length (&loader->data)))
3335         {
3336           DBusMessage *message;
3337
3338           _dbus_assert (validity == DBUS_VALID);
3339
3340           message = dbus_message_new_empty_header ();
3341           if (message == NULL)
3342             return FALSE;
3343
3344           if (!load_message (loader, message,
3345                              byte_order, fields_array_len,
3346                              header_len, body_len))
3347             {
3348               dbus_message_unref (message);
3349               /* load_message() returns false if corrupted or OOM; if
3350                * corrupted then return TRUE for not OOM
3351                */
3352               return loader->corrupted;
3353             }
3354
3355           _dbus_assert (loader->messages != NULL);
3356           _dbus_assert (_dbus_list_find_last (&loader->messages, message) != NULL);
3357         }
3358       else
3359         {
3360           _dbus_verbose ("Initial peek at header says we don't have a whole message yet, or data broken with invalid code %d\n",
3361                          validity);
3362           if (validity != DBUS_VALID)
3363             {
3364               loader->corrupted = TRUE;
3365               loader->corruption_reason = validity;
3366             }
3367           return TRUE;
3368         }
3369     }
3370
3371   return TRUE;
3372 }
3373
3374 /**
3375  * Peeks at first loaded message, returns #NULL if no messages have
3376  * been queued.
3377  *
3378  * @param loader the loader.
3379  * @returns the next message, or #NULL if none.
3380  */
3381 DBusMessage*
3382 _dbus_message_loader_peek_message (DBusMessageLoader *loader)
3383 {
3384   if (loader->messages)
3385     return loader->messages->data;
3386   else
3387     return NULL;
3388 }
3389
3390 /**
3391  * Pops a loaded message (passing ownership of the message
3392  * to the caller). Returns #NULL if no messages have been
3393  * queued.
3394  *
3395  * @param loader the loader.
3396  * @returns the next message, or #NULL if none.
3397  */
3398 DBusMessage*
3399 _dbus_message_loader_pop_message (DBusMessageLoader *loader)
3400 {
3401   return _dbus_list_pop_first (&loader->messages);
3402 }
3403
3404 /**
3405  * Pops a loaded message inside a list link (passing ownership of the
3406  * message and link to the caller). Returns #NULL if no messages have
3407  * been loaded.
3408  *
3409  * @param loader the loader.
3410  * @returns the next message link, or #NULL if none.
3411  */
3412 DBusList*
3413 _dbus_message_loader_pop_message_link (DBusMessageLoader *loader)
3414 {
3415   return _dbus_list_pop_first_link (&loader->messages);
3416 }
3417
3418 /**
3419  * Returns a popped message link, used to undo a pop.
3420  *
3421  * @param loader the loader
3422  * @param link the link with a message in it
3423  */
3424 void
3425 _dbus_message_loader_putback_message_link (DBusMessageLoader  *loader,
3426                                            DBusList           *link)
3427 {
3428   _dbus_list_prepend_link (&loader->messages, link);
3429 }
3430
3431 /**
3432  * Checks whether the loader is confused due to bad data.
3433  * If messages are received that are invalid, the
3434  * loader gets confused and gives up permanently.
3435  * This state is called "corrupted."
3436  *
3437  * @param loader the loader
3438  * @returns #TRUE if the loader is hosed.
3439  */
3440 dbus_bool_t
3441 _dbus_message_loader_get_is_corrupted (DBusMessageLoader *loader)
3442 {
3443   _dbus_assert ((loader->corrupted && loader->corruption_reason != DBUS_VALID) ||
3444                 (!loader->corrupted && loader->corruption_reason == DBUS_VALID));
3445   return loader->corrupted;
3446 }
3447
3448 /**
3449  * Sets the maximum size message we allow.
3450  *
3451  * @param loader the loader
3452  * @param size the max message size in bytes
3453  */
3454 void
3455 _dbus_message_loader_set_max_message_size (DBusMessageLoader  *loader,
3456                                            long                size)
3457 {
3458   if (size > DBUS_MAXIMUM_MESSAGE_LENGTH)
3459     {
3460       _dbus_verbose ("clamping requested max message size %ld to %d\n",
3461                      size, DBUS_MAXIMUM_MESSAGE_LENGTH);
3462       size = DBUS_MAXIMUM_MESSAGE_LENGTH;
3463     }
3464   loader->max_message_size = size;
3465 }
3466
3467 /**
3468  * Gets the maximum allowed message size in bytes.
3469  *
3470  * @param loader the loader
3471  * @returns max size in bytes
3472  */
3473 long
3474 _dbus_message_loader_get_max_message_size (DBusMessageLoader  *loader)
3475 {
3476   return loader->max_message_size;
3477 }
3478
3479 static DBusDataSlotAllocator slot_allocator;
3480 _DBUS_DEFINE_GLOBAL_LOCK (message_slots);
3481
3482 /**
3483  * Allocates an integer ID to be used for storing application-specific
3484  * data on any DBusMessage. The allocated ID may then be used
3485  * with dbus_message_set_data() and dbus_message_get_data().
3486  * The passed-in slot must be initialized to -1, and is filled in
3487  * with the slot ID. If the passed-in slot is not -1, it's assumed
3488  * to be already allocated, and its refcount is incremented.
3489  *
3490  * The allocated slot is global, i.e. all DBusMessage objects will
3491  * have a slot with the given integer ID reserved.
3492  *
3493  * @param slot_p address of a global variable storing the slot
3494  * @returns #FALSE on failure (no memory)
3495  */
3496 dbus_bool_t
3497 dbus_message_allocate_data_slot (dbus_int32_t *slot_p)
3498 {
3499   return _dbus_data_slot_allocator_alloc (&slot_allocator,
3500                                           _DBUS_LOCK_NAME (message_slots),
3501                                           slot_p);
3502 }
3503
3504 /**
3505  * Deallocates a global ID for message data slots.
3506  * dbus_message_get_data() and dbus_message_set_data() may no
3507  * longer be used with this slot.  Existing data stored on existing
3508  * DBusMessage objects will be freed when the message is
3509  * finalized, but may not be retrieved (and may only be replaced if
3510  * someone else reallocates the slot).  When the refcount on the
3511  * passed-in slot reaches 0, it is set to -1.
3512  *
3513  * @param slot_p address storing the slot to deallocate
3514  */
3515 void
3516 dbus_message_free_data_slot (dbus_int32_t *slot_p)
3517 {
3518   _dbus_return_if_fail (*slot_p >= 0);
3519
3520   _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
3521 }
3522
3523 /**
3524  * Stores a pointer on a DBusMessage, along
3525  * with an optional function to be used for freeing
3526  * the data when the data is set again, or when
3527  * the message is finalized. The slot number
3528  * must have been allocated with dbus_message_allocate_data_slot().
3529  *
3530  * @param message the message
3531  * @param slot the slot number
3532  * @param data the data to store
3533  * @param free_data_func finalizer function for the data
3534  * @returns #TRUE if there was enough memory to store the data
3535  */
3536 dbus_bool_t
3537 dbus_message_set_data (DBusMessage     *message,
3538                        dbus_int32_t     slot,
3539                        void            *data,
3540                        DBusFreeFunction free_data_func)
3541 {
3542   DBusFreeFunction old_free_func;
3543   void *old_data;
3544   dbus_bool_t retval;
3545
3546   _dbus_return_val_if_fail (message != NULL, FALSE);
3547   _dbus_return_val_if_fail (slot >= 0, FALSE);
3548
3549   retval = _dbus_data_slot_list_set (&slot_allocator,
3550                                      &message->slot_list,
3551                                      slot, data, free_data_func,
3552                                      &old_free_func, &old_data);
3553
3554   if (retval)
3555     {
3556       /* Do the actual free outside the message lock */
3557       if (old_free_func)
3558         (* old_free_func) (old_data);
3559     }
3560
3561   return retval;
3562 }
3563
3564 /**
3565  * Retrieves data previously set with dbus_message_set_data().
3566  * The slot must still be allocated (must not have been freed).
3567  *
3568  * @param message the message
3569  * @param slot the slot to get data from
3570  * @returns the data, or #NULL if not found
3571  */
3572 void*
3573 dbus_message_get_data (DBusMessage   *message,
3574                        dbus_int32_t   slot)
3575 {
3576   void *res;
3577
3578   _dbus_return_val_if_fail (message != NULL, NULL);
3579
3580   res = _dbus_data_slot_list_get (&slot_allocator,
3581                                   &message->slot_list,
3582                                   slot);
3583
3584   return res;
3585 }
3586
3587 /**
3588  * Utility function to convert a machine-readable (not translated)
3589  * string into a D-BUS message type.
3590  *
3591  * @code
3592  *   "method_call"    -> DBUS_MESSAGE_TYPE_METHOD_CALL
3593  *   "method_return"  -> DBUS_MESSAGE_TYPE_METHOD_RETURN
3594  *   "signal"         -> DBUS_MESSAGE_TYPE_SIGNAL
3595  *   "error"          -> DBUS_MESSAGE_TYPE_ERROR
3596  *   anything else    -> DBUS_MESSAGE_TYPE_INVALID
3597  * @endcode
3598  *
3599  */
3600 int
3601 dbus_message_type_from_string (const char *type_str)
3602 {
3603   if (strcmp (type_str, "method_call") == 0)
3604     return DBUS_MESSAGE_TYPE_METHOD_CALL;
3605   if (strcmp (type_str, "method_return") == 0)
3606     return DBUS_MESSAGE_TYPE_METHOD_RETURN;
3607   else if (strcmp (type_str, "signal") == 0)
3608     return DBUS_MESSAGE_TYPE_SIGNAL;
3609   else if (strcmp (type_str, "error") == 0)
3610     return DBUS_MESSAGE_TYPE_ERROR;
3611   else
3612     return DBUS_MESSAGE_TYPE_INVALID;
3613 }
3614
3615 /**
3616  * Utility function to convert a D-BUS message type into a
3617  * machine-readable string (not translated).
3618  *
3619  * @code
3620  *   DBUS_MESSAGE_TYPE_METHOD_CALL    -> "method_call"
3621  *   DBUS_MESSAGE_TYPE_METHOD_RETURN  -> "method_return"
3622  *   DBUS_MESSAGE_TYPE_SIGNAL         -> "signal"
3623  *   DBUS_MESSAGE_TYPE_ERROR          -> "error"
3624  *   DBUS_MESSAGE_TYPE_INVALID        -> "invalid"
3625  * @endcode
3626  *
3627  */
3628 const char *
3629 dbus_message_type_to_string (int type)
3630 {
3631   switch (type)
3632     {
3633     case DBUS_MESSAGE_TYPE_METHOD_CALL:
3634       return "method_call";
3635     case DBUS_MESSAGE_TYPE_METHOD_RETURN:
3636       return "method_return";
3637     case DBUS_MESSAGE_TYPE_SIGNAL:
3638       return "signal";
3639     case DBUS_MESSAGE_TYPE_ERROR:
3640       return "error";
3641     default:
3642       return "invalid";
3643     }
3644 }
3645
3646 /** @} */
3647
3648 /* tests in dbus-message-util.c */