2003-03-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  Red Hat Inc.
5  * Copyright (C) 2002, 2003  CodeFactory AB
6  *
7  * Licensed under the Academic Free License version 1.2
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.h"
27 #include "dbus-message.h"
28 #include "dbus-message-internal.h"
29 #include "dbus-memory.h"
30 #include "dbus-list.h"
31 #include "dbus-message-builder.h"
32 #include <string.h>
33
34 /**
35  * @defgroup DBusMessageInternals DBusMessage implementation details
36  * @ingroup DBusInternals
37  * @brief DBusMessage private implementation details.
38  *
39  * The guts of DBusMessage and its methods.
40  *
41  * @{
42  */
43
44 enum
45 {
46   FIELD_HEADER_LENGTH,
47   FIELD_BODY_LENGTH,
48   FIELD_CLIENT_SERIAL,
49   FIELD_NAME,
50   FIELD_SERVICE,
51   FIELD_SENDER,
52   FIELD_REPLY_SERIAL,
53
54   FIELD_LAST
55 };
56
57 static dbus_bool_t field_is_named[FIELD_LAST] =
58 {
59   FALSE, /* FIELD_HEADER_LENGTH */
60   FALSE, /* FIELD_BODY_LENGTH */
61   FALSE, /* FIELD_CLIENT_SERIAL */
62   TRUE,  /* FIELD_NAME */
63   TRUE,  /* FIELD_SERVICE */
64   TRUE,  /* FIELD_SENDER */
65   TRUE   /* FIELD_REPLY_SERIAL */
66 };
67
68 typedef struct
69 {
70   int offset; /**< Offset to start of field (location of name of field
71                * for named fields)
72                */
73 } HeaderField;
74
75 /**
76  * @brief Internals of DBusMessage
77  * 
78  * Object representing a message received from or to be sent to
79  * another application. This is an opaque object, all members
80  * are private.
81  */
82 struct DBusMessage
83 {
84   dbus_atomic_t refcount; /**< Reference count */
85
86   DBusString header; /**< Header network data, stored
87                       * separately from body so we can
88                       * independently realloc it.
89                       */
90
91   HeaderField header_fields[FIELD_LAST]; /**< Track the location
92                                            * of each field in "header"
93                                            */
94
95   dbus_int32_t client_serial; /**< Cached client serial value for speed */
96   dbus_int32_t reply_serial;  /**< Cached reply serial value for speed */
97   
98   int header_padding; /**< bytes of alignment in header */
99   
100   DBusString body;   /**< Body network data. */
101
102   char byte_order; /**< Message byte order. */
103
104   DBusCounter *size_counter; /**< Counter for the size of the message, or #NULL */
105   long size_counter_delta;   /**< Size we incremented the size counter by. */
106   
107   unsigned int locked : 1; /**< Message being sent, no modifications allowed. */
108 };
109
110 /**
111  * @brief Internals of DBusMessageIter
112  * 
113  * Object representing a position in a message. All fields are internal.
114  */
115 struct DBusMessageIter
116 {
117   int refcount; /**< Reference count */
118
119   int pos; /**< Current position in the string */
120   
121   DBusMessage *message; /**< Message used */
122 };
123
124 /**
125  * Gets the data to be sent over the network for this message.
126  * The header and then the body should be written out.
127  * This function is guaranteed to always return the same
128  * data once a message is locked (with _dbus_message_lock()).
129  *
130  * @param message the message.
131  * @param header return location for message header data.
132  * @param body return location for message body data.
133  */
134 void
135 _dbus_message_get_network_data (DBusMessage          *message,
136                                 const DBusString    **header,
137                                 const DBusString    **body)
138 {
139   _dbus_assert (message->locked);
140   
141   *header = &message->header;
142   *body = &message->body;
143 }
144
145 static void
146 clear_header_padding (DBusMessage *message)
147 {
148   _dbus_string_shorten (&message->header,
149                         message->header_padding);
150   message->header_padding = 0;
151 }              
152
153 static dbus_bool_t
154 append_header_padding (DBusMessage *message)
155 {
156   int old_len;
157   old_len = _dbus_string_get_length (&message->header);
158   if (!_dbus_string_align_length (&message->header, 8))
159     return FALSE;
160
161   message->header_padding = _dbus_string_get_length (&message->header) - old_len;
162
163   return TRUE;
164 }
165
166 static void
167 adjust_field_offsets (DBusMessage *message,
168                       int          offsets_after,
169                       int          delta)
170 {
171   int i;
172
173   if (delta == 0)
174     return;
175   
176   i = 0;
177   while (i < FIELD_LAST)
178     {
179       if (message->header_fields[i].offset > offsets_after)
180         message->header_fields[i].offset += delta;
181
182       ++i;
183     }
184 }
185
186 static const char*
187 get_string_field (DBusMessage *message,
188                   int          field,
189                   int         *len)
190 {
191   int offset;
192   const char *data;
193
194   offset = message->header_fields[field].offset;
195
196   _dbus_assert (field < FIELD_LAST);
197   
198   if (offset < 0)
199     return NULL;
200
201   /* offset points to string length, string data follows it */
202   /* FIXME _dbus_demarshal_const_string() that returned
203    * a reference to the string plus its len might be nice.
204    */
205   
206   if (len)
207     *len = _dbus_demarshal_uint32 (&message->header,
208                                    message->byte_order,
209                                    offset,
210                                    NULL);
211
212   _dbus_string_get_const_data (&message->header,
213                                &data);
214   
215   return data + (offset + 4); 
216 }
217
218 static dbus_int32_t
219 get_int_field (DBusMessage *message,
220                int          field)
221 {
222   int offset;
223
224   _dbus_assert (field < FIELD_LAST);
225   
226   offset = message->header_fields[field].offset;
227   
228   if (offset < 0)
229     return -1; /* useless if -1 is a valid value of course */
230   
231   return _dbus_demarshal_int32 (&message->header,
232                                 message->byte_order,
233                                 offset,
234                                 NULL);
235 }
236
237 static dbus_bool_t
238 append_int_field (DBusMessage *message,
239                   int          field,
240                   const char  *name,
241                   int          value)
242 {
243   int orig_len;
244
245   _dbus_assert (!message->locked);
246
247   clear_header_padding (message);
248   
249   orig_len = _dbus_string_get_length (&message->header);
250   
251   if (!_dbus_string_align_length (&message->header, 4))
252     goto failed;  
253   
254   if (!_dbus_string_append_len (&message->header, name, 4))
255     goto failed;
256
257   if (!_dbus_string_append_byte (&message->header, DBUS_TYPE_INT32))
258     goto failed;
259
260   if (!_dbus_string_align_length (&message->header, 4))
261     goto failed;
262   
263   message->header_fields[FIELD_REPLY_SERIAL].offset =
264     _dbus_string_get_length (&message->header);
265   
266   if (!_dbus_marshal_int32 (&message->header, message->byte_order,
267                             value))
268     goto failed;
269
270   if (!append_header_padding (message))
271     goto failed;
272   
273   return TRUE;
274   
275  failed:
276   message->header_fields[field].offset = -1;
277   _dbus_string_set_length (&message->header, orig_len);
278
279   /* this must succeed because it was allocated on function entry and
280    * DBusString doesn't ever realloc smaller
281    */
282   if (!append_header_padding (message))
283     _dbus_assert_not_reached ("failed to reappend header padding");
284   return FALSE;
285 }
286
287 static dbus_bool_t
288 append_string_field (DBusMessage *message,
289                      int          field,
290                      const char  *name,
291                      const char  *value)
292 {
293   int orig_len;
294
295   _dbus_assert (!message->locked);
296
297   clear_header_padding (message);
298   
299   orig_len = _dbus_string_get_length (&message->header);
300
301   if (!_dbus_string_align_length (&message->header, 4))
302     goto failed;
303   
304   if (!_dbus_string_append_len (&message->header, name, 4))
305     goto failed;
306   
307   if (!_dbus_string_append_byte (&message->header, DBUS_TYPE_STRING))
308     goto failed;
309
310   if (!_dbus_string_align_length (&message->header, 4))
311     goto failed;
312   
313   message->header_fields[field].offset =
314     _dbus_string_get_length (&message->header);
315   
316   if (!_dbus_marshal_string (&message->header, message->byte_order,
317                              value))
318     goto failed;
319
320   if (!append_header_padding (message))
321     goto failed;
322   
323   return TRUE;
324   
325  failed:
326   message->header_fields[field].offset = -1;
327   _dbus_string_set_length (&message->header, orig_len);
328
329   /* this must succeed because it was allocated on function entry and
330    * DBusString doesn't ever realloc smaller
331    */
332   if (!append_header_padding (message))
333     _dbus_assert_not_reached ("failed to reappend header padding");
334   
335   return FALSE;
336 }
337
338 static void
339 delete_int_field (DBusMessage *message,
340                   int          field)
341 {
342   int offset = message->header_fields[field].offset;
343
344   _dbus_assert (!message->locked);
345   _dbus_assert (field_is_named[field]);
346   
347   if (offset < 0)
348     return;  
349
350   clear_header_padding (message);
351   
352   /* The field typecode and name take up 8 bytes */
353   _dbus_string_delete (&message->header,
354                        offset - 8,
355                        12);
356
357   message->header_fields[field].offset = -1;
358   
359   adjust_field_offsets (message,
360                         offset - 8,
361                         - 12);
362
363   append_header_padding (message);
364 }
365
366 static void
367 delete_string_field (DBusMessage *message,
368                      int          field)
369 {
370   int offset = message->header_fields[field].offset;
371   int len;
372   int delete_len;
373   
374   _dbus_assert (!message->locked);
375   _dbus_assert (field_is_named[field]);
376   
377   if (offset < 0)
378     return;
379
380   clear_header_padding (message);
381   
382   get_string_field (message, field, &len);
383   
384   /* The field typecode and name take up 8 bytes, and the nul
385    * termination is 1 bytes, string length integer is 4 bytes
386    */
387   delete_len = 8 + 4 + 1 + len;
388   
389   _dbus_string_delete (&message->header,
390                        offset - 8,
391                        delete_len);
392
393   message->header_fields[field].offset = -1;
394   
395   adjust_field_offsets (message,
396                         offset - 8,
397                         - delete_len);
398
399   append_header_padding (message);
400 }
401
402 static dbus_bool_t
403 set_int_field (DBusMessage *message,
404                int          field,
405                int          value)
406 {
407   int offset = message->header_fields[field].offset;
408
409   _dbus_assert (!message->locked);
410   
411   if (offset < 0)
412     {
413       /* need to append the field */
414
415       switch (field)
416         {
417         case FIELD_REPLY_SERIAL:
418           return append_int_field (message, field,
419                                    DBUS_HEADER_FIELD_REPLY,
420                                    value);
421         default:
422           _dbus_assert_not_reached ("appending an int field we don't support appending");
423           return FALSE;
424         }
425     }
426   else
427     {
428       _dbus_marshal_set_int32 (&message->header,
429                                message->byte_order,
430                                offset, value);
431
432       return TRUE;
433     }
434 }
435
436 static dbus_bool_t
437 set_uint_field (DBusMessage  *message,
438                 int           field,
439                 dbus_uint32_t value)
440 {
441   int offset = message->header_fields[field].offset;
442
443   _dbus_assert (!message->locked);
444   
445   if (offset < 0)
446     {
447       /* need to append the field */
448
449       switch (field)
450         {
451         default:
452           _dbus_assert_not_reached ("appending a uint field we don't support appending");
453           return FALSE;
454         }
455     }
456   else
457     {
458       _dbus_marshal_set_uint32 (&message->header,
459                                 message->byte_order,
460                                 offset, value);
461
462       return TRUE;
463     }
464 }
465
466 static dbus_bool_t
467 set_string_field (DBusMessage *message,
468                   int          field,
469                   const char  *value)
470 {
471   int offset = message->header_fields[field].offset;
472
473   _dbus_assert (!message->locked);
474   _dbus_assert (value != NULL);
475   
476   if (offset < 0)
477     {      
478       /* need to append the field */
479
480       switch (field)
481         {
482         case FIELD_SENDER:
483           return append_string_field (message, field,
484                                       DBUS_HEADER_FIELD_SENDER,
485                                       value);
486         default:
487           _dbus_assert_not_reached ("appending a string field we don't support appending");
488           return FALSE;
489         }
490     }
491   else
492     {
493       DBusString v;
494       int old_len;
495       int new_len;
496       int len;
497       
498       clear_header_padding (message);
499       
500       old_len = _dbus_string_get_length (&message->header);
501
502       len = strlen (value);
503       
504       _dbus_string_init_const_len (&v, value,
505                                    len + 1); /* include nul */
506       if (!_dbus_marshal_set_string (&message->header,
507                                      message->byte_order,
508                                      offset, &v,
509                                      len))
510         goto failed;
511       
512       new_len = _dbus_string_get_length (&message->header);
513
514       adjust_field_offsets (message,
515                             offset,
516                             new_len - old_len);
517
518       if (!append_header_padding (message))
519         goto failed;
520       
521       return TRUE;
522
523     failed:
524       /* this must succeed because it was allocated on function entry and
525        * DBusString doesn't ever realloc smaller
526        */
527       if (!append_header_padding (message))
528         _dbus_assert_not_reached ("failed to reappend header padding");
529
530       return FALSE;
531     }
532 }
533
534 /**
535  * Sets the serial number of a message. 
536  * This can only be done once on a message.
537  * 
538  * @param message the message
539  * @param serial the serial
540  */
541 void
542 _dbus_message_set_serial (DBusMessage  *message,
543                           dbus_int32_t  serial)
544 {
545   _dbus_assert (!message->locked);
546   _dbus_assert (dbus_message_get_serial (message) < 0);
547   
548   set_int_field (message, FIELD_CLIENT_SERIAL,
549                  serial);
550   message->client_serial = serial;
551 }
552
553 /**
554  * Sets the reply serial of a message (the client serial
555  * of the message this is a reply to).
556  *
557  * @param message the message
558  * @param reply_serial the client serial
559  * @returns #FALSE if not enough memory
560  */
561 dbus_bool_t
562 dbus_message_set_reply_serial (DBusMessage  *message,
563                                 dbus_int32_t  reply_serial)
564 {
565   _dbus_assert (!message->locked);
566
567   if (set_int_field (message, FIELD_REPLY_SERIAL,
568                      reply_serial))
569     {
570       message->reply_serial = reply_serial;
571       return TRUE;
572     }
573   else
574     return FALSE;
575 }
576
577 /**
578  * Returns the serial of a message or -1 if none has been specified.
579  * The message's serial number is provided by the application sending
580  * the message and is used to identify replies to this message.
581  *
582  * @param message the message
583  * @returns the client serial
584  */
585 dbus_int32_t
586 dbus_message_get_serial (DBusMessage *message)
587 {
588   return message->client_serial;
589 }
590
591 /**
592  * Returns the serial that the message is
593  * a reply to or -1 if none.
594  *
595  * @param message the message
596  * @returns the reply serial
597  */
598 dbus_int32_t
599 dbus_message_get_reply_serial  (DBusMessage *message)
600 {
601   return message->reply_serial;
602 }
603
604 /**
605  * Adds a counter to be incremented immediately with the
606  * size of this message, and decremented by the size
607  * of this message when this message if finalized.
608  *
609  * @param message the message
610  * @param counter the counter
611  */
612 void
613 _dbus_message_add_size_counter (DBusMessage *message,
614                                 DBusCounter *counter)
615 {
616   _dbus_assert (message->size_counter == NULL); /* If this fails we may need to keep a list of
617                                                  * counters instead of just one
618                                                  */
619
620   message->size_counter = counter;
621   _dbus_counter_ref (message->size_counter);
622
623   /* When we can change message size, we may want to
624    * update this each time we do so, or we may want to
625    * just KISS like this.
626    */
627   message->size_counter_delta =
628     _dbus_string_get_length (&message->header) +
629     _dbus_string_get_length (&message->body);
630
631 #if 0
632   _dbus_verbose ("message has size %ld\n",
633                  message->size_counter_delta);
634 #endif
635   
636   _dbus_counter_adjust (message->size_counter, message->size_counter_delta);
637 }
638
639 static dbus_bool_t
640 dbus_message_create_header (DBusMessage *message,
641                             const char  *service,
642                             const char  *name)
643 {
644   unsigned int flags;
645   
646   if (!_dbus_string_append_byte (&message->header, message->byte_order))
647     return FALSE;
648
649   flags = 0;
650   if (!_dbus_string_append_byte (&message->header, flags))
651     return FALSE;
652
653   if (!_dbus_string_append_byte (&message->header, DBUS_MAJOR_PROTOCOL_VERSION))
654     return FALSE;
655
656   if (!_dbus_string_append_byte (&message->header, 0))
657     return FALSE;
658
659   message->header_fields[FIELD_HEADER_LENGTH].offset = 4;
660   if (!_dbus_marshal_uint32 (&message->header, message->byte_order, 0))
661     return FALSE;
662
663   message->header_fields[FIELD_BODY_LENGTH].offset = 8;
664   if (!_dbus_marshal_uint32 (&message->header, message->byte_order, 0))
665     return FALSE;
666
667   message->header_fields[FIELD_CLIENT_SERIAL].offset = 12;
668   if (!_dbus_marshal_int32 (&message->header, message->byte_order, -1))
669     return FALSE;
670   
671   /* Marshal message service */
672   if (service != NULL)
673     {
674       if (!append_string_field (message,
675                                 FIELD_SERVICE,
676                                 DBUS_HEADER_FIELD_SERVICE,
677                                 service))
678         return FALSE;
679     }
680
681   _dbus_assert (name != NULL);
682   if (!append_string_field (message,
683                             FIELD_NAME,
684                             DBUS_HEADER_FIELD_NAME,
685                             name))
686     return FALSE;
687   
688   return TRUE;
689 }
690
691 /**
692  * Locks a message. Allows checking that applications don't keep a
693  * reference to a message in the outgoing queue and change it
694  * underneath us. Messages are locked when they enter the outgoing
695  * queue (dbus_connection_send_message()), and the library complains
696  * if the message is modified while locked.
697  *
698  * @param message the message to lock.
699  */
700 void
701 _dbus_message_lock (DBusMessage  *message)
702 {
703   if (!message->locked)
704     {
705       /* Fill in our lengths */
706       set_uint_field (message,
707                       FIELD_HEADER_LENGTH,
708                       _dbus_string_get_length (&message->header));
709
710       set_uint_field (message,
711                       FIELD_BODY_LENGTH,
712                       _dbus_string_get_length (&message->body));
713
714       message->locked = TRUE;
715     }
716 }
717
718 /** @} */
719
720 /**
721  * @defgroup DBusMessage DBusMessage
722  * @ingroup  DBus
723  * @brief Message to be sent or received over a DBusConnection.
724  *
725  * A DBusMessage is the most basic unit of communication over a
726  * DBusConnection. A DBusConnection represents a stream of messages
727  * received from a remote application, and a stream of messages
728  * sent to a remote application.
729  *
730  * @{
731  */
732
733 /**
734  * @typedef DBusMessage
735  *
736  * Opaque data type representing a message received from or to be
737  * sent to another application.
738  */
739
740 static DBusMessage*
741 dbus_message_new_empty_header (void)
742 {
743   DBusMessage *message;
744   int i;
745   
746   message = dbus_new0 (DBusMessage, 1);
747   if (message == NULL)
748     return NULL;
749   
750   message->refcount = 1;
751   message->byte_order = DBUS_COMPILER_BYTE_ORDER;
752   message->client_serial = -1;
753   message->reply_serial = -1;
754   
755   i = 0;
756   while (i < FIELD_LAST)
757     {
758       message->header_fields[i].offset = -1;
759       ++i;
760     }
761   
762   if (!_dbus_string_init (&message->header, _DBUS_INT_MAX))
763     {
764       dbus_free (message);
765       return NULL;
766     }
767   
768   if (!_dbus_string_init (&message->body, _DBUS_INT_MAX))
769     {
770       _dbus_string_free (&message->header);
771       dbus_free (message);
772       return NULL;
773     }
774   
775   return message;
776 }
777
778
779 /**
780  * Constructs a new message. Returns #NULL if memory can't be
781  * allocated for the message. The service may be #NULL in which case
782  * no service is set; this is appropriate when using D-BUS in a
783  * peer-to-peer context (no message bus).
784  *
785  * @todo reverse the arguments, first 'name' then 'service'
786  * as 'name' is more fundamental
787  *
788  * @param service service that the message should be sent to or #NULL
789  * @param name name of the message
790  * @returns a new DBusMessage, free with dbus_message_unref()
791  * @see dbus_message_unref()
792  */
793 DBusMessage*
794 dbus_message_new (const char *service,
795                   const char *name)
796 {
797   DBusMessage *message;
798
799   message = dbus_message_new_empty_header ();
800   if (message == NULL)
801     return NULL;
802   
803   if (!dbus_message_create_header (message, service, name))
804     {
805       dbus_message_unref (message);
806       return NULL;
807     }
808   
809   return message;
810 }
811
812 /**
813  * Constructs a message that is a reply to some other
814  * message. Returns #NULL if memory can't be allocated
815  * for the message.
816  *
817  * @param original_message the message which the created
818  * message is a reply to.
819  * @returns a new DBusMessage, free with dbus_message_unref()
820  * @see dbus_message_new(), dbus_message_unref()
821  */ 
822 DBusMessage*
823 dbus_message_new_reply (DBusMessage *original_message)
824 {
825   DBusMessage *message;
826   const char *sender, *name;
827
828   sender = get_string_field (original_message,
829                              FIELD_SENDER, NULL);
830   name = get_string_field (original_message,
831                            FIELD_NAME, NULL);
832
833   /* sender is allowed to be null here in peer-to-peer case */
834   
835   message = dbus_message_new (sender, name);
836   
837   if (message == NULL)
838     return NULL;
839
840   if (!dbus_message_set_reply_serial (message,
841                                       dbus_message_get_serial (original_message)))
842     {
843       dbus_message_unref (message);
844       return NULL;
845     }
846
847   return message;
848 }
849
850 /**
851  * Creates a new message that is an error reply to a certain message.
852  *
853  * @param original_message the original message
854  * @param error_name the error name
855  * @param error_message the error message string
856  * @returns a new error message
857  */
858 DBusMessage*
859 dbus_message_new_error_reply (DBusMessage *original_message,
860                               const char  *error_name,
861                               const char  *error_message)
862 {
863   DBusMessage *message;
864   const char *sender;
865
866   sender = get_string_field (original_message,
867                              FIELD_SENDER, NULL);
868   
869   _dbus_assert (sender != NULL);
870   
871   message = dbus_message_new (sender, error_name);
872   
873   if (message == NULL)
874     return NULL;
875
876   if (!dbus_message_set_reply_serial (message,
877                                       dbus_message_get_serial (original_message)))
878     {
879       dbus_message_unref (message);
880       return NULL;
881     }
882
883   if (!dbus_message_append_string (message, error_message))
884     {
885       dbus_message_unref (message);
886       return NULL;
887     }
888
889   dbus_message_set_is_error (message, TRUE);
890   
891   return message;
892 }
893
894 /**
895  * Creates a new message that is an exact replica of the message
896  * specified, except that its refcount is set to 1.
897  *
898  * @param message the message.
899  * @returns the new message.
900  */
901 DBusMessage *
902 dbus_message_copy (const DBusMessage *message)
903 {
904   DBusMessage *retval;
905   int i;
906   
907   retval = dbus_new0 (DBusMessage, 1);
908   if (retval == NULL)
909     return NULL;
910   
911   retval->refcount = 1;
912   retval->byte_order = message->byte_order;
913   retval->client_serial = message->client_serial;
914   retval->reply_serial = message->reply_serial;
915   retval->header_padding = message->header_padding;
916   retval->locked = FALSE;
917   
918   if (!_dbus_string_init (&retval->header, _DBUS_INT_MAX))
919     {
920       dbus_free (retval);
921       return NULL;
922     }
923   
924   if (!_dbus_string_init (&retval->body, _DBUS_INT_MAX))
925     {
926       _dbus_string_free (&retval->header);
927       dbus_free (retval);
928       return NULL;
929     }
930
931   if (!_dbus_string_copy (&message->header, 0,
932                           &retval->header, 0))
933     {
934       _dbus_string_free (&retval->header);
935       _dbus_string_free (&retval->body);
936       dbus_free (retval);
937
938       return NULL;
939     }
940
941   if (!_dbus_string_copy (&message->body, 0,
942                           &retval->body, 0))
943     {
944       _dbus_string_free (&retval->header);
945       _dbus_string_free (&retval->body);
946       dbus_free (retval);
947
948       return NULL;
949     }
950
951   for (i = 0; i < FIELD_LAST; i++)
952     {
953       retval->header_fields[i].offset = message->header_fields[i].offset;
954     }
955   
956   return retval;
957 }
958
959
960 /**
961  * Increments the reference count of a DBusMessage.
962  *
963  * @param message The message
964  * @see dbus_message_unref
965  */
966 void
967 dbus_message_ref (DBusMessage *message)
968 {
969   dbus_atomic_t refcount;
970
971   refcount = _dbus_atomic_inc (&message->refcount);
972   _dbus_assert (refcount > 1);
973 }
974
975 /**
976  * Decrements the reference count of a DBusMessage.
977  *
978  * @param message The message
979  * @see dbus_message_ref
980  */
981 void
982 dbus_message_unref (DBusMessage *message)
983 {
984   dbus_atomic_t refcount;
985
986   refcount = _dbus_atomic_dec (&message->refcount);
987   
988   _dbus_assert (refcount >= 0);
989
990   if (refcount == 0)
991     {
992       if (message->size_counter != NULL)
993         {
994           _dbus_counter_adjust (message->size_counter,
995                                 - message->size_counter_delta);
996           _dbus_counter_unref (message->size_counter);
997         }
998       
999       _dbus_string_free (&message->header);
1000       _dbus_string_free (&message->body);
1001       
1002       dbus_free (message);
1003     }
1004 }
1005
1006 /**
1007  * Gets the name of a message.
1008  *
1009  * @param message the message
1010  * @returns the message name (should not be freed)
1011  */
1012 const char*
1013 dbus_message_get_name (DBusMessage *message)
1014 {
1015   return get_string_field (message, FIELD_NAME, NULL);
1016 }
1017
1018 /**
1019  * Gets the destination service of a message.
1020  *
1021  * @todo I think if we have set_sender/get_sender,
1022  * this function might be better named set_destination/
1023  * get_destination for clarity, as the sender
1024  * is also a service name.
1025  * 
1026  * @param message the message
1027  * @returns the message destination service (should not be freed)
1028  */
1029 const char*
1030 dbus_message_get_service (DBusMessage *message)
1031 {
1032   return get_string_field (message, FIELD_SERVICE, NULL);
1033 }
1034
1035 /**
1036  * Appends fields to a message given a variable argument
1037  * list. The variable argument list should contain the type
1038  * of the argument followed by the value to add. Array values
1039  * are specified by a pointer to the array followed by an int
1040  * giving the length of the array. The list is terminated
1041  * with 0.
1042  *
1043  * @param message the message
1044  * @param first_arg_type type of the first argument
1045  * @param ... value of first argument, list of additional type-value pairs
1046  * @returns #TRUE on success
1047  */
1048 dbus_bool_t
1049 dbus_message_append_args (DBusMessage *message,
1050                           int first_arg_type,
1051                           ...)
1052 {
1053   dbus_bool_t retval;
1054   va_list var_args;
1055
1056   va_start (var_args, first_arg_type);
1057   retval = dbus_message_append_args_valist (message,
1058                                             first_arg_type,
1059                                             var_args);
1060   va_end (var_args);
1061
1062   return retval;
1063 }
1064
1065 /**
1066  * This function takes a va_list for use by language bindings
1067  *
1068  * @see dbus_message_append_args.  
1069  * @param message the message
1070  * @param first_arg_type type of first argument
1071  * @param var_args value of first argument, then list of type/value pairs
1072  * @returns #TRUE on success
1073  */
1074 dbus_bool_t
1075 dbus_message_append_args_valist (DBusMessage *message,
1076                                  int          first_arg_type,
1077                                  va_list      var_args)
1078 {
1079   int type, old_len;
1080
1081   old_len = _dbus_string_get_length (&message->body);
1082   
1083   type = first_arg_type;
1084
1085   while (type != 0)
1086     {
1087       switch (type)
1088         {
1089         case DBUS_TYPE_NIL:
1090           if (!dbus_message_append_nil (message))
1091             goto enomem;
1092         case DBUS_TYPE_BOOLEAN:
1093           if (!dbus_message_append_boolean (message, va_arg (var_args, dbus_bool_t)))
1094             goto enomem;
1095           break;
1096         case DBUS_TYPE_INT32:
1097           if (!dbus_message_append_int32 (message, va_arg (var_args, dbus_int32_t)))
1098             goto enomem;
1099           break;
1100         case DBUS_TYPE_UINT32:
1101           if (!dbus_message_append_uint32 (message, va_arg (var_args, dbus_uint32_t)))
1102             goto enomem;            
1103           break;
1104         case DBUS_TYPE_DOUBLE:
1105           if (!dbus_message_append_double (message, va_arg (var_args, double)))
1106             goto enomem;
1107           break;
1108         case DBUS_TYPE_STRING:
1109           if (!dbus_message_append_string (message, va_arg (var_args, const char *)))
1110             goto enomem;
1111           break;
1112         case DBUS_TYPE_BOOLEAN_ARRAY:
1113           {
1114             int len;
1115             unsigned char *data;
1116
1117             data = va_arg (var_args, unsigned char *);
1118             len = va_arg (var_args, int);
1119
1120             if (!dbus_message_append_boolean_array (message, data, len))
1121               goto enomem;
1122           }
1123           break;
1124         case DBUS_TYPE_INT32_ARRAY:
1125           {
1126             int len;
1127             dbus_int32_t *data;
1128
1129             data = va_arg (var_args, dbus_int32_t *);
1130             len = va_arg (var_args, int);
1131
1132             if (!dbus_message_append_int32_array (message, data, len))
1133               goto enomem;
1134           }
1135           break;
1136         case DBUS_TYPE_UINT32_ARRAY:
1137           {
1138             int len;
1139             dbus_uint32_t *data;
1140
1141             data = va_arg (var_args, dbus_uint32_t *);
1142             len = va_arg (var_args, int);
1143
1144             if (!dbus_message_append_uint32_array (message, data, len))
1145               goto enomem;
1146           }
1147           break;
1148         case DBUS_TYPE_DOUBLE_ARRAY:
1149           {
1150             int len;
1151             double *data;
1152
1153             data = va_arg (var_args, double *);
1154             len = va_arg (var_args, int);
1155
1156             if (!dbus_message_append_double_array (message, data, len))
1157               goto enomem;
1158           }
1159           break;
1160         case DBUS_TYPE_BYTE_ARRAY:
1161           {
1162             int len;
1163             unsigned char *data;
1164
1165             data = va_arg (var_args, unsigned char *);
1166             len = va_arg (var_args, int);
1167
1168             if (!dbus_message_append_byte_array (message, data, len))
1169               goto enomem;
1170           }
1171           break;
1172         case DBUS_TYPE_STRING_ARRAY:
1173           {
1174             int len;
1175             const char **data;
1176             
1177             data = va_arg (var_args, const char **);
1178             len = va_arg (var_args, int);
1179
1180             if (!dbus_message_append_string_array (message, data, len))
1181               goto enomem;
1182           }
1183           break;
1184         case DBUS_TYPE_DICT:
1185           {
1186             DBusDict *dict;
1187
1188             dict = va_arg (var_args, DBusDict *);
1189
1190             if (!dbus_message_append_dict (message, dict))
1191               goto enomem;
1192             break;
1193           }
1194         default:
1195           _dbus_warn ("Unknown field type %d\n", type);
1196         }
1197
1198       type = va_arg (var_args, int);
1199     }
1200
1201   return TRUE;
1202
1203  enomem:
1204   return FALSE;
1205 }
1206
1207 /**
1208  * Appends a nil value to the message
1209  *
1210  * @param message the message
1211  * @returns #TRUE on success
1212  */
1213 dbus_bool_t
1214 dbus_message_append_nil (DBusMessage *message)
1215 {
1216   _dbus_assert (!message->locked);
1217
1218   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_NIL))
1219       return FALSE;
1220   else
1221     return TRUE;
1222 }
1223
1224 /**
1225  * Appends a boolean value to the message
1226  *
1227  * @param message the message
1228  * @param value the boolean value
1229  * @returns #TRUE on success
1230  */
1231 dbus_bool_t
1232 dbus_message_append_boolean (DBusMessage  *message,
1233                              dbus_bool_t   value)
1234 {
1235   _dbus_assert (!message->locked);
1236   
1237   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_BOOLEAN))
1238     return FALSE;
1239
1240   if (!_dbus_string_append_byte (&message->body, (value != FALSE)))
1241     {
1242       _dbus_string_shorten (&message->body, 1);
1243       return FALSE;
1244     }
1245
1246   return TRUE;
1247 }
1248
1249 /**
1250  * Appends a 32 bit signed integer to the message.
1251  *
1252  * @param message the message
1253  * @param value the integer value
1254  * @returns #TRUE on success
1255  */
1256 dbus_bool_t
1257 dbus_message_append_int32 (DBusMessage  *message,
1258                            dbus_int32_t  value)
1259 {
1260   _dbus_assert (!message->locked);
1261
1262   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_INT32))
1263       return FALSE;
1264   
1265   if (!_dbus_marshal_int32 (&message->body, message->byte_order, value))
1266     {
1267       _dbus_string_shorten (&message->body, 1);
1268       return FALSE;
1269     }
1270
1271   return TRUE;
1272 }
1273
1274 /**
1275  * Appends a 32 bit unsigned integer to the message.
1276  *
1277  * @param message the message
1278  * @param value the integer value
1279  * @returns #TRUE on success
1280  */
1281 dbus_bool_t
1282 dbus_message_append_uint32 (DBusMessage   *message,
1283                             dbus_uint32_t  value)
1284 {
1285   _dbus_assert (!message->locked);
1286
1287   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_UINT32))
1288       return FALSE;
1289   
1290   if (!_dbus_marshal_uint32 (&message->body, message->byte_order, value))
1291     {
1292       _dbus_string_shorten (&message->body, 1);
1293       return FALSE;
1294     }
1295
1296   return TRUE;      
1297 }
1298
1299 /**
1300  * Appends a double value to the message.
1301  *
1302  * @param message the message
1303  * @param value the double value
1304  * @returns #TRUE on success
1305  */
1306 dbus_bool_t
1307 dbus_message_append_double (DBusMessage *message,
1308                             double       value)
1309 {
1310   _dbus_assert (!message->locked);
1311
1312   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_DOUBLE))
1313     return FALSE;
1314
1315   if (!_dbus_marshal_double (&message->body, message->byte_order, value))
1316     {
1317       _dbus_string_shorten (&message->body, 1);
1318       return FALSE;
1319     }
1320   
1321   return TRUE;
1322 }
1323
1324 /**
1325  * Appends a UTF-8 string to the message.
1326  *
1327  * @param message the message
1328  * @param value the string
1329  * @returns #TRUE on success
1330  */
1331 dbus_bool_t
1332 dbus_message_append_string (DBusMessage *message,
1333                             const char  *value)
1334 {
1335   _dbus_assert (!message->locked);
1336
1337   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_STRING))
1338       return FALSE;
1339   
1340   if (!_dbus_marshal_string (&message->body, message->byte_order, value))
1341     {
1342       _dbus_string_shorten (&message->body, 1);
1343       return FALSE;      
1344     }
1345
1346   return TRUE;
1347 }
1348
1349 /**
1350  * Appends a boolean array to the message.
1351  *
1352  * @param message the message
1353  * @param value the array
1354  * @param len the length of the array
1355  * @returns #TRUE on success
1356  */
1357 dbus_bool_t
1358 dbus_message_append_boolean_array (DBusMessage         *message,
1359                                    unsigned const char *value,
1360                                    int                  len)
1361 {
1362   _dbus_assert (!message->locked);
1363
1364   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_BOOLEAN_ARRAY))
1365     return FALSE;
1366
1367   if (!_dbus_marshal_byte_array (&message->body, message->byte_order, value, len))
1368     {
1369       _dbus_string_shorten (&message->body, 1);
1370       return FALSE;
1371     }
1372
1373   return TRUE;
1374 }
1375
1376 /**
1377  * Appends a 32 bit signed integer array to the message.
1378  *
1379  * @param message the message
1380  * @param value the array
1381  * @param len the length of the array
1382  * @returns #TRUE on success
1383  */
1384 dbus_bool_t
1385 dbus_message_append_int32_array (DBusMessage        *message,
1386                                  const dbus_int32_t *value,
1387                                  int                 len)
1388 {
1389   _dbus_assert (!message->locked);
1390
1391   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_INT32_ARRAY))
1392     return FALSE;
1393
1394   if (!_dbus_marshal_int32_array (&message->body, message->byte_order,
1395                                   value, len))
1396     {
1397       _dbus_string_shorten (&message->body, 1);
1398       return FALSE;
1399     }
1400
1401   return TRUE;
1402 }
1403
1404 /**
1405  * Appends a 32 bit unsigned integer array to the message.
1406  *
1407  * @param message the message
1408  * @param value the array
1409  * @param len the length of the array
1410  * @returns #TRUE on success
1411  */
1412 dbus_bool_t
1413 dbus_message_append_uint32_array (DBusMessage         *message,
1414                                   const dbus_uint32_t *value,
1415                                   int                  len)
1416 {
1417   _dbus_assert (!message->locked);
1418
1419   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_UINT32_ARRAY))
1420     return FALSE;
1421
1422   if (!_dbus_marshal_uint32_array (&message->body, message->byte_order,
1423                                   value, len))
1424     {
1425       _dbus_string_shorten (&message->body, 1);
1426       return FALSE;
1427     }
1428
1429   return TRUE;
1430 }
1431
1432 /**
1433  * Appends a double array to the message.
1434  *
1435  * @param message the message
1436  * @param value the array
1437  * @param len the length of the array
1438  * @returns #TRUE on success
1439  */
1440 dbus_bool_t
1441 dbus_message_append_double_array (DBusMessage  *message,
1442                                   const double *value,
1443                                   int           len)
1444 {
1445   _dbus_assert (!message->locked);
1446
1447   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_DOUBLE_ARRAY))
1448     return FALSE;
1449
1450   if (!_dbus_marshal_double_array (&message->body, message->byte_order,
1451                                    value, len))
1452     {
1453       _dbus_string_shorten (&message->body, 1);
1454       return FALSE;
1455     }
1456
1457   return TRUE;
1458 }
1459
1460 /**
1461  * Appends a byte array to the message.
1462  *
1463  * @param message the message
1464  * @param value the array
1465  * @param len the length of the array
1466  * @returns #TRUE on success
1467  */
1468 dbus_bool_t
1469 dbus_message_append_byte_array (DBusMessage         *message,
1470                                 unsigned const char *value,
1471                                 int                 len)
1472 {
1473   _dbus_assert (!message->locked);
1474
1475   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_BYTE_ARRAY))
1476     return FALSE;
1477   
1478   if (!_dbus_marshal_byte_array (&message->body, message->byte_order, value, len))
1479     {
1480       _dbus_string_shorten (&message->body, 1);
1481       return FALSE;
1482     }
1483       
1484   return TRUE;
1485 }
1486
1487 /**
1488  * Appends a string array to the message.
1489  *
1490  * @param message the message
1491  * @param value the array
1492  * @param len the length of the array
1493  * @returns #TRUE on success
1494  */
1495 dbus_bool_t
1496 dbus_message_append_string_array (DBusMessage  *message,
1497                                   const char  **value,
1498                                   int           len)
1499 {
1500   _dbus_assert (!message->locked);
1501
1502   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_STRING_ARRAY))
1503     return FALSE;
1504
1505   if (!_dbus_marshal_string_array (&message->body, message->byte_order,
1506                                    (const char **)value, len))
1507     {
1508       _dbus_string_shorten (&message->body, 1);
1509       return FALSE;
1510     }
1511
1512   return TRUE;
1513 }
1514
1515 /**
1516  * Appends a dict to the message.
1517  *
1518  * @param message the message
1519  * @param dict the dict
1520  * @returns #TRUE on success
1521  */
1522 dbus_bool_t
1523 dbus_message_append_dict (DBusMessage *message,
1524                           DBusDict    *dict)
1525 {
1526   _dbus_assert (!message->locked);
1527
1528   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_DICT))
1529     return FALSE;
1530
1531   if (!_dbus_marshal_dict (&message->body, message->byte_order, dict))
1532     {
1533       _dbus_string_shorten (&message->body, 1);
1534       return FALSE;
1535     }
1536
1537   return TRUE;
1538 }
1539
1540 /**
1541  * Gets arguments from a message given a variable argument list.
1542  * The variable argument list should contain the type of the
1543  * argumen followed by a pointer to where the value should be
1544  * stored. The list is terminated with 0.
1545  *
1546  * @param message the message
1547  * @param error error to be filled in on failure
1548  * @param first_arg_type the first argument type
1549  * @param ... location for first argument value, then list of type-location pairs
1550  * @returns #FALSE if the error was set
1551  */
1552 dbus_bool_t
1553 dbus_message_get_args (DBusMessage *message,
1554                        DBusError   *error,
1555                        int          first_arg_type,
1556                        ...)
1557 {
1558   dbus_bool_t retval;
1559   va_list var_args;
1560
1561   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1562   
1563   va_start (var_args, first_arg_type);
1564   retval = dbus_message_get_args_valist (message, error, first_arg_type, var_args);
1565   va_end (var_args);
1566
1567   return retval;
1568 }
1569
1570 /**
1571  * This function takes a va_list for use by language bindings
1572  *
1573  * @todo this function (or some lower-level non-convenience function)
1574  * needs better error handling; should allow the application to
1575  * distinguish between out of memory, and bad data from the remote
1576  * app. It also needs to not leak a bunch of args when it gets
1577  * to the arg that's bad, as that would be a security hole
1578  * (allow one app to force another to leak memory)
1579  *
1580  * @todo We need to free the argument data when an error occurs.
1581  *
1582  * @see dbus_message_get_args
1583  * @param message the message
1584  * @param error error to be filled in
1585  * @param first_arg_type type of the first argument
1586  * @param var_args return location for first argument, followed by list of type/location pairs
1587  * @returns #FALSE if error was set
1588  */
1589 dbus_bool_t
1590 dbus_message_get_args_valist (DBusMessage *message,
1591                               DBusError   *error,
1592                               int          first_arg_type,
1593                               va_list      var_args)
1594 {
1595   int spec_type, msg_type, i;
1596   DBusMessageIter *iter;
1597   dbus_bool_t retval;
1598
1599   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1600   
1601   iter = dbus_message_get_args_iter (message);
1602
1603   if (iter == NULL)
1604     {
1605       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1606       return FALSE;
1607     }
1608
1609   retval = FALSE;
1610   
1611   spec_type = first_arg_type;
1612   i = 0;
1613   
1614   while (spec_type != 0)
1615     {
1616       msg_type = dbus_message_iter_get_arg_type (iter);      
1617       
1618       if (msg_type != spec_type)
1619         {
1620           dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
1621                           "Argument %d is specified to be of type \"%s\", but "
1622                           "is actually of type \"%s\"\n", i,
1623                           _dbus_type_to_string (spec_type),
1624                           _dbus_type_to_string (msg_type));
1625
1626           goto out;
1627         }
1628
1629       switch (spec_type)
1630         {
1631         case DBUS_TYPE_NIL:
1632           break;
1633         case DBUS_TYPE_BOOLEAN:
1634           {
1635             dbus_bool_t *ptr;
1636
1637             ptr = va_arg (var_args, dbus_bool_t *);
1638
1639             *ptr = dbus_message_iter_get_boolean (iter);
1640             break;
1641           }
1642         case DBUS_TYPE_INT32:
1643           {
1644             dbus_int32_t *ptr;
1645
1646             ptr = va_arg (var_args, dbus_int32_t *);
1647
1648             *ptr = dbus_message_iter_get_int32 (iter);
1649             break;
1650           }
1651         case DBUS_TYPE_UINT32:
1652           {
1653             dbus_uint32_t *ptr;
1654
1655             ptr = va_arg (var_args, dbus_uint32_t *);
1656
1657             *ptr = dbus_message_iter_get_uint32 (iter);
1658             break;
1659           }
1660
1661         case DBUS_TYPE_DOUBLE:
1662           {
1663             double *ptr;
1664
1665             ptr = va_arg (var_args, double *);
1666
1667             *ptr = dbus_message_iter_get_double (iter);
1668             break;
1669           }
1670
1671         case DBUS_TYPE_STRING:
1672           {
1673             char **ptr;
1674
1675             ptr = va_arg (var_args, char **);
1676
1677             *ptr = dbus_message_iter_get_string (iter);
1678
1679             if (!*ptr)
1680               {
1681                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1682                 goto out;
1683               }
1684             
1685             break;
1686           }
1687
1688         case DBUS_TYPE_BOOLEAN_ARRAY:
1689           {
1690             unsigned char **ptr;
1691             int *len;
1692
1693             ptr = va_arg (var_args, unsigned char **);
1694             len = va_arg (var_args, int *);
1695
1696             if (!dbus_message_iter_get_boolean_array (iter, ptr, len))
1697               {
1698                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1699                 goto out;
1700               }
1701             break;
1702           }
1703           
1704         case DBUS_TYPE_INT32_ARRAY:
1705           {
1706             dbus_int32_t **ptr;
1707             int *len;
1708
1709             ptr = va_arg (var_args, dbus_int32_t **);
1710             len = va_arg (var_args, int *);
1711
1712             if (!dbus_message_iter_get_int32_array (iter, ptr, len))
1713               {
1714                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1715                 goto out;
1716               }
1717             
1718             break;
1719           }
1720
1721         case DBUS_TYPE_UINT32_ARRAY:
1722           {
1723             dbus_uint32_t **ptr;
1724             int *len;
1725
1726             ptr = va_arg (var_args, dbus_uint32_t **);
1727             len = va_arg (var_args, int *);
1728
1729             if (!dbus_message_iter_get_uint32_array (iter, ptr, len))
1730               {
1731                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1732                 goto out;
1733               }
1734             
1735             break;
1736           }
1737
1738         case DBUS_TYPE_DOUBLE_ARRAY:
1739           {
1740             double **ptr;
1741             int *len;
1742
1743             ptr = va_arg (var_args, double **);
1744             len = va_arg (var_args, int *);
1745
1746             if (!dbus_message_iter_get_double_array (iter, ptr, len))
1747               {
1748                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1749                 goto out;
1750               }
1751             break;
1752           }
1753           
1754         case DBUS_TYPE_BYTE_ARRAY:
1755           {
1756             unsigned char **ptr;
1757             int *len;
1758
1759             ptr = va_arg (var_args, unsigned char **);
1760             len = va_arg (var_args, int *);
1761
1762             if (!dbus_message_iter_get_byte_array (iter, ptr, len))
1763               {
1764                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1765                 goto out;
1766               }
1767             break;
1768           }
1769         case DBUS_TYPE_STRING_ARRAY:
1770           {
1771             char ***ptr;
1772             int *len;
1773
1774             ptr = va_arg (var_args, char ***);
1775             len = va_arg (var_args, int *);
1776
1777             if (!dbus_message_iter_get_string_array (iter, ptr, len))
1778               {
1779                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1780                 goto out;
1781               }
1782             break;
1783           }
1784         case DBUS_TYPE_DICT:
1785           {
1786             DBusDict **dict;
1787
1788             dict = va_arg (var_args, DBusDict **);
1789
1790             if (!dbus_message_iter_get_dict (iter, dict))
1791               {
1792                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1793                 goto out;
1794               }
1795             break;
1796           }
1797         default:          
1798           _dbus_warn ("Unknown field type %d\n", spec_type);
1799         }
1800       
1801       spec_type = va_arg (var_args, int);
1802       if (spec_type != 0 && !dbus_message_iter_next (iter))
1803         {
1804           dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
1805                           "Message has only %d arguments, but more were expected", i);
1806           goto out;
1807         }
1808
1809       i++;
1810     }
1811   
1812   retval = TRUE;
1813   
1814  out:
1815   dbus_message_iter_unref (iter);
1816   return retval;
1817 }
1818
1819 /**
1820  * Returns a DBusMessageIter representing the arguments of the
1821  * message passed in.
1822  *
1823  * @todo IMO the message iter should follow the GtkTextIter pattern,
1824  * a static object with a "stamp" value used to detect invalid
1825  * iter uses (uninitialized or after changing the message).
1826  * ref/unref is kind of annoying to deal with, and slower too.
1827  * This implies not ref'ing the message from the iter.
1828  *
1829  * @todo I'd also name this dbus_message_iter_new() or
1830  * for the static object dbus_message_iter_init() rather
1831  * than making it a method on the message
1832  *
1833  * @param message the message
1834  * @returns a new iter.
1835  */
1836 DBusMessageIter *
1837 dbus_message_get_args_iter (DBusMessage *message)
1838 {
1839   DBusMessageIter *iter;
1840   
1841   iter = dbus_new (DBusMessageIter, 1);
1842
1843   if (iter != NULL)
1844     {
1845       dbus_message_ref (message);
1846   
1847       iter->refcount = 1;
1848       iter->message = message;
1849       iter->pos = 0;
1850     }
1851   
1852   return iter;
1853 }
1854
1855 /**
1856  * Increments the reference count of a DBusMessageIter.
1857  *
1858  * @param iter the message iter
1859  * @see dbus_message_iter_unref
1860  */
1861 void
1862 dbus_message_iter_ref (DBusMessageIter *iter)
1863 {
1864   _dbus_assert (iter->refcount > 0);
1865   
1866   iter->refcount += 1;
1867 }
1868
1869 /**
1870  * Decrements the reference count of a DBusMessageIter.
1871  *
1872  * @param iter The message iter
1873  * @see dbus_message_iter_ref
1874  */
1875 void
1876 dbus_message_iter_unref (DBusMessageIter *iter)
1877 {
1878   _dbus_assert (iter->refcount > 0);
1879
1880   iter->refcount -= 1;
1881
1882   if (iter->refcount == 0)
1883     {
1884       dbus_message_unref (iter->message);
1885
1886       dbus_free (iter);
1887     }
1888 }
1889
1890 /**
1891  * Checks if an iterator has any more fields.
1892  *
1893  * @param iter the message iter
1894  * @returns #TRUE if there are more fields
1895  * following
1896  */
1897 dbus_bool_t
1898 dbus_message_iter_has_next (DBusMessageIter *iter)
1899 {
1900   int end_pos;
1901   
1902   if (!_dbus_marshal_get_arg_end_pos (&iter->message->body,
1903                                       iter->message->byte_order,
1904                                       iter->pos, &end_pos))
1905     return FALSE;
1906   
1907   if (end_pos >= _dbus_string_get_length (&iter->message->body))
1908     return FALSE;
1909   
1910   return TRUE;  
1911 }
1912
1913 /**
1914  * Moves the iterator to the next field.
1915  *
1916  * @param iter The message iter
1917  * @returns #TRUE if the iterator was moved to the next field
1918  */
1919 dbus_bool_t
1920 dbus_message_iter_next (DBusMessageIter *iter)
1921 {
1922   int end_pos;
1923   
1924   if (!_dbus_marshal_get_arg_end_pos (&iter->message->body,
1925                                       iter->message->byte_order,
1926                                       iter->pos, &end_pos))
1927     return FALSE;
1928
1929   if (end_pos >= _dbus_string_get_length (&iter->message->body))
1930     return FALSE;
1931
1932   iter->pos = end_pos;
1933
1934   return TRUE;
1935 }
1936
1937 /**
1938  * Returns the argument type of the argument that the
1939  * message iterator points at.
1940  *
1941  * @param iter the message iter
1942  * @returns the field type
1943  */
1944 int
1945 dbus_message_iter_get_arg_type (DBusMessageIter *iter)
1946 {
1947   const char *data;
1948
1949   if (iter->pos >= _dbus_string_get_length (&iter->message->body))
1950     return DBUS_TYPE_INVALID;
1951
1952   _dbus_string_get_const_data_len (&iter->message->body, &data, iter->pos, 1);
1953
1954   if (*data > DBUS_TYPE_INVALID && *data <= DBUS_TYPE_DICT)
1955     return *data;
1956
1957   return DBUS_TYPE_INVALID;
1958 }
1959
1960 /**
1961  * Returns the string value that an iterator may point to.
1962  * Note that you need to check that the iterator points to
1963  * a string value before using this function.
1964  *
1965  * @see dbus_message_iter_get_arg_type
1966  * @param iter the message iter
1967  * @returns the string
1968  */
1969 char *
1970 dbus_message_iter_get_string (DBusMessageIter *iter)
1971 {
1972   _dbus_assert (dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_STRING);
1973
1974   return _dbus_demarshal_string (&iter->message->body, iter->message->byte_order,
1975                                  iter->pos + 1, NULL);
1976 }
1977
1978 /**
1979  * Returns the boolean value that an iterator may point to.
1980  * Note that you need to check that the iterator points to
1981  * a boolean value before using this function.
1982  *
1983  * @see dbus_message_iter_get_arg_type
1984  * @param iter the message iter
1985  * @returns the string
1986  */
1987 dbus_bool_t
1988 dbus_message_iter_get_boolean (DBusMessageIter *iter)
1989 {
1990   unsigned char value;
1991   
1992   _dbus_assert (dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_BOOLEAN);
1993
1994   value = _dbus_string_get_byte (&iter->message->body, iter->pos + 1);
1995   
1996   return value;
1997 }
1998
1999 /**
2000  * Returns the 32 bit signed integer value that an iterator may point to.
2001  * Note that you need to check that the iterator points to
2002  * an integer value before using this function.
2003  *
2004  * @see dbus_message_iter_get_arg_type
2005  * @param iter the message iter
2006  * @returns the integer
2007  */
2008 int
2009 dbus_message_iter_get_int32 (DBusMessageIter *iter)
2010 {
2011   _dbus_assert (dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_INT32);
2012   
2013   return _dbus_demarshal_int32 (&iter->message->body, iter->message->byte_order,
2014                                 iter->pos + 1, NULL);
2015 }
2016
2017 /**
2018  * Returns the 32 bit unsigned integer value that an iterator may point to.
2019  * Note that you need to check that the iterator points to
2020  * an unsigned integer value before using this function.
2021  *
2022  * @see dbus_message_iter_get_arg_type
2023  * @param iter the message iter
2024  * @returns the integer
2025  */
2026 int
2027 dbus_message_iter_get_uint32 (DBusMessageIter *iter)
2028 {
2029   _dbus_assert (dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_UINT32);
2030   
2031   return _dbus_demarshal_uint32 (&iter->message->body, iter->message->byte_order,
2032                                  iter->pos + 1, NULL);
2033 }
2034
2035 /**
2036  * Returns the double value that an iterator may point to.
2037  * Note that you need to check that the iterator points to
2038  * a string value before using this function.
2039  *
2040  * @see dbus_message_iter_get_arg_type
2041  * @param iter the message iter
2042  * @returns the double
2043  */
2044 double
2045 dbus_message_iter_get_double (DBusMessageIter *iter)
2046 {
2047   _dbus_assert (dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_DOUBLE);
2048   
2049   return _dbus_demarshal_double (&iter->message->body, iter->message->byte_order,
2050                                  iter->pos + 1, NULL);
2051 }
2052
2053 /**
2054  * Returns the boolean array that the iterator may point to. Note that
2055  * you need to check that the iterator points to an array of the
2056  * correct type prior to using this function.
2057  *
2058  * @param iter the iterator
2059  * @param value return location for the array
2060  * @param len return location for the array length
2061  * @returns #TRUE on success
2062  */
2063 dbus_bool_t
2064 dbus_message_iter_get_boolean_array (DBusMessageIter   *iter,
2065                                      unsigned char    **value,
2066                                      int               *len)
2067 {
2068   _dbus_assert (dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_BOOLEAN_ARRAY);
2069
2070   if (!_dbus_demarshal_byte_array (&iter->message->body, iter->message->byte_order,
2071                                    iter->pos + 1, NULL, value, len))
2072     return FALSE;
2073   else
2074     return TRUE;
2075 }
2076
2077 /**
2078  * Returns the 32 bit signed integer array that the iterator may point
2079  * to. Note that you need to check that the iterator points to an
2080  * array of the correct type prior to using this function.
2081  *
2082  * @param iter the iterator
2083  * @param value return location for the array
2084  * @param len return location for the array length
2085  * @returns #TRUE on success
2086  */
2087 dbus_bool_t
2088 dbus_message_iter_get_int32_array  (DBusMessageIter *iter,
2089                                     dbus_int32_t   **value,
2090                                     int             *len)
2091 {
2092   _dbus_assert (dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_INT32_ARRAY);
2093
2094   if (!_dbus_demarshal_int32_array (&iter->message->body, iter->message->byte_order,
2095                                     iter->pos + 1, NULL, value, len))
2096     return FALSE;
2097   else
2098     return TRUE;
2099 }
2100
2101 /**
2102  * Returns the 32 bit unsigned integer array that the iterator may point
2103  * to. Note that you need to check that the iterator points to an
2104  * array of the correct type prior to using this function.
2105  *
2106  * @param iter the iterator
2107  * @param value return location for the array
2108  * @param len return location for the array length
2109  * @returns #TRUE on success
2110  */
2111 dbus_bool_t
2112 dbus_message_iter_get_uint32_array  (DBusMessageIter *iter,
2113                                      dbus_uint32_t  **value,
2114                                      int             *len)
2115 {
2116   _dbus_assert (dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_UINT32_ARRAY);
2117
2118   if (!_dbus_demarshal_uint32_array (&iter->message->body, iter->message->byte_order,
2119                                      iter->pos + 1, NULL, value, len))
2120     return FALSE;
2121   else
2122     return TRUE;
2123 }
2124
2125 /**
2126  * Returns the double array that the iterator may point to. Note that
2127  * you need to check that the iterator points to an array of the
2128  * correct type prior to using this function.
2129  *
2130  * @param iter the iterator
2131  * @param value return location for the array
2132  * @param len return location for the array length
2133  * @returns #TRUE on success
2134  */
2135 dbus_bool_t
2136 dbus_message_iter_get_double_array  (DBusMessageIter *iter,
2137                                      double         **value,
2138                                      int             *len)
2139 {
2140   _dbus_assert (dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_DOUBLE_ARRAY);
2141
2142   if (!_dbus_demarshal_double_array (&iter->message->body, iter->message->byte_order,
2143                                      iter->pos + 1, NULL, value, len))
2144     return FALSE;
2145   else
2146     return TRUE;
2147 }
2148
2149 /**
2150  * Returns the byte array that the iterator may point to.
2151  * Note that you need to check that the iterator points
2152  * to a byte array prior to using this function.
2153  *
2154  * @param iter the iterator
2155  * @param value return location for array values
2156  * @param len return location for length of byte array
2157  * @returns #TRUE on success
2158  */
2159 dbus_bool_t
2160 dbus_message_iter_get_byte_array (DBusMessageIter  *iter,
2161                                   unsigned char   **value,
2162                                   int              *len)
2163 {
2164   _dbus_assert (dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_BYTE_ARRAY);
2165
2166   if (!_dbus_demarshal_byte_array (&iter->message->body, iter->message->byte_order,
2167                                    iter->pos + 1, NULL, value, len))
2168     return FALSE;
2169   else
2170     return TRUE;
2171 }
2172
2173 /**
2174  * Returns the string array that the iterator may point to.
2175  * Note that you need to check that the iterator points
2176  * to a byte array prior to using this function.
2177  *
2178  * The returned value is a #NULL-terminated array of strings.
2179  * Each string is a separate malloc block, and the array
2180  * itself is a malloc block. You can free this type of
2181  * string array with dbus_free_string_array().
2182  *
2183  * @param iter the iterator
2184  * @param value return location for string values
2185  * @param len return location for length of byte array
2186  * @returns #TRUE on success
2187  */
2188 dbus_bool_t
2189 dbus_message_iter_get_string_array (DBusMessageIter *iter,
2190                                     char          ***value,
2191                                     int             *len)
2192 {
2193   _dbus_assert (dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_STRING_ARRAY);
2194
2195   if (!_dbus_demarshal_string_array (&iter->message->body, iter->message->byte_order,
2196                                      iter->pos + 1, NULL, value, len))
2197     return FALSE;
2198   else
2199     return TRUE;
2200 }
2201
2202 /**
2203  * Returns the dict that the iterator may point to.
2204  * Note that you need to check that the iterator points
2205  * to a dict prior to using this function.
2206  *
2207  * @param iter the iterator
2208  * @param dict return location for dict
2209  * @returns #TRUE on success
2210  */
2211 dbus_bool_t
2212 dbus_message_iter_get_dict (DBusMessageIter *iter,
2213                             DBusDict       **dict)
2214 {
2215   _dbus_assert (dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_DICT);
2216
2217   if (!_dbus_demarshal_dict (&iter->message->body, iter->message->byte_order,
2218                              iter->pos + 1, NULL, dict))
2219     return FALSE;
2220   else
2221     return TRUE;
2222 }
2223
2224 /**
2225  * Sets the message sender.
2226  *
2227  * @param message the message
2228  * @param sender the sender
2229  * @returns #FALSE if not enough memory
2230  */
2231 dbus_bool_t
2232 dbus_message_set_sender (DBusMessage  *message,
2233                          const char   *sender)
2234 {
2235   _dbus_assert (!message->locked);
2236
2237   if (sender == NULL)
2238     {
2239       delete_string_field (message, FIELD_SENDER);
2240       return TRUE;
2241     }
2242   else
2243     {
2244       return set_string_field (message,
2245                                FIELD_SENDER,
2246                                sender);
2247     }
2248 }
2249
2250 /**
2251  * Sets a flag indicating that the message is an error reply
2252  * message, i.e. an "exception" rather than a normal response.
2253  *
2254  * @param message the message
2255  * @param is_error_reply #TRUE if this is an error message.
2256  */
2257 void
2258 dbus_message_set_is_error (DBusMessage *message,
2259                            dbus_bool_t  is_error_reply)
2260 {
2261   char *header;
2262   
2263   _dbus_assert (!message->locked);
2264   
2265   _dbus_string_get_data_len (&message->header, &header, 1, 1);
2266   
2267   if (is_error_reply)
2268     *header |= DBUS_HEADER_FLAG_ERROR;
2269   else
2270     *header &= ~DBUS_HEADER_FLAG_ERROR;    
2271 }
2272
2273 /**
2274  * Returns #TRUE if the message is an error
2275  * reply to some previous message we sent.
2276  *
2277  * @param message the message
2278  * @returns #TRUE if the message is an error
2279  */
2280 dbus_bool_t
2281 dbus_message_get_is_error (DBusMessage *message)
2282 {
2283   const char *header;
2284
2285   _dbus_string_get_const_data_len (&message->header, &header, 1, 1);
2286
2287   return (*header & DBUS_HEADER_FLAG_ERROR) != 0;
2288 }
2289
2290 /**
2291  * Gets the service which originated this message,
2292  * or #NULL if unknown or inapplicable.
2293  *
2294  * @param message the message
2295  * @returns the service name or #NULL
2296  */
2297 const char*
2298 dbus_message_get_sender (DBusMessage *message)
2299 {
2300   return get_string_field (message, FIELD_SENDER, NULL);
2301 }
2302
2303 /**
2304  * Checks whether the message has the given name.
2305  * If the message has no name or has a different
2306  * name, returns #FALSE.
2307  *
2308  * @param message the message
2309  * @param name the name to check (must not be #NULL)
2310  * 
2311  * @returns #TRUE if the message has the given name
2312  */
2313 dbus_bool_t
2314 dbus_message_name_is (DBusMessage *message,
2315                       const char  *name)
2316 {
2317   const char *n;
2318
2319   _dbus_assert (name != NULL);
2320   
2321   n = dbus_message_get_name (message);
2322
2323   if (n && strcmp (n, name) == 0)
2324     return TRUE;
2325   else
2326     return FALSE;
2327 }
2328
2329 /**
2330  * Checks whether the message was sent to the given service.  If the
2331  * message has no service specified or has a different name, returns
2332  * #FALSE.
2333  *
2334  * @param message the message
2335  * @param service the service to check (must not be #NULL)
2336  * 
2337  * @returns #TRUE if the message has the given destination service
2338  */
2339 dbus_bool_t
2340 dbus_message_service_is (DBusMessage  *message,
2341                          const char   *service)
2342 {
2343   const char *s;
2344
2345   _dbus_assert (service != NULL);
2346   
2347   s = dbus_message_get_service (message);
2348
2349   if (s && strcmp (s, service) == 0)
2350     return TRUE;
2351   else
2352     return FALSE;
2353 }
2354
2355 /**
2356  * Checks whether the message has the given service as its sender.  If
2357  * the message has no sender specified or has a different sender,
2358  * returns #FALSE. Note that if a peer application owns multiple
2359  * services, its messages will have only one of those services as the
2360  * sender (usually the base service). So you can't use this
2361  * function to prove the sender didn't own service Foo, you can
2362  * only use it to prove that it did.
2363  *
2364  * @param message the message
2365  * @param service the service to check (must not be #NULL)
2366  * 
2367  * @returns #TRUE if the message has the given origin service
2368  */
2369 dbus_bool_t
2370 dbus_message_sender_is (DBusMessage  *message,
2371                         const char   *service)
2372 {
2373   const char *s;
2374
2375   _dbus_assert (service != NULL);
2376   
2377   s = dbus_message_get_sender (message);
2378
2379   if (s && strcmp (s, service) == 0)
2380     return TRUE;
2381   else
2382     return FALSE;
2383 }
2384
2385 /** @} */
2386
2387 /**
2388  * @addtogroup DBusMessageInternals
2389  *
2390  * @{
2391  */
2392 /**
2393  * @typedef DBusMessageLoader
2394  *
2395  * The DBusMessageLoader object encapsulates the process of converting
2396  * a byte stream into a series of DBusMessage. It buffers the incoming
2397  * bytes as efficiently as possible, and generates a queue of
2398  * messages. DBusMessageLoader is typically used as part of a
2399  * DBusTransport implementation. The DBusTransport then hands off
2400  * the loaded messages to a DBusConnection, making the messages
2401  * visible to the application.
2402  *
2403  * @todo write tests for break-loader that a) randomly delete header
2404  * fields and b) set string fields to zero-length and other funky
2405  * values.
2406  * 
2407  */
2408
2409 /* we definitely use signed ints for sizes, so don't exceed
2410  * _DBUS_INT_MAX; and add 16 for paranoia, since a message
2411  * over 128M is pretty nuts anyhow.
2412  */
2413
2414 /**
2415  * The maximum sane message size.
2416  */
2417 #define MAX_SANE_MESSAGE_SIZE (_DBUS_INT_MAX/16)
2418
2419 /**
2420  * Implementation details of DBusMessageLoader.
2421  * All members are private.
2422  */
2423 struct DBusMessageLoader
2424 {
2425   int refcount;        /**< Reference count. */
2426
2427   DBusString data;     /**< Buffered data */
2428   
2429   DBusList *messages;  /**< Complete messages. */
2430
2431   long max_message_size; /**< Maximum size of a message */
2432   
2433   unsigned int buffer_outstanding : 1; /**< Someone is using the buffer to read */
2434
2435   unsigned int corrupted : 1; /**< We got broken data, and are no longer working */
2436 };
2437
2438 /**
2439  * The initial buffer size of the message loader.
2440  * 
2441  * @todo this should be based on min header size plus some average
2442  * body size, or something. Or rather, the min header size only, if we
2443  * want to try to read only the header, store that in a DBusMessage,
2444  * then read only the body and store that, etc., depends on
2445  * how we optimize _dbus_message_loader_get_buffer() and what
2446  * the exact message format is.
2447  */
2448 #define INITIAL_LOADER_DATA_LEN 32
2449
2450 /**
2451  * Creates a new message loader. Returns #NULL if memory can't
2452  * be allocated.
2453  *
2454  * @returns new loader, or #NULL.
2455  */
2456 DBusMessageLoader*
2457 _dbus_message_loader_new (void)
2458 {
2459   DBusMessageLoader *loader;
2460
2461   loader = dbus_new0 (DBusMessageLoader, 1);
2462   if (loader == NULL)
2463     return NULL;
2464   
2465   loader->refcount = 1;
2466
2467   /* Try to cap message size at something that won't *totally* hose
2468    * the system if we have a couple of them.
2469    */
2470   loader->max_message_size = _DBUS_ONE_MEGABYTE * 32;
2471   
2472   if (!_dbus_string_init (&loader->data, _DBUS_INT_MAX))
2473     {
2474       dbus_free (loader);
2475       return NULL;
2476     }
2477
2478   /* preallocate the buffer for speed, ignore failure */
2479   _dbus_string_set_length (&loader->data, INITIAL_LOADER_DATA_LEN);
2480   _dbus_string_set_length (&loader->data, 0);
2481   
2482   return loader;
2483 }
2484
2485 /**
2486  * Increments the reference count of the loader.
2487  *
2488  * @param loader the loader.
2489  */
2490 void
2491 _dbus_message_loader_ref (DBusMessageLoader *loader)
2492 {
2493   loader->refcount += 1;
2494 }
2495
2496 /**
2497  * Decrements the reference count of the loader and finalizes the
2498  * loader when the count reaches zero.
2499  *
2500  * @param loader the loader.
2501  */
2502 void
2503 _dbus_message_loader_unref (DBusMessageLoader *loader)
2504 {
2505   loader->refcount -= 1;
2506   if (loader->refcount == 0)
2507     {
2508       _dbus_list_foreach (&loader->messages,
2509                           (DBusForeachFunction) dbus_message_unref,
2510                           NULL);
2511       _dbus_list_clear (&loader->messages);
2512       _dbus_string_free (&loader->data);
2513       dbus_free (loader);
2514     }
2515 }
2516
2517 /**
2518  * Gets the buffer to use for reading data from the network.  Network
2519  * data is read directly into an allocated buffer, which is then used
2520  * in the DBusMessage, to avoid as many extra memcpy's as possible.
2521  * The buffer must always be returned immediately using
2522  * _dbus_message_loader_return_buffer(), even if no bytes are
2523  * successfully read.
2524  *
2525  * @todo this function can be a lot more clever. For example
2526  * it can probably always return a buffer size to read exactly
2527  * the body of the next message, thus avoiding any memory wastage
2528  * or reallocs.
2529  *
2530  * @todo we need to enforce a max length on strings in header fields.
2531  * 
2532  * @param loader the message loader.
2533  * @param buffer the buffer
2534  */
2535 void
2536 _dbus_message_loader_get_buffer (DBusMessageLoader  *loader,
2537                                  DBusString        **buffer)
2538 {
2539   _dbus_assert (!loader->buffer_outstanding);
2540
2541   *buffer = &loader->data;
2542   
2543   loader->buffer_outstanding = TRUE;
2544 }
2545
2546 /**
2547  * The smallest header size that can occur. 
2548  * (It won't be valid)
2549  */
2550 #define DBUS_MINIMUM_HEADER_SIZE 16
2551
2552 /** Pack four characters as in "abcd" into a uint32 */
2553 #define FOUR_CHARS_TO_UINT32(a, b, c, d)                \
2554                       ((((dbus_uint32_t)a) << 24) |     \
2555                        (((dbus_uint32_t)b) << 16) |     \
2556                        (((dbus_uint32_t)c) << 8)  |     \
2557                        ((dbus_uint32_t)d))
2558
2559 /** DBUS_HEADER_FIELD_NAME packed into a dbus_uint32_t */
2560 #define DBUS_HEADER_FIELD_NAME_AS_UINT32    \
2561   FOUR_CHARS_TO_UINT32 ('n', 'a', 'm', 'e')
2562
2563 /** DBUS_HEADER_FIELD_SERVICE packed into a dbus_uint32_t */
2564 #define DBUS_HEADER_FIELD_SERVICE_AS_UINT32 \
2565   FOUR_CHARS_TO_UINT32 ('s', 'r', 'v', 'c')
2566
2567 /** DBUS_HEADER_FIELD_REPLY packed into a dbus_uint32_t */
2568 #define DBUS_HEADER_FIELD_REPLY_AS_UINT32   \
2569   FOUR_CHARS_TO_UINT32 ('r', 'p', 'l', 'y')
2570
2571 /** DBUS_HEADER_FIELD_SENDER Packed into a dbus_uint32_t */
2572 #define DBUS_HEADER_FIELD_SENDER_AS_UINT32  \
2573   FOUR_CHARS_TO_UINT32 ('s', 'n', 'd', 'r')
2574
2575 /* FIXME impose max length on name, srvc, sndr */
2576 static dbus_bool_t
2577 decode_header_data (const DBusString   *data,
2578                     int                 header_len,
2579                     int                 byte_order,
2580                     HeaderField         fields[FIELD_LAST],
2581                     int                *message_padding)
2582 {
2583   const char *field;
2584   int pos, new_pos;
2585   int i;
2586   
2587   if (header_len < 16)
2588     return FALSE;
2589   
2590   i = 0;
2591   while (i < FIELD_LAST)
2592     {
2593       fields[i].offset = -1;
2594       ++i;
2595     }
2596   
2597   fields[FIELD_HEADER_LENGTH].offset = 4;
2598   fields[FIELD_BODY_LENGTH].offset = 8;   
2599   fields[FIELD_CLIENT_SERIAL].offset = 12;
2600   
2601   /* Now handle the named fields. A real named field is at least 4
2602    * bytes for the name, plus a type code (1 byte) plus padding.  So
2603    * if we have less than 8 bytes left, it must be alignment padding,
2604    * not a field. While >= 8 bytes can't be entirely alignment
2605    * padding.
2606    */  
2607   pos = 16;
2608   while ((pos + 7) < header_len)
2609     {
2610       pos = _DBUS_ALIGN_VALUE (pos, 4);
2611       
2612       if ((pos + 4) > header_len)
2613         return FALSE;      
2614       
2615       _dbus_string_get_const_data_len (data, &field, pos, 4);
2616       pos += 4;
2617
2618       _dbus_assert (_DBUS_ALIGN_ADDRESS (field, 4) == field);
2619
2620       /* I believe FROM_BE is right, but if not we'll find out
2621        * I guess. ;-)
2622        */
2623       switch (DBUS_UINT32_FROM_BE (*(int*)field))
2624         {
2625         case DBUS_HEADER_FIELD_SERVICE_AS_UINT32:
2626           if (fields[FIELD_SERVICE].offset >= 0)
2627             {
2628               _dbus_verbose ("%s field provided twice\n",
2629                              DBUS_HEADER_FIELD_SERVICE);
2630               return FALSE;
2631             }
2632           
2633           fields[FIELD_SERVICE].offset = _DBUS_ALIGN_VALUE (pos + 1, 4);
2634 #if 0
2635           _dbus_verbose ("Found service name at offset %d\n",
2636                          fields[FIELD_SERVICE].offset);
2637 #endif
2638           break;
2639
2640         case DBUS_HEADER_FIELD_NAME_AS_UINT32:
2641           if (fields[FIELD_NAME].offset >= 0)
2642             {              
2643               _dbus_verbose ("%s field provided twice\n",
2644                              DBUS_HEADER_FIELD_NAME);
2645               return FALSE;
2646             }
2647           
2648           fields[FIELD_NAME].offset = _DBUS_ALIGN_VALUE (pos + 1, 4);
2649
2650 #if 0
2651           _dbus_verbose ("Found message name at offset %d\n",
2652                          fields[FIELD_NAME].offset);
2653 #endif
2654           break;
2655         case DBUS_HEADER_FIELD_SENDER_AS_UINT32:
2656           if (fields[FIELD_SENDER].offset >= 0)
2657             {
2658               _dbus_verbose ("%s field provided twice\n",
2659                              DBUS_HEADER_FIELD_SENDER);
2660               return FALSE;
2661             }
2662           
2663           fields[FIELD_SENDER].offset = _DBUS_ALIGN_VALUE (pos + 1, 4);
2664
2665           _dbus_verbose ("Found sender name at offset %d\n",
2666                          fields[FIELD_NAME].offset);
2667           break;
2668           
2669         case DBUS_HEADER_FIELD_REPLY_AS_UINT32:
2670           if (fields[FIELD_REPLY_SERIAL].offset >= 0)
2671             {
2672               _dbus_verbose ("%s field provided twice\n",
2673                              DBUS_HEADER_FIELD_REPLY);
2674               return FALSE;
2675             }
2676           
2677           fields[FIELD_REPLY_SERIAL].offset = _DBUS_ALIGN_VALUE (pos + 1, 4);
2678
2679           _dbus_verbose ("Found reply serial at offset %d\n",
2680                          fields[FIELD_REPLY_SERIAL].offset);
2681           break;
2682
2683         default:
2684           _dbus_verbose ("Ignoring an unknown header field: %c%c%c%c at offset %d\n",
2685                          field[0], field[1], field[2], field[3], pos);
2686         }
2687
2688       if (!_dbus_marshal_validate_arg (data, byte_order, pos, &new_pos))
2689         {
2690           _dbus_verbose ("Failed to validate argument to named header field\n");
2691           return FALSE;
2692         }
2693
2694       if (new_pos > header_len)
2695         {
2696           _dbus_verbose ("Named header field tries to extend beyond header length\n");
2697           return FALSE;
2698         }
2699       
2700       pos = new_pos;
2701     }
2702
2703   if (pos < header_len)
2704     {
2705       /* Alignment padding, verify that it's nul */
2706       _dbus_assert ((header_len - pos) < 8);
2707
2708       if (!_dbus_string_validate_nul (data,
2709                                       pos, (header_len - pos)))
2710         {
2711           _dbus_verbose ("header alignment padding is not nul\n");
2712           return FALSE;
2713         }
2714     }
2715
2716  if (fields[FIELD_NAME].offset < 0)
2717    {
2718      _dbus_verbose ("No %s field provided\n",
2719                     DBUS_HEADER_FIELD_NAME);
2720      return FALSE;
2721    }
2722   
2723   if (message_padding)
2724     *message_padding = header_len - pos;  
2725   
2726   return TRUE;
2727 }
2728
2729 /**
2730  * Returns a buffer obtained from _dbus_message_loader_get_buffer(),
2731  * indicating to the loader how many bytes of the buffer were filled
2732  * in. This function must always be called, even if no bytes were
2733  * successfully read.
2734  *
2735  * @param loader the loader.
2736  * @param buffer the buffer.
2737  * @param bytes_read number of bytes that were read into the buffer.
2738  */
2739 void
2740 _dbus_message_loader_return_buffer (DBusMessageLoader  *loader,
2741                                     DBusString         *buffer,
2742                                     int                 bytes_read)
2743 {
2744   _dbus_assert (loader->buffer_outstanding);
2745   _dbus_assert (buffer == &loader->data);
2746
2747   loader->buffer_outstanding = FALSE;
2748 }
2749
2750 /**
2751  * Converts buffered data into messages.
2752  *
2753  * @param loader the loader.
2754  * @returns #TRUE if we had enough memory to finish.
2755  */
2756 dbus_bool_t
2757 _dbus_message_loader_queue_messages (DBusMessageLoader *loader)
2758 {
2759   if (loader->corrupted)
2760     return TRUE;
2761
2762   while (_dbus_string_get_length (&loader->data) >= 16)
2763     {
2764       DBusMessage *message;      
2765       const char *header_data;
2766       int byte_order, header_len, body_len, header_padding;
2767       dbus_uint32_t header_len_unsigned, body_len_unsigned;
2768       
2769       _dbus_string_get_const_data_len (&loader->data, &header_data, 0, 16);
2770
2771       _dbus_assert (_DBUS_ALIGN_ADDRESS (header_data, 4) == header_data);
2772
2773       if (header_data[2] != DBUS_MAJOR_PROTOCOL_VERSION)
2774         {
2775           _dbus_verbose ("Message has protocol version %d ours is %d\n",
2776                          (int) header_data[2], DBUS_MAJOR_PROTOCOL_VERSION);
2777           loader->corrupted = TRUE;
2778           return TRUE;
2779         }
2780       
2781       byte_order = header_data[0];
2782
2783       if (byte_order != DBUS_LITTLE_ENDIAN &&
2784           byte_order != DBUS_BIG_ENDIAN)
2785         {
2786           _dbus_verbose ("Message with bad byte order '%c' received\n",
2787                          byte_order);
2788           loader->corrupted = TRUE;
2789           return TRUE;
2790         }
2791
2792       header_len_unsigned = _dbus_unpack_uint32 (byte_order, header_data + 4);
2793       body_len_unsigned = _dbus_unpack_uint32 (byte_order, header_data + 8);
2794
2795       if (header_len_unsigned < 16)
2796         {
2797           _dbus_verbose ("Message had broken too-small header length %u\n",
2798                          header_len_unsigned);
2799           loader->corrupted = TRUE;
2800           return TRUE;
2801         }
2802
2803       if (header_len_unsigned > (unsigned) MAX_SANE_MESSAGE_SIZE ||
2804           body_len_unsigned > (unsigned) MAX_SANE_MESSAGE_SIZE)
2805         {
2806           _dbus_verbose ("Header or body length too large (%u %u)\n",
2807                          header_len_unsigned,
2808                          body_len_unsigned);
2809           loader->corrupted = TRUE;
2810           return TRUE;
2811         }
2812
2813       /* Now that we know the values are in signed range, get
2814        * rid of stupid unsigned, just causes bugs
2815        */
2816       header_len = header_len_unsigned;
2817       body_len = body_len_unsigned;
2818
2819       if (_DBUS_ALIGN_VALUE (header_len, 8) != header_len_unsigned)
2820         {
2821           
2822           _dbus_verbose ("header length %d is not aligned to 8 bytes\n",
2823                          header_len);
2824           loader->corrupted = TRUE;
2825           return TRUE;
2826         }
2827       
2828       if (header_len + body_len > loader->max_message_size)
2829         {
2830           _dbus_verbose ("Message claimed length header = %d body = %d exceeds max message length %ld\n",
2831                          header_len, body_len, loader->max_message_size);
2832           loader->corrupted = TRUE;
2833           return TRUE;
2834         }
2835
2836       if (_dbus_string_get_length (&loader->data) >= (header_len + body_len))
2837         {
2838           HeaderField fields[FIELD_LAST];
2839           int i;
2840           int next_arg;          
2841
2842 #if 0
2843           _dbus_verbose_bytes_of_string (&loader->data, 0, header_len + body_len);
2844 #endif    
2845           if (!decode_header_data (&loader->data, header_len, byte_order,
2846                                    fields, &header_padding))
2847             {
2848               _dbus_verbose ("Header was invalid\n");
2849               loader->corrupted = TRUE;
2850               return TRUE;
2851             }
2852           
2853           next_arg = header_len;
2854           while (next_arg < (header_len + body_len))
2855             {
2856               int prev = next_arg;
2857
2858               if (!_dbus_marshal_validate_arg (&loader->data,
2859                                                byte_order,
2860                                                next_arg,
2861                                                &next_arg))
2862                 {
2863                   loader->corrupted = TRUE;
2864                   return TRUE;
2865                 }
2866
2867               _dbus_assert (next_arg > prev);
2868             }
2869           
2870           if (next_arg > (header_len + body_len))
2871             {
2872               _dbus_verbose ("end of last arg at %d but message has len %d+%d=%d\n",
2873                              next_arg, header_len, body_len,
2874                              header_len + body_len);
2875               loader->corrupted = TRUE;
2876               return TRUE;
2877             }
2878
2879           message = dbus_message_new_empty_header ();
2880           if (message == NULL)
2881             return FALSE;
2882
2883           message->byte_order = byte_order;
2884           message->header_padding = header_padding;
2885           
2886           /* Copy in the offsets we found */
2887           i = 0;
2888           while (i < FIELD_LAST)
2889             {
2890               message->header_fields[i] = fields[i];
2891               ++i;
2892             }
2893           
2894           if (!_dbus_list_append (&loader->messages, message))
2895             {
2896               dbus_message_unref (message);
2897               return FALSE;
2898             }
2899
2900           _dbus_assert (_dbus_string_get_length (&message->header) == 0);
2901           _dbus_assert (_dbus_string_get_length (&message->body) == 0);
2902
2903           _dbus_assert (_dbus_string_get_length (&loader->data) >=
2904                         (header_len + body_len));
2905           
2906           if (!_dbus_string_move_len (&loader->data, 0, header_len, &message->header, 0))
2907             {
2908               _dbus_list_remove_last (&loader->messages, message);
2909               dbus_message_unref (message);
2910               return FALSE;
2911             }
2912           
2913           if (!_dbus_string_move_len (&loader->data, 0, body_len, &message->body, 0))
2914             {
2915               dbus_bool_t result;
2916
2917               /* put the header back, we'll try again later */
2918               result = _dbus_string_copy_len (&message->header, 0, header_len,
2919                                               &loader->data, 0);
2920               _dbus_assert (result); /* because DBusString never reallocs smaller */
2921
2922               _dbus_list_remove_last (&loader->messages, message);
2923               dbus_message_unref (message);
2924               return FALSE;
2925             }
2926
2927           _dbus_assert (_dbus_string_get_length (&message->header) == header_len);
2928           _dbus_assert (_dbus_string_get_length (&message->body) == body_len);
2929
2930           /* Fill in caches */
2931           message->reply_serial = get_int_field (message,
2932                                                  FIELD_REPLY_SERIAL);
2933           message->client_serial = get_int_field (message,
2934                                                   FIELD_CLIENT_SERIAL);
2935           
2936           _dbus_verbose ("Loaded message %p\n", message);
2937         }
2938       else
2939         return TRUE;
2940     }
2941
2942   return TRUE;
2943 }
2944
2945 /**
2946  * Peeks at first loaded message, returns #NULL if no messages have
2947  * been queued.
2948  *
2949  * @param loader the loader.
2950  * @returns the next message, or #NULL if none.
2951  */
2952 DBusMessage*
2953 _dbus_message_loader_peek_message (DBusMessageLoader *loader)
2954 {
2955   if (loader->messages)
2956     return loader->messages->data;
2957   else
2958     return NULL;
2959 }
2960
2961 /**
2962  * Pops a loaded message (passing ownership of the message
2963  * to the caller). Returns #NULL if no messages have been
2964  * queued.
2965  *
2966  * @param loader the loader.
2967  * @returns the next message, or #NULL if none.
2968  */
2969 DBusMessage*
2970 _dbus_message_loader_pop_message (DBusMessageLoader *loader)
2971 {
2972   return _dbus_list_pop_first (&loader->messages);
2973 }
2974
2975 /**
2976  * Pops a loaded message inside a list link (passing ownership of the
2977  * message and link to the caller). Returns #NULL if no messages have
2978  * been loaded.
2979  *
2980  * @param loader the loader.
2981  * @returns the next message link, or #NULL if none.
2982  */
2983 DBusList*
2984 _dbus_message_loader_pop_message_link (DBusMessageLoader *loader)
2985 {
2986   return _dbus_list_pop_first_link (&loader->messages);
2987 }
2988
2989 /**
2990  * Checks whether the loader is confused due to bad data.
2991  * If messages are received that are invalid, the
2992  * loader gets confused and gives up permanently.
2993  * This state is called "corrupted."
2994  *
2995  * @param loader the loader
2996  * @returns #TRUE if the loader is hosed.
2997  */
2998 dbus_bool_t
2999 _dbus_message_loader_get_is_corrupted (DBusMessageLoader *loader)
3000 {
3001   return loader->corrupted;
3002 }
3003
3004 /**
3005  * Sets the maximum size message we allow.
3006  *
3007  * @param loader the loader
3008  * @param size the max message size in bytes
3009  */
3010 void
3011 _dbus_message_loader_set_max_message_size (DBusMessageLoader  *loader,
3012                                            long                size)
3013 {
3014   if (size > MAX_SANE_MESSAGE_SIZE)
3015     {
3016       _dbus_verbose ("clamping requested max message size %ld to %d\n",
3017                      size, MAX_SANE_MESSAGE_SIZE);
3018       size = MAX_SANE_MESSAGE_SIZE;
3019     }
3020   loader->max_message_size = size;
3021 }
3022
3023 /**
3024  * Gets the maximum allowed message size in bytes.
3025  *
3026  * @param loader the loader
3027  * @returns max size in bytes
3028  */
3029 long
3030 _dbus_message_loader_get_max_message_size (DBusMessageLoader  *loader)
3031 {
3032   return loader->max_message_size;
3033 }
3034
3035 /** @} */
3036 #ifdef DBUS_BUILD_TESTS
3037 #include "dbus-test.h"
3038 #include <stdio.h>
3039
3040 static void
3041 message_iter_test (DBusMessage *message)
3042 {
3043   DBusMessageIter *iter;
3044   char *str;
3045   
3046   iter = dbus_message_get_args_iter (message);
3047
3048   /* String tests */
3049   if (dbus_message_iter_get_arg_type (iter) != DBUS_TYPE_STRING)
3050     _dbus_assert_not_reached ("Argument type isn't string");
3051
3052   str = dbus_message_iter_get_string (iter);
3053   if (strcmp (str, "Test string") != 0)
3054     _dbus_assert_not_reached ("Strings differ");
3055   dbus_free (str);
3056
3057   if (!dbus_message_iter_next (iter))
3058     _dbus_assert_not_reached ("Reached end of arguments");
3059
3060   /* Signed integer tests */
3061   if (dbus_message_iter_get_arg_type (iter) != DBUS_TYPE_INT32)
3062     _dbus_assert_not_reached ("Argument type isn't int32");
3063
3064   if (dbus_message_iter_get_int32 (iter) != -0x12345678)
3065     _dbus_assert_not_reached ("Signed integers differ");
3066
3067   if (!dbus_message_iter_next (iter))
3068     _dbus_assert_not_reached ("Reached end of fields");
3069   
3070   /* Unsigned integer tests */
3071   if (dbus_message_iter_get_arg_type (iter) != DBUS_TYPE_UINT32)
3072     _dbus_assert_not_reached ("Argument type isn't int32");
3073
3074   if (dbus_message_iter_get_uint32 (iter) != 0xedd1e)
3075     _dbus_assert_not_reached ("Unsigned integers differ");
3076
3077   if (!dbus_message_iter_next (iter))
3078     _dbus_assert_not_reached ("Reached end of arguments");
3079
3080   /* Double tests */
3081   if (dbus_message_iter_get_arg_type (iter) != DBUS_TYPE_DOUBLE)
3082     _dbus_assert_not_reached ("Argument type isn't double");
3083
3084   if (dbus_message_iter_get_double (iter) != 3.14159)
3085     _dbus_assert_not_reached ("Doubles differ");
3086
3087   if (dbus_message_iter_next (iter))
3088     _dbus_assert_not_reached ("Didn't reach end of arguments");
3089   
3090   dbus_message_iter_unref (iter);
3091 }
3092
3093 static dbus_bool_t
3094 check_message_handling (DBusMessage *message)
3095 {
3096   DBusMessageIter *iter;
3097   int type;
3098   dbus_bool_t retval;
3099   dbus_int32_t client_serial;
3100   
3101   retval = FALSE;
3102   iter = NULL;
3103   
3104   client_serial = dbus_message_get_serial (message);
3105
3106   /* can't use set_serial due to the assertions at the start of it */
3107   set_int_field (message, FIELD_CLIENT_SERIAL,
3108                  client_serial);
3109   
3110   if (client_serial != dbus_message_get_serial (message))
3111     {
3112       _dbus_warn ("get/set cycle for client_serial did not succeed\n");
3113       goto failed;
3114     }
3115   
3116   /* If we implement message_set_arg (message, n, value)
3117    * then we would want to test it here
3118    */
3119
3120   iter = dbus_message_get_args_iter (message);
3121   while ((type = dbus_message_iter_get_arg_type (iter)) != DBUS_TYPE_INVALID)
3122     {
3123       switch (type)
3124         {
3125         case DBUS_TYPE_NIL:
3126           break;
3127         case DBUS_TYPE_INT32:
3128           dbus_message_iter_get_int32 (iter);
3129           break;
3130         case DBUS_TYPE_UINT32:
3131           dbus_message_iter_get_uint32 (iter);
3132           break;
3133         case DBUS_TYPE_DOUBLE:
3134           dbus_message_iter_get_double (iter);
3135           break;
3136         case DBUS_TYPE_STRING:
3137           {
3138             char *str;
3139             str = dbus_message_iter_get_string (iter);
3140             dbus_free (str);
3141           }
3142           break;
3143         case DBUS_TYPE_BOOLEAN_ARRAY:
3144           {
3145             unsigned char *values;
3146             int len;
3147             
3148             if (!dbus_message_iter_get_boolean_array (iter, &values, &len))
3149               return FALSE;
3150
3151             dbus_free (values);
3152           }
3153           break;
3154         case DBUS_TYPE_INT32_ARRAY:
3155           {
3156             dbus_int32_t *values;
3157             int len;
3158             
3159             if (!dbus_message_iter_get_int32_array (iter, &values, &len))
3160               return FALSE;
3161
3162             dbus_free (values);
3163           }
3164           break;
3165         case DBUS_TYPE_UINT32_ARRAY:
3166           {
3167             dbus_uint32_t *values;
3168             int len;
3169             
3170             if (!dbus_message_iter_get_uint32_array (iter, &values, &len))
3171               return FALSE;
3172
3173             dbus_free (values);
3174           }
3175           break;
3176         case DBUS_TYPE_DOUBLE_ARRAY:
3177           {
3178             double *values;
3179             int len;
3180             
3181             if (!dbus_message_iter_get_double_array (iter, &values, &len))
3182               return FALSE;
3183
3184             dbus_free (values);
3185           }
3186           break;
3187         case DBUS_TYPE_STRING_ARRAY:
3188           {
3189             char **values;
3190             int len;
3191             
3192             if (!dbus_message_iter_get_string_array (iter, &values, &len))
3193               return FALSE;
3194
3195             dbus_free_string_array (values);
3196           }
3197           break;
3198
3199         case DBUS_TYPE_DICT:
3200           {
3201             DBusDict *dict;
3202
3203             if (!dbus_message_iter_get_dict (iter, &dict))
3204               return FALSE;
3205             dbus_dict_unref (dict);
3206           }
3207           break;
3208
3209         default:
3210           break;
3211         }
3212       
3213       if (!dbus_message_iter_next (iter))
3214         break;
3215     }
3216
3217   retval = TRUE;
3218   
3219  failed:
3220   if (iter)
3221     dbus_message_iter_unref (iter);
3222
3223   return retval;
3224 }
3225
3226 static dbus_bool_t
3227 check_have_valid_message (DBusMessageLoader *loader)
3228 {
3229   DBusMessage *message;
3230   dbus_bool_t retval;
3231
3232   message = NULL;
3233   retval = FALSE;
3234
3235   if (!_dbus_message_loader_queue_messages (loader))
3236     _dbus_assert_not_reached ("no memory to queue messages");
3237   
3238   if (_dbus_message_loader_get_is_corrupted (loader))
3239     {
3240       _dbus_warn ("loader corrupted on message that was expected to be valid\n");
3241       goto failed;
3242     }
3243   
3244   message = _dbus_message_loader_pop_message (loader);
3245   if (message == NULL)
3246     {
3247       _dbus_warn ("didn't load message that was expected to be valid (message not popped)\n");
3248       goto failed;
3249     }
3250   
3251   if (_dbus_string_get_length (&loader->data) > 0)
3252     {
3253       _dbus_warn ("had leftover bytes from expected-to-be-valid single message\n");
3254       goto failed;
3255     }
3256
3257   /* Verify that we're able to properly deal with the message.
3258    * For example, this would detect improper handling of messages
3259    * in nonstandard byte order.
3260    */
3261   if (!check_message_handling (message))
3262     goto failed;  
3263   
3264   retval = TRUE;
3265
3266  failed:
3267   if (message)
3268     dbus_message_unref (message);
3269
3270   return retval;
3271 }
3272
3273 static dbus_bool_t
3274 check_invalid_message (DBusMessageLoader *loader)
3275 {
3276   dbus_bool_t retval;
3277
3278   retval = FALSE;
3279
3280   if (!_dbus_message_loader_queue_messages (loader))
3281     _dbus_assert_not_reached ("no memory to queue messages");
3282   
3283   if (!_dbus_message_loader_get_is_corrupted (loader))
3284     {
3285       _dbus_warn ("loader not corrupted on message that was expected to be invalid\n");
3286       goto failed;
3287     }
3288
3289   retval = TRUE;
3290
3291  failed:
3292   return retval;
3293 }
3294
3295 static dbus_bool_t
3296 check_incomplete_message (DBusMessageLoader *loader)
3297 {
3298   DBusMessage *message;
3299   dbus_bool_t retval;
3300
3301   message = NULL;
3302   retval = FALSE;
3303
3304   if (!_dbus_message_loader_queue_messages (loader))
3305     _dbus_assert_not_reached ("no memory to queue messages");
3306   
3307   if (_dbus_message_loader_get_is_corrupted (loader))
3308     {
3309       _dbus_warn ("loader corrupted on message that was expected to be valid (but incomplete)\n");
3310       goto failed;
3311     }
3312   
3313   message = _dbus_message_loader_pop_message (loader);
3314   if (message != NULL)
3315     {
3316       _dbus_warn ("loaded message that was expected to be incomplete\n");
3317       goto failed;
3318     }
3319
3320   retval = TRUE;
3321
3322  failed:
3323   if (message)
3324     dbus_message_unref (message);
3325   return retval;
3326 }
3327
3328 static dbus_bool_t
3329 check_loader_results (DBusMessageLoader      *loader,
3330                       DBusMessageValidity     validity)
3331 {
3332   if (!_dbus_message_loader_queue_messages (loader))
3333     _dbus_assert_not_reached ("no memory to queue messages");
3334   
3335   switch (validity)
3336     {
3337     case _DBUS_MESSAGE_VALID:
3338       return check_have_valid_message (loader);
3339     case _DBUS_MESSAGE_INVALID:
3340       return check_invalid_message (loader);
3341     case _DBUS_MESSAGE_INCOMPLETE:
3342       return check_incomplete_message (loader);
3343     case _DBUS_MESSAGE_UNKNOWN:
3344       return TRUE;
3345     }
3346
3347   _dbus_assert_not_reached ("bad DBusMessageValidity");
3348   return FALSE;
3349 }
3350
3351
3352 /**
3353  * Loads the message in the given message file.
3354  *
3355  * @param filename filename to load
3356  * @param is_raw if #TRUE load as binary data, if #FALSE as message builder language
3357  * @param data string to load message into
3358  * @returns #TRUE if the message was loaded
3359  */
3360 dbus_bool_t
3361 dbus_internal_do_not_use_load_message_file (const DBusString    *filename,
3362                                             dbus_bool_t          is_raw,
3363                                             DBusString          *data)
3364 {
3365   dbus_bool_t retval;
3366
3367   retval = FALSE;  
3368
3369   if (is_raw)
3370     {
3371       DBusError error;
3372
3373       dbus_error_init (&error);
3374       if (!_dbus_file_get_contents (data, filename, &error))
3375         {
3376           const char *s;      
3377           _dbus_string_get_const_data (filename, &s);
3378           _dbus_warn ("Could not load message file %s: %s\n", s, error.message);
3379           dbus_error_free (&error);
3380           goto failed;
3381         }
3382     }
3383   else
3384     {
3385       if (!_dbus_message_data_load (data, filename))
3386         {
3387           const char *s;      
3388           _dbus_string_get_const_data (filename, &s);
3389           _dbus_warn ("Could not load message file %s\n", s);
3390           goto failed;
3391         }
3392     }
3393
3394   retval = TRUE;
3395   
3396  failed:
3397
3398   return retval;
3399 }
3400
3401 /**
3402  * Tries loading the message in the given message file
3403  * and verifies that DBusMessageLoader can handle it.
3404  *
3405  * @param filename filename to load
3406  * @param is_raw if #TRUE load as binary data, if #FALSE as message builder language
3407  * @param expected_validity what the message has to be like to return #TRUE
3408  * @returns #TRUE if the message has the expected validity
3409  */
3410 dbus_bool_t
3411 dbus_internal_do_not_use_try_message_file (const DBusString    *filename,
3412                                            dbus_bool_t          is_raw,
3413                                            DBusMessageValidity  expected_validity)
3414 {
3415   DBusString data;
3416   dbus_bool_t retval;
3417
3418   retval = FALSE;
3419   
3420   if (!_dbus_string_init (&data, _DBUS_INT_MAX))
3421     _dbus_assert_not_reached ("could not allocate string\n");
3422
3423   if (!dbus_internal_do_not_use_load_message_file (filename, is_raw,
3424                                                    &data))
3425     goto failed;
3426
3427   retval = dbus_internal_do_not_use_try_message_data (&data, expected_validity);
3428
3429  failed:
3430
3431   if (!retval)
3432     {
3433       const char *s;
3434
3435       if (_dbus_string_get_length (&data) > 0)
3436         _dbus_verbose_bytes_of_string (&data, 0,
3437                                        _dbus_string_get_length (&data));
3438       
3439       _dbus_string_get_const_data (filename, &s);
3440       _dbus_warn ("Failed message loader test on %s\n",
3441                   s);
3442     }
3443   
3444   _dbus_string_free (&data);
3445
3446   return retval;
3447 }
3448
3449 /**
3450  * Tries loading the given message data.
3451  *
3452  *
3453  * @param data the message data
3454  * @param expected_validity what the message has to be like to return #TRUE
3455  * @returns #TRUE if the message has the expected validity
3456  */
3457 dbus_bool_t
3458 dbus_internal_do_not_use_try_message_data (const DBusString    *data,
3459                                            DBusMessageValidity  expected_validity)
3460 {
3461   DBusMessageLoader *loader;
3462   dbus_bool_t retval;
3463   int len;
3464   int i;
3465
3466   loader = NULL;
3467   retval = FALSE;
3468
3469   /* Write the data one byte at a time */
3470   
3471   loader = _dbus_message_loader_new ();
3472
3473   len = _dbus_string_get_length (data);
3474   for (i = 0; i < len; i++)
3475     {
3476       DBusString *buffer;
3477
3478       _dbus_message_loader_get_buffer (loader, &buffer);
3479       _dbus_string_append_byte (buffer,
3480                                 _dbus_string_get_byte (data, i));
3481       _dbus_message_loader_return_buffer (loader, buffer, 1);
3482     }
3483   
3484   if (!check_loader_results (loader, expected_validity))
3485     goto failed;
3486
3487   _dbus_message_loader_unref (loader);
3488   loader = NULL;
3489
3490   /* Write the data all at once */
3491   
3492   loader = _dbus_message_loader_new ();
3493
3494   {
3495     DBusString *buffer;
3496     
3497     _dbus_message_loader_get_buffer (loader, &buffer);
3498     _dbus_string_copy (data, 0, buffer,
3499                        _dbus_string_get_length (buffer));
3500     _dbus_message_loader_return_buffer (loader, buffer, 1);
3501   }
3502   
3503   if (!check_loader_results (loader, expected_validity))
3504     goto failed;
3505
3506   _dbus_message_loader_unref (loader);
3507   loader = NULL;  
3508
3509   /* Write the data 2 bytes at a time */
3510   
3511   loader = _dbus_message_loader_new ();
3512
3513   len = _dbus_string_get_length (data);
3514   for (i = 0; i < len; i += 2)
3515     {
3516       DBusString *buffer;
3517
3518       _dbus_message_loader_get_buffer (loader, &buffer);
3519       _dbus_string_append_byte (buffer,
3520                                 _dbus_string_get_byte (data, i));
3521       if ((i+1) < len)
3522         _dbus_string_append_byte (buffer,
3523                                   _dbus_string_get_byte (data, i+1));
3524       _dbus_message_loader_return_buffer (loader, buffer, 1);
3525     }
3526   
3527   if (!check_loader_results (loader, expected_validity))
3528     goto failed;
3529
3530   _dbus_message_loader_unref (loader);
3531   loader = NULL;
3532   
3533   retval = TRUE;
3534   
3535  failed:
3536   
3537   if (loader)
3538     _dbus_message_loader_unref (loader);
3539   
3540   return retval;
3541 }
3542
3543 static dbus_bool_t
3544 process_test_subdir (const DBusString          *test_base_dir,
3545                      const char                *subdir,
3546                      DBusMessageValidity        validity,
3547                      DBusForeachMessageFileFunc function,
3548                      void                      *user_data)
3549 {
3550   DBusString test_directory;
3551   DBusString filename;
3552   DBusDirIter *dir;
3553   dbus_bool_t retval;
3554   DBusError error;
3555
3556   retval = FALSE;
3557   dir = NULL;
3558   
3559   if (!_dbus_string_init (&test_directory, _DBUS_INT_MAX))
3560     _dbus_assert_not_reached ("didn't allocate test_directory\n");
3561
3562   _dbus_string_init_const (&filename, subdir);
3563   
3564   if (!_dbus_string_copy (test_base_dir, 0,
3565                           &test_directory, 0))
3566     _dbus_assert_not_reached ("couldn't copy test_base_dir to test_directory");
3567   
3568   if (!_dbus_concat_dir_and_file (&test_directory, &filename))    
3569     _dbus_assert_not_reached ("couldn't allocate full path");
3570
3571   _dbus_string_free (&filename);
3572   if (!_dbus_string_init (&filename, _DBUS_INT_MAX))
3573     _dbus_assert_not_reached ("didn't allocate filename string\n");
3574
3575   dbus_error_init (&error);
3576   dir = _dbus_directory_open (&test_directory, &error);
3577   if (dir == NULL)
3578     {
3579       const char *s;
3580       _dbus_string_get_const_data (&test_directory, &s);
3581       _dbus_warn ("Could not open %s: %s\n", s,
3582                   error.message);
3583       dbus_error_free (&error);
3584       goto failed;
3585     }
3586
3587   printf ("Testing:\n");
3588   
3589  next:
3590   while (_dbus_directory_get_next_file (dir, &filename, &error))
3591     {
3592       DBusString full_path;
3593       dbus_bool_t is_raw;
3594       
3595       if (!_dbus_string_init (&full_path, _DBUS_INT_MAX))
3596         _dbus_assert_not_reached ("couldn't init string");
3597
3598       if (!_dbus_string_copy (&test_directory, 0, &full_path, 0))
3599         _dbus_assert_not_reached ("couldn't copy dir to full_path");
3600
3601       if (!_dbus_concat_dir_and_file (&full_path, &filename))
3602         _dbus_assert_not_reached ("couldn't concat file to dir");
3603
3604       if (_dbus_string_ends_with_c_str (&filename, ".message"))
3605         is_raw = FALSE;
3606       else if (_dbus_string_ends_with_c_str (&filename, ".message-raw"))
3607         is_raw = TRUE;
3608       else
3609         {
3610           const char *filename_c;
3611           _dbus_string_get_const_data (&filename, &filename_c);
3612           _dbus_verbose ("Skipping non-.message file %s\n",
3613                          filename_c);
3614           _dbus_string_free (&full_path);
3615           goto next;
3616         }
3617
3618       {
3619         const char *s;
3620         _dbus_string_get_const_data (&filename, &s);
3621         printf ("    %s\n", s);
3622       }
3623       
3624       _dbus_verbose (" expecting %s\n",
3625                      validity == _DBUS_MESSAGE_VALID ? "valid" :
3626                      (validity == _DBUS_MESSAGE_INVALID ? "invalid" :
3627                       (validity == _DBUS_MESSAGE_INCOMPLETE ? "incomplete" : "unknown")));
3628       
3629       if (! (*function) (&full_path, is_raw, validity, user_data))
3630         {
3631           _dbus_string_free (&full_path);
3632           goto failed;
3633         }
3634       else
3635         _dbus_string_free (&full_path);
3636     }
3637
3638   if (dbus_error_is_set (&error))
3639     {
3640       const char *s;
3641       _dbus_string_get_const_data (&test_directory, &s);
3642       _dbus_warn ("Could not get next file in %s: %s\n",
3643                   s, error.message);
3644       dbus_error_free (&error);
3645       goto failed;
3646     }
3647     
3648   retval = TRUE;
3649   
3650  failed:
3651
3652   if (dir)
3653     _dbus_directory_close (dir);
3654   _dbus_string_free (&test_directory);
3655   _dbus_string_free (&filename);
3656
3657   return retval;
3658 }
3659                      
3660 /**
3661  * Runs the given function on every message file in the test suite.
3662  * The function should return #FALSE on test failure or fatal error.
3663  *
3664  * @param test_data_dir root dir of the test suite data files (top_srcdir/test/data)
3665  * @param func the function to run
3666  * @param user_data data for function
3667  * @returns #FALSE if there's a failure
3668  */
3669 dbus_bool_t
3670 dbus_internal_do_not_use_foreach_message_file (const char                *test_data_dir,
3671                                                DBusForeachMessageFileFunc func,
3672                                                void                      *user_data)
3673 {
3674   DBusString test_directory;
3675   dbus_bool_t retval;
3676
3677   retval = FALSE;
3678   
3679   _dbus_string_init_const (&test_directory, test_data_dir);
3680
3681   if (!process_test_subdir (&test_directory, "valid-messages",
3682                             _DBUS_MESSAGE_VALID, func, user_data))
3683     goto failed;
3684
3685   if (!process_test_subdir (&test_directory, "invalid-messages",
3686                             _DBUS_MESSAGE_INVALID, func, user_data))
3687     goto failed;
3688   
3689   if (!process_test_subdir (&test_directory, "incomplete-messages",
3690                             _DBUS_MESSAGE_INCOMPLETE, func, user_data))
3691     goto failed;
3692
3693   retval = TRUE;
3694   
3695  failed:
3696
3697   _dbus_string_free (&test_directory);
3698   
3699   return retval;
3700 }
3701
3702 static void
3703 verify_test_message (DBusMessage *message)
3704 {
3705   dbus_int32_t our_int;
3706   char *our_str;
3707   double our_double;
3708   dbus_bool_t our_bool;
3709   
3710   if (!dbus_message_get_args (message, NULL,
3711                               DBUS_TYPE_INT32, &our_int,
3712                               DBUS_TYPE_STRING, &our_str,
3713                               DBUS_TYPE_DOUBLE, &our_double,
3714                               DBUS_TYPE_BOOLEAN, &our_bool,
3715                               0))
3716     _dbus_assert_not_reached ("Could not get arguments");
3717
3718   if (our_int != -0x12345678)
3719     _dbus_assert_not_reached ("integers differ!");
3720
3721   if (our_double != 3.14159)
3722     _dbus_assert_not_reached ("doubles differ!");
3723
3724   if (strcmp (our_str, "Test string") != 0)
3725     _dbus_assert_not_reached ("strings differ!");
3726
3727   if (!our_bool)
3728     _dbus_assert_not_reached ("booleans differ");
3729   
3730   dbus_free (our_str);
3731 }
3732
3733 /**
3734  * @ingroup DBusMessageInternals
3735  * Unit test for DBusMessage.
3736  *
3737  * @returns #TRUE on success.
3738  */
3739 dbus_bool_t
3740 _dbus_message_test (const char *test_data_dir)
3741 {
3742   DBusMessage *message;
3743   DBusMessageLoader *loader;
3744   int i;
3745   const char *data;
3746   DBusMessage *copy;
3747   const char *name1;
3748   const char *name2;
3749   
3750   /* Test the vararg functions */
3751   message = dbus_message_new ("org.freedesktop.DBus.Test", "testMessage");
3752   _dbus_message_set_serial (message, 1);
3753   dbus_message_append_args (message,
3754                             DBUS_TYPE_INT32, -0x12345678,
3755                             DBUS_TYPE_STRING, "Test string",
3756                             DBUS_TYPE_DOUBLE, 3.14159,
3757                             DBUS_TYPE_BOOLEAN, TRUE,
3758                             0);
3759   _dbus_verbose_bytes_of_string (&message->header, 0,
3760                                  _dbus_string_get_length (&message->header));
3761   _dbus_verbose_bytes_of_string (&message->body, 0,
3762                                  _dbus_string_get_length (&message->body));
3763
3764   verify_test_message (message);
3765
3766   copy = dbus_message_copy (message);
3767   
3768   _dbus_assert (message->client_serial == copy->client_serial);
3769   _dbus_assert (message->reply_serial == copy->reply_serial);
3770   _dbus_assert (message->header_padding == copy->header_padding);
3771   
3772   _dbus_assert (_dbus_string_get_length (&message->header) ==
3773                 _dbus_string_get_length (&copy->header));
3774
3775   _dbus_assert (_dbus_string_get_length (&message->body) ==
3776                 _dbus_string_get_length (&copy->body));
3777
3778   verify_test_message (copy);
3779
3780   name1 = dbus_message_get_name (message);
3781   name2 = dbus_message_get_name (copy);
3782
3783   _dbus_assert (strcmp (name1, name2) == 0);
3784   
3785   dbus_message_unref (message);
3786   dbus_message_unref (copy);
3787   
3788   message = dbus_message_new ("org.freedesktop.DBus.Test", "testMessage");
3789   _dbus_message_set_serial (message, 1);
3790   dbus_message_set_reply_serial (message, 0x12345678);
3791
3792   dbus_message_append_string (message, "Test string");
3793   dbus_message_append_int32 (message, -0x12345678);
3794   dbus_message_append_uint32 (message, 0xedd1e);
3795   dbus_message_append_double (message, 3.14159);
3796
3797   message_iter_test (message);
3798
3799   /* Message loader test */
3800   _dbus_message_lock (message);
3801   loader = _dbus_message_loader_new ();
3802
3803   /* Write the header data one byte at a time */
3804   _dbus_string_get_const_data (&message->header, &data);
3805   for (i = 0; i < _dbus_string_get_length (&message->header); i++)
3806     {
3807       DBusString *buffer;
3808
3809       _dbus_message_loader_get_buffer (loader, &buffer);
3810       _dbus_string_append_byte (buffer, data[i]);
3811       _dbus_message_loader_return_buffer (loader, buffer, 1);
3812     }
3813
3814   /* Write the body data one byte at a time */
3815   _dbus_string_get_const_data (&message->body, &data);
3816   for (i = 0; i < _dbus_string_get_length (&message->body); i++)
3817     {
3818       DBusString *buffer;
3819
3820       _dbus_message_loader_get_buffer (loader, &buffer);
3821       _dbus_string_append_byte (buffer, data[i]);
3822       _dbus_message_loader_return_buffer (loader, buffer, 1);
3823     }
3824
3825   dbus_message_unref (message);
3826
3827   /* Now pop back the message */
3828   if (!_dbus_message_loader_queue_messages (loader))
3829     _dbus_assert_not_reached ("no memory to queue messages");
3830   
3831   if (_dbus_message_loader_get_is_corrupted (loader))
3832     _dbus_assert_not_reached ("message loader corrupted");
3833   
3834   message = _dbus_message_loader_pop_message (loader);
3835   if (!message)
3836     _dbus_assert_not_reached ("received a NULL message");
3837
3838   if (dbus_message_get_reply_serial (message) != 0x12345678)
3839     _dbus_assert_not_reached ("reply serial fields differ");
3840   
3841   message_iter_test (message);
3842   
3843   dbus_message_unref (message);
3844   _dbus_message_loader_unref (loader);
3845
3846   /* Now load every message in test_data_dir if we have one */
3847   if (test_data_dir == NULL)
3848     return TRUE;
3849
3850   return dbus_internal_do_not_use_foreach_message_file (test_data_dir,
3851                                                         (DBusForeachMessageFileFunc)
3852                                                         dbus_internal_do_not_use_try_message_file,
3853                                                         NULL);
3854 }
3855
3856 #endif /* DBUS_BUILD_TESTS */