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