2003-03-17 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  * @param message the message
1022  * @returns the message destination service (should not be freed)
1023  */
1024 const char*
1025 dbus_message_get_service (DBusMessage *message)
1026 {
1027   return get_string_field (message, FIELD_SERVICE, NULL);
1028 }
1029
1030 /**
1031  * Appends fields to a message given a variable argument
1032  * list. The variable argument list should contain the type
1033  * of the argument followed by the value to add. Array values
1034  * are specified by a pointer to the array followed by an int
1035  * giving the length of the array. The list is terminated
1036  * with 0.
1037  *
1038  * @param message the message
1039  * @param first_arg_type type of the first argument
1040  * @param ... value of first argument, list of additional type-value pairs
1041  * @returns #TRUE on success
1042  */
1043 dbus_bool_t
1044 dbus_message_append_args (DBusMessage *message,
1045                           int first_arg_type,
1046                           ...)
1047 {
1048   dbus_bool_t retval;
1049   va_list var_args;
1050
1051   va_start (var_args, first_arg_type);
1052   retval = dbus_message_append_args_valist (message,
1053                                             first_arg_type,
1054                                             var_args);
1055   va_end (var_args);
1056
1057   return retval;
1058 }
1059
1060 /**
1061  * This function takes a va_list for use by language bindings
1062  *
1063  * @see dbus_message_append_args.  
1064  * @param message the message
1065  * @param first_arg_type type of first argument
1066  * @param var_args value of first argument, then list of type/value pairs
1067  * @returns #TRUE on success
1068  */
1069 dbus_bool_t
1070 dbus_message_append_args_valist (DBusMessage *message,
1071                                  int          first_arg_type,
1072                                  va_list      var_args)
1073 {
1074   int type, old_len;
1075
1076   old_len = _dbus_string_get_length (&message->body);
1077   
1078   type = first_arg_type;
1079
1080   while (type != 0)
1081     {
1082       switch (type)
1083         {
1084         case DBUS_TYPE_NIL:
1085           if (!dbus_message_append_nil (message))
1086             goto enomem;
1087         case DBUS_TYPE_BOOLEAN:
1088           if (!dbus_message_append_boolean (message, va_arg (var_args, dbus_bool_t)))
1089             goto enomem;
1090           break;
1091         case DBUS_TYPE_INT32:
1092           if (!dbus_message_append_int32 (message, va_arg (var_args, dbus_int32_t)))
1093             goto enomem;
1094           break;
1095         case DBUS_TYPE_UINT32:
1096           if (!dbus_message_append_uint32 (message, va_arg (var_args, dbus_uint32_t)))
1097             goto enomem;            
1098           break;
1099         case DBUS_TYPE_DOUBLE:
1100           if (!dbus_message_append_double (message, va_arg (var_args, double)))
1101             goto enomem;
1102           break;
1103         case DBUS_TYPE_STRING:
1104           if (!dbus_message_append_string (message, va_arg (var_args, const char *)))
1105             goto enomem;
1106           break;
1107         case DBUS_TYPE_BOOLEAN_ARRAY:
1108           {
1109             int len;
1110             unsigned char *data;
1111
1112             data = va_arg (var_args, unsigned char *);
1113             len = va_arg (var_args, int);
1114
1115             if (!dbus_message_append_boolean_array (message, data, len))
1116               goto enomem;
1117           }
1118           break;
1119         case DBUS_TYPE_INT32_ARRAY:
1120           {
1121             int len;
1122             dbus_int32_t *data;
1123
1124             data = va_arg (var_args, dbus_int32_t *);
1125             len = va_arg (var_args, int);
1126
1127             if (!dbus_message_append_int32_array (message, data, len))
1128               goto enomem;
1129           }
1130           break;
1131         case DBUS_TYPE_UINT32_ARRAY:
1132           {
1133             int len;
1134             dbus_uint32_t *data;
1135
1136             data = va_arg (var_args, dbus_uint32_t *);
1137             len = va_arg (var_args, int);
1138
1139             if (!dbus_message_append_uint32_array (message, data, len))
1140               goto enomem;
1141           }
1142           break;
1143         case DBUS_TYPE_DOUBLE_ARRAY:
1144           {
1145             int len;
1146             double *data;
1147
1148             data = va_arg (var_args, double *);
1149             len = va_arg (var_args, int);
1150
1151             if (!dbus_message_append_double_array (message, data, len))
1152               goto enomem;
1153           }
1154           break;
1155         case DBUS_TYPE_BYTE_ARRAY:
1156           {
1157             int len;
1158             unsigned char *data;
1159
1160             data = va_arg (var_args, unsigned char *);
1161             len = va_arg (var_args, int);
1162
1163             if (!dbus_message_append_byte_array (message, data, len))
1164               goto enomem;
1165           }
1166           break;
1167         case DBUS_TYPE_STRING_ARRAY:
1168           {
1169             int len;
1170             const char **data;
1171             
1172             data = va_arg (var_args, const char **);
1173             len = va_arg (var_args, int);
1174
1175             if (!dbus_message_append_string_array (message, data, len))
1176               goto enomem;
1177           }
1178           break;
1179         case DBUS_TYPE_DICT:
1180           {
1181             DBusDict *dict;
1182
1183             dict = va_arg (var_args, DBusDict *);
1184
1185             if (!dbus_message_append_dict (message, dict))
1186               goto enomem;
1187             break;
1188           }
1189         default:
1190           _dbus_warn ("Unknown field type %d\n", type);
1191         }
1192
1193       type = va_arg (var_args, int);
1194     }
1195
1196   return TRUE;
1197
1198  enomem:
1199   return FALSE;
1200 }
1201
1202 /**
1203  * Appends a nil value to the message
1204  *
1205  * @param message the message
1206  * @returns #TRUE on success
1207  */
1208 dbus_bool_t
1209 dbus_message_append_nil (DBusMessage *message)
1210 {
1211   _dbus_assert (!message->locked);
1212
1213   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_NIL))
1214       return FALSE;
1215   else
1216     return TRUE;
1217 }
1218
1219 /**
1220  * Appends a boolean value to the message
1221  *
1222  * @param message the message
1223  * @param value the boolean value
1224  * @returns #TRUE on success
1225  */
1226 dbus_bool_t
1227 dbus_message_append_boolean (DBusMessage  *message,
1228                              dbus_bool_t   value)
1229 {
1230   _dbus_assert (!message->locked);
1231   
1232   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_BOOLEAN))
1233     return FALSE;
1234
1235   if (!_dbus_string_append_byte (&message->body, (value != FALSE)))
1236     {
1237       _dbus_string_shorten (&message->body, 1);
1238       return FALSE;
1239     }
1240
1241   return TRUE;
1242 }
1243
1244 /**
1245  * Appends a 32 bit signed integer to the message.
1246  *
1247  * @param message the message
1248  * @param value the integer value
1249  * @returns #TRUE on success
1250  */
1251 dbus_bool_t
1252 dbus_message_append_int32 (DBusMessage  *message,
1253                            dbus_int32_t  value)
1254 {
1255   _dbus_assert (!message->locked);
1256
1257   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_INT32))
1258       return FALSE;
1259   
1260   if (!_dbus_marshal_int32 (&message->body, message->byte_order, value))
1261     {
1262       _dbus_string_shorten (&message->body, 1);
1263       return FALSE;
1264     }
1265
1266   return TRUE;
1267 }
1268
1269 /**
1270  * Appends a 32 bit unsigned integer to the message.
1271  *
1272  * @param message the message
1273  * @param value the integer value
1274  * @returns #TRUE on success
1275  */
1276 dbus_bool_t
1277 dbus_message_append_uint32 (DBusMessage   *message,
1278                             dbus_uint32_t  value)
1279 {
1280   _dbus_assert (!message->locked);
1281
1282   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_UINT32))
1283       return FALSE;
1284   
1285   if (!_dbus_marshal_uint32 (&message->body, message->byte_order, value))
1286     {
1287       _dbus_string_shorten (&message->body, 1);
1288       return FALSE;
1289     }
1290
1291   return TRUE;      
1292 }
1293
1294 /**
1295  * Appends a double value to the message.
1296  *
1297  * @param message the message
1298  * @param value the double value
1299  * @returns #TRUE on success
1300  */
1301 dbus_bool_t
1302 dbus_message_append_double (DBusMessage *message,
1303                             double       value)
1304 {
1305   _dbus_assert (!message->locked);
1306
1307   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_DOUBLE))
1308     return FALSE;
1309
1310   if (!_dbus_marshal_double (&message->body, message->byte_order, value))
1311     {
1312       _dbus_string_shorten (&message->body, 1);
1313       return FALSE;
1314     }
1315   
1316   return TRUE;
1317 }
1318
1319 /**
1320  * Appends a UTF-8 string to the message.
1321  *
1322  * @param message the message
1323  * @param value the string
1324  * @returns #TRUE on success
1325  */
1326 dbus_bool_t
1327 dbus_message_append_string (DBusMessage *message,
1328                             const char  *value)
1329 {
1330   _dbus_assert (!message->locked);
1331
1332   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_STRING))
1333       return FALSE;
1334   
1335   if (!_dbus_marshal_string (&message->body, message->byte_order, value))
1336     {
1337       _dbus_string_shorten (&message->body, 1);
1338       return FALSE;      
1339     }
1340
1341   return TRUE;
1342 }
1343
1344 /**
1345  * Appends a boolean array to the message.
1346  *
1347  * @param message the message
1348  * @param value the array
1349  * @param len the length of the array
1350  * @returns #TRUE on success
1351  */
1352 dbus_bool_t
1353 dbus_message_append_boolean_array (DBusMessage         *message,
1354                                    unsigned const char *value,
1355                                    int                  len)
1356 {
1357   _dbus_assert (!message->locked);
1358
1359   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_BOOLEAN_ARRAY))
1360     return FALSE;
1361
1362   if (!_dbus_marshal_byte_array (&message->body, message->byte_order, value, len))
1363     {
1364       _dbus_string_shorten (&message->body, 1);
1365       return FALSE;
1366     }
1367
1368   return TRUE;
1369 }
1370
1371 /**
1372  * Appends a 32 bit signed integer array to the message.
1373  *
1374  * @param message the message
1375  * @param value the array
1376  * @param len the length of the array
1377  * @returns #TRUE on success
1378  */
1379 dbus_bool_t
1380 dbus_message_append_int32_array (DBusMessage        *message,
1381                                  const dbus_int32_t *value,
1382                                  int                 len)
1383 {
1384   _dbus_assert (!message->locked);
1385
1386   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_INT32_ARRAY))
1387     return FALSE;
1388
1389   if (!_dbus_marshal_int32_array (&message->body, message->byte_order,
1390                                   value, len))
1391     {
1392       _dbus_string_shorten (&message->body, 1);
1393       return FALSE;
1394     }
1395
1396   return TRUE;
1397 }
1398
1399 /**
1400  * Appends a 32 bit unsigned integer array to the message.
1401  *
1402  * @param message the message
1403  * @param value the array
1404  * @param len the length of the array
1405  * @returns #TRUE on success
1406  */
1407 dbus_bool_t
1408 dbus_message_append_uint32_array (DBusMessage         *message,
1409                                   const dbus_uint32_t *value,
1410                                   int                  len)
1411 {
1412   _dbus_assert (!message->locked);
1413
1414   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_UINT32_ARRAY))
1415     return FALSE;
1416
1417   if (!_dbus_marshal_uint32_array (&message->body, message->byte_order,
1418                                   value, len))
1419     {
1420       _dbus_string_shorten (&message->body, 1);
1421       return FALSE;
1422     }
1423
1424   return TRUE;
1425 }
1426
1427 /**
1428  * Appends a double array to the message.
1429  *
1430  * @param message the message
1431  * @param value the array
1432  * @param len the length of the array
1433  * @returns #TRUE on success
1434  */
1435 dbus_bool_t
1436 dbus_message_append_double_array (DBusMessage  *message,
1437                                   const double *value,
1438                                   int           len)
1439 {
1440   _dbus_assert (!message->locked);
1441
1442   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_DOUBLE_ARRAY))
1443     return FALSE;
1444
1445   if (!_dbus_marshal_double_array (&message->body, message->byte_order,
1446                                    value, len))
1447     {
1448       _dbus_string_shorten (&message->body, 1);
1449       return FALSE;
1450     }
1451
1452   return TRUE;
1453 }
1454
1455 /**
1456  * Appends a byte array to the message.
1457  *
1458  * @param message the message
1459  * @param value the array
1460  * @param len the length of the array
1461  * @returns #TRUE on success
1462  */
1463 dbus_bool_t
1464 dbus_message_append_byte_array (DBusMessage         *message,
1465                                 unsigned const char *value,
1466                                 int                 len)
1467 {
1468   _dbus_assert (!message->locked);
1469
1470   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_BYTE_ARRAY))
1471     return FALSE;
1472   
1473   if (!_dbus_marshal_byte_array (&message->body, message->byte_order, value, len))
1474     {
1475       _dbus_string_shorten (&message->body, 1);
1476       return FALSE;
1477     }
1478       
1479   return TRUE;
1480 }
1481
1482 /**
1483  * Appends a string array to the message.
1484  *
1485  * @param message the message
1486  * @param value the array
1487  * @param len the length of the array
1488  * @returns #TRUE on success
1489  */
1490 dbus_bool_t
1491 dbus_message_append_string_array (DBusMessage  *message,
1492                                   const char  **value,
1493                                   int           len)
1494 {
1495   _dbus_assert (!message->locked);
1496
1497   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_STRING_ARRAY))
1498     return FALSE;
1499
1500   if (!_dbus_marshal_string_array (&message->body, message->byte_order,
1501                                    (const char **)value, len))
1502     {
1503       _dbus_string_shorten (&message->body, 1);
1504       return FALSE;
1505     }
1506
1507   return TRUE;
1508 }
1509
1510 /**
1511  * Appends a dict to the message.
1512  *
1513  * @param message the message
1514  * @param dict the dict
1515  * @returns #TRUE on success
1516  */
1517 dbus_bool_t
1518 dbus_message_append_dict (DBusMessage *message,
1519                           DBusDict    *dict)
1520 {
1521   _dbus_assert (!message->locked);
1522
1523   if (!_dbus_string_append_byte (&message->body, DBUS_TYPE_DICT))
1524     return FALSE;
1525
1526   if (!_dbus_marshal_dict (&message->body, message->byte_order, dict))
1527     {
1528       _dbus_string_shorten (&message->body, 1);
1529       return FALSE;
1530     }
1531
1532   return TRUE;
1533 }
1534
1535 /**
1536  * Gets arguments from a message given a variable argument list.
1537  * The variable argument list should contain the type of the
1538  * argumen followed by a pointer to where the value should be
1539  * stored. The list is terminated with 0.
1540  *
1541  * @param message the message
1542  * @param error error to be filled in on failure
1543  * @param first_arg_type the first argument type
1544  * @param ... location for first argument value, then list of type-location pairs
1545  * @returns #FALSE if the error was set
1546  */
1547 dbus_bool_t
1548 dbus_message_get_args (DBusMessage *message,
1549                        DBusError   *error,
1550                        int          first_arg_type,
1551                        ...)
1552 {
1553   DBusResultCode retval;
1554   va_list var_args;
1555
1556   va_start (var_args, first_arg_type);
1557   retval = dbus_message_get_args_valist (message, error, first_arg_type, var_args);
1558   va_end (var_args);
1559
1560   return retval;
1561 }
1562
1563 /**
1564  * This function takes a va_list for use by language bindings
1565  *
1566  * @todo this function (or some lower-level non-convenience function)
1567  * needs better error handling; should allow the application to
1568  * distinguish between out of memory, and bad data from the remote
1569  * app. It also needs to not leak a bunch of args when it gets
1570  * to the arg that's bad, as that would be a security hole
1571  * (allow one app to force another to leak memory)
1572  *
1573  * @todo We need to free the argument data when an error occurs.
1574  *
1575  * @see dbus_message_get_args
1576  * @param message the message
1577  * @param error error to be filled in
1578  * @param first_arg_type type of the first argument
1579  * @param var_args return location for first argument, followed by list of type/location pairs
1580  * @returns #FALSE if error was set
1581  */
1582 dbus_bool_t
1583 dbus_message_get_args_valist (DBusMessage *message,
1584                               DBusError   *error,
1585                               int          first_arg_type,
1586                               va_list      var_args)
1587 {
1588   int spec_type, msg_type, i;
1589   DBusMessageIter *iter;
1590   dbus_bool_t retval;
1591   
1592   iter = dbus_message_get_args_iter (message);
1593
1594   if (iter == NULL)
1595     {
1596       dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
1597                       "No memory to get message arguments");
1598       return FALSE;
1599     }
1600
1601   retval = FALSE;
1602   
1603   spec_type = first_arg_type;
1604   i = 0;
1605   
1606   while (spec_type != 0)
1607     {
1608       msg_type = dbus_message_iter_get_arg_type (iter);      
1609       
1610       if (msg_type != spec_type)
1611         {
1612           dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
1613                           "Argument %d is specified to be of type \"%s\", but "
1614                           "is actually of type \"%s\"\n", i,
1615                           _dbus_type_to_string (spec_type),
1616                           _dbus_type_to_string (msg_type));
1617
1618           goto out;
1619         }
1620
1621       switch (spec_type)
1622         {
1623         case DBUS_TYPE_NIL:
1624           break;
1625         case DBUS_TYPE_BOOLEAN:
1626           {
1627             dbus_bool_t *ptr;
1628
1629             ptr = va_arg (var_args, dbus_bool_t *);
1630
1631             *ptr = dbus_message_iter_get_boolean (iter);
1632             break;
1633           }
1634         case DBUS_TYPE_INT32:
1635           {
1636             dbus_int32_t *ptr;
1637
1638             ptr = va_arg (var_args, dbus_int32_t *);
1639
1640             *ptr = dbus_message_iter_get_int32 (iter);
1641             break;
1642           }
1643         case DBUS_TYPE_UINT32:
1644           {
1645             dbus_uint32_t *ptr;
1646
1647             ptr = va_arg (var_args, dbus_uint32_t *);
1648
1649             *ptr = dbus_message_iter_get_uint32 (iter);
1650             break;
1651           }
1652
1653         case DBUS_TYPE_DOUBLE:
1654           {
1655             double *ptr;
1656
1657             ptr = va_arg (var_args, double *);
1658
1659             *ptr = dbus_message_iter_get_double (iter);
1660             break;
1661           }
1662
1663         case DBUS_TYPE_STRING:
1664           {
1665             char **ptr;
1666
1667             ptr = va_arg (var_args, char **);
1668
1669             *ptr = dbus_message_iter_get_string (iter);
1670
1671             if (!*ptr)
1672               {
1673                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
1674                                 "No memory for argument %d", i);
1675                 goto out;
1676               }
1677             
1678             break;
1679           }
1680
1681         case DBUS_TYPE_BOOLEAN_ARRAY:
1682           {
1683             unsigned char **ptr;
1684             int *len;
1685
1686             ptr = va_arg (var_args, unsigned char **);
1687             len = va_arg (var_args, int *);
1688
1689             if (!dbus_message_iter_get_boolean_array (iter, ptr, len))
1690               {
1691                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
1692                                 "No memory for argument %d", i);
1693                 goto out;
1694               }
1695             break;
1696           }
1697           
1698         case DBUS_TYPE_INT32_ARRAY:
1699           {
1700             dbus_int32_t **ptr;
1701             int *len;
1702
1703             ptr = va_arg (var_args, dbus_int32_t **);
1704             len = va_arg (var_args, int *);
1705
1706             if (!dbus_message_iter_get_int32_array (iter, ptr, len))
1707               {
1708                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
1709                                 "No memory for argument %d", i);
1710                 goto out;
1711               }
1712             
1713             break;
1714           }
1715
1716         case DBUS_TYPE_UINT32_ARRAY:
1717           {
1718             dbus_uint32_t **ptr;
1719             int *len;
1720
1721             ptr = va_arg (var_args, dbus_uint32_t **);
1722             len = va_arg (var_args, int *);
1723
1724             if (!dbus_message_iter_get_uint32_array (iter, ptr, len))
1725               {
1726                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
1727                                 "No memory for argument %d", i);
1728                 goto out;
1729               }
1730             
1731             break;
1732           }
1733
1734         case DBUS_TYPE_DOUBLE_ARRAY:
1735           {
1736             double **ptr;
1737             int *len;
1738
1739             ptr = va_arg (var_args, double **);
1740             len = va_arg (var_args, int *);
1741
1742             if (!dbus_message_iter_get_double_array (iter, ptr, len))
1743               {
1744                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
1745                                 "No memory for argument %d", i);
1746                 goto out;
1747               }
1748             break;
1749           }
1750           
1751         case DBUS_TYPE_BYTE_ARRAY:
1752           {
1753             unsigned char **ptr;
1754             int *len;
1755
1756             ptr = va_arg (var_args, unsigned char **);
1757             len = va_arg (var_args, int *);
1758
1759             if (!dbus_message_iter_get_byte_array (iter, ptr, len))
1760               {
1761                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
1762                                 "No memory for argument %d", i);
1763                 goto out;
1764               }
1765             break;
1766           }
1767         case DBUS_TYPE_STRING_ARRAY:
1768           {
1769             char ***ptr;
1770             int *len;
1771
1772             ptr = va_arg (var_args, char ***);
1773             len = va_arg (var_args, int *);
1774
1775             if (!dbus_message_iter_get_string_array (iter, ptr, len))
1776               {
1777                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
1778                                 "No memory for argument %d", i);
1779                 goto out;
1780               }
1781             break;
1782           }
1783         case DBUS_TYPE_DICT:
1784           {
1785             DBusDict **dict;
1786
1787             dict = va_arg (var_args, DBusDict **);
1788
1789             if (!dbus_message_iter_get_dict (iter, dict))
1790               {
1791                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
1792                                 "No memory for argument %d", i);
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
2331 /**
2332  * @addtogroup DBusMessageInternals
2333  *
2334  * @{
2335  */
2336 /**
2337  * @typedef DBusMessageLoader
2338  *
2339  * The DBusMessageLoader object encapsulates the process of converting
2340  * a byte stream into a series of DBusMessage. It buffers the incoming
2341  * bytes as efficiently as possible, and generates a queue of
2342  * messages. DBusMessageLoader is typically used as part of a
2343  * DBusTransport implementation. The DBusTransport then hands off
2344  * the loaded messages to a DBusConnection, making the messages
2345  * visible to the application.
2346  *
2347  * @todo write tests for break-loader that a) randomly delete header
2348  * fields and b) set string fields to zero-length and other funky
2349  * values.
2350  * 
2351  */
2352
2353 /* we definitely use signed ints for sizes, so don't exceed
2354  * _DBUS_INT_MAX; and add 16 for paranoia, since a message
2355  * over 128M is pretty nuts anyhow.
2356  */
2357
2358 /**
2359  * The maximum sane message size.
2360  */
2361 #define MAX_SANE_MESSAGE_SIZE (_DBUS_INT_MAX/16)
2362
2363 /**
2364  * Implementation details of DBusMessageLoader.
2365  * All members are private.
2366  */
2367 struct DBusMessageLoader
2368 {
2369   int refcount;        /**< Reference count. */
2370
2371   DBusString data;     /**< Buffered data */
2372   
2373   DBusList *messages;  /**< Complete messages. */
2374
2375   long max_message_size; /**< Maximum size of a message */
2376   
2377   unsigned int buffer_outstanding : 1; /**< Someone is using the buffer to read */
2378
2379   unsigned int corrupted : 1; /**< We got broken data, and are no longer working */
2380 };
2381
2382 /**
2383  * The initial buffer size of the message loader.
2384  * 
2385  * @todo this should be based on min header size plus some average
2386  * body size, or something. Or rather, the min header size only, if we
2387  * want to try to read only the header, store that in a DBusMessage,
2388  * then read only the body and store that, etc., depends on
2389  * how we optimize _dbus_message_loader_get_buffer() and what
2390  * the exact message format is.
2391  */
2392 #define INITIAL_LOADER_DATA_LEN 32
2393
2394 /**
2395  * Creates a new message loader. Returns #NULL if memory can't
2396  * be allocated.
2397  *
2398  * @returns new loader, or #NULL.
2399  */
2400 DBusMessageLoader*
2401 _dbus_message_loader_new (void)
2402 {
2403   DBusMessageLoader *loader;
2404
2405   loader = dbus_new0 (DBusMessageLoader, 1);
2406   if (loader == NULL)
2407     return NULL;
2408   
2409   loader->refcount = 1;
2410
2411   /* Try to cap message size at something that won't *totally* hose
2412    * the system if we have a couple of them.
2413    */
2414   loader->max_message_size = _DBUS_ONE_MEGABYTE * 32;
2415   
2416   if (!_dbus_string_init (&loader->data, _DBUS_INT_MAX))
2417     {
2418       dbus_free (loader);
2419       return NULL;
2420     }
2421
2422   /* preallocate the buffer for speed, ignore failure */
2423   _dbus_string_set_length (&loader->data, INITIAL_LOADER_DATA_LEN);
2424   _dbus_string_set_length (&loader->data, 0);
2425   
2426   return loader;
2427 }
2428
2429 /**
2430  * Increments the reference count of the loader.
2431  *
2432  * @param loader the loader.
2433  */
2434 void
2435 _dbus_message_loader_ref (DBusMessageLoader *loader)
2436 {
2437   loader->refcount += 1;
2438 }
2439
2440 /**
2441  * Decrements the reference count of the loader and finalizes the
2442  * loader when the count reaches zero.
2443  *
2444  * @param loader the loader.
2445  */
2446 void
2447 _dbus_message_loader_unref (DBusMessageLoader *loader)
2448 {
2449   loader->refcount -= 1;
2450   if (loader->refcount == 0)
2451     {
2452       _dbus_list_foreach (&loader->messages,
2453                           (DBusForeachFunction) dbus_message_unref,
2454                           NULL);
2455       _dbus_list_clear (&loader->messages);
2456       _dbus_string_free (&loader->data);
2457       dbus_free (loader);
2458     }
2459 }
2460
2461 /**
2462  * Gets the buffer to use for reading data from the network.  Network
2463  * data is read directly into an allocated buffer, which is then used
2464  * in the DBusMessage, to avoid as many extra memcpy's as possible.
2465  * The buffer must always be returned immediately using
2466  * _dbus_message_loader_return_buffer(), even if no bytes are
2467  * successfully read.
2468  *
2469  * @todo this function can be a lot more clever. For example
2470  * it can probably always return a buffer size to read exactly
2471  * the body of the next message, thus avoiding any memory wastage
2472  * or reallocs.
2473  *
2474  * @todo we need to enforce a max length on strings in header fields.
2475  * 
2476  * @param loader the message loader.
2477  * @param buffer the buffer
2478  */
2479 void
2480 _dbus_message_loader_get_buffer (DBusMessageLoader  *loader,
2481                                  DBusString        **buffer)
2482 {
2483   _dbus_assert (!loader->buffer_outstanding);
2484
2485   *buffer = &loader->data;
2486   
2487   loader->buffer_outstanding = TRUE;
2488 }
2489
2490 /**
2491  * The smallest header size that can occur. 
2492  * (It won't be valid)
2493  */
2494 #define DBUS_MINIMUM_HEADER_SIZE 16
2495
2496 /** Pack four characters as in "abcd" into a uint32 */
2497 #define FOUR_CHARS_TO_UINT32(a, b, c, d)                \
2498                       ((((dbus_uint32_t)a) << 24) |     \
2499                        (((dbus_uint32_t)b) << 16) |     \
2500                        (((dbus_uint32_t)c) << 8)  |     \
2501                        ((dbus_uint32_t)d))
2502
2503 /** DBUS_HEADER_FIELD_NAME packed into a dbus_uint32_t */
2504 #define DBUS_HEADER_FIELD_NAME_AS_UINT32    \
2505   FOUR_CHARS_TO_UINT32 ('n', 'a', 'm', 'e')
2506
2507 /** DBUS_HEADER_FIELD_SERVICE packed into a dbus_uint32_t */
2508 #define DBUS_HEADER_FIELD_SERVICE_AS_UINT32 \
2509   FOUR_CHARS_TO_UINT32 ('s', 'r', 'v', 'c')
2510
2511 /** DBUS_HEADER_FIELD_REPLY packed into a dbus_uint32_t */
2512 #define DBUS_HEADER_FIELD_REPLY_AS_UINT32   \
2513   FOUR_CHARS_TO_UINT32 ('r', 'p', 'l', 'y')
2514
2515 /** DBUS_HEADER_FIELD_SENDER Packed into a dbus_uint32_t */
2516 #define DBUS_HEADER_FIELD_SENDER_AS_UINT32  \
2517   FOUR_CHARS_TO_UINT32 ('s', 'n', 'd', 'r')
2518
2519 /* FIXME impose max length on name, srvc, sndr */
2520 static dbus_bool_t
2521 decode_header_data (const DBusString   *data,
2522                     int                 header_len,
2523                     int                 byte_order,
2524                     HeaderField         fields[FIELD_LAST],
2525                     int                *message_padding)
2526 {
2527   const char *field;
2528   int pos, new_pos;
2529   int i;
2530   
2531   if (header_len < 16)
2532     return FALSE;
2533   
2534   i = 0;
2535   while (i < FIELD_LAST)
2536     {
2537       fields[i].offset = -1;
2538       ++i;
2539     }
2540   
2541   fields[FIELD_HEADER_LENGTH].offset = 4;
2542   fields[FIELD_BODY_LENGTH].offset = 8;   
2543   fields[FIELD_CLIENT_SERIAL].offset = 12;
2544   
2545   /* Now handle the named fields. A real named field is at least 4
2546    * bytes for the name, plus a type code (1 byte) plus padding.  So
2547    * if we have less than 8 bytes left, it must be alignment padding,
2548    * not a field. While >= 8 bytes can't be entirely alignment
2549    * padding.
2550    */  
2551   pos = 16;
2552   while ((pos + 7) < header_len)
2553     {
2554       pos = _DBUS_ALIGN_VALUE (pos, 4);
2555       
2556       if ((pos + 4) > header_len)
2557         return FALSE;      
2558       
2559       _dbus_string_get_const_data_len (data, &field, pos, 4);
2560       pos += 4;
2561
2562       _dbus_assert (_DBUS_ALIGN_ADDRESS (field, 4) == field);
2563
2564       /* I believe FROM_BE is right, but if not we'll find out
2565        * I guess. ;-)
2566        */
2567       switch (DBUS_UINT32_FROM_BE (*(int*)field))
2568         {
2569         case DBUS_HEADER_FIELD_SERVICE_AS_UINT32:
2570           if (fields[FIELD_SERVICE].offset >= 0)
2571             {
2572               _dbus_verbose ("%s field provided twice\n",
2573                              DBUS_HEADER_FIELD_SERVICE);
2574               return FALSE;
2575             }
2576           
2577           fields[FIELD_SERVICE].offset = _DBUS_ALIGN_VALUE (pos + 1, 4);
2578 #if 0
2579           _dbus_verbose ("Found service name at offset %d\n",
2580                          fields[FIELD_SERVICE].offset);
2581 #endif
2582           break;
2583
2584         case DBUS_HEADER_FIELD_NAME_AS_UINT32:
2585           if (fields[FIELD_NAME].offset >= 0)
2586             {              
2587               _dbus_verbose ("%s field provided twice\n",
2588                              DBUS_HEADER_FIELD_NAME);
2589               return FALSE;
2590             }
2591           
2592           fields[FIELD_NAME].offset = _DBUS_ALIGN_VALUE (pos + 1, 4);
2593
2594 #if 0
2595           _dbus_verbose ("Found message name at offset %d\n",
2596                          fields[FIELD_NAME].offset);
2597 #endif
2598           break;
2599         case DBUS_HEADER_FIELD_SENDER_AS_UINT32:
2600           if (fields[FIELD_SENDER].offset >= 0)
2601             {
2602               _dbus_verbose ("%s field provided twice\n",
2603                              DBUS_HEADER_FIELD_SENDER);
2604               return FALSE;
2605             }
2606           
2607           fields[FIELD_SENDER].offset = _DBUS_ALIGN_VALUE (pos + 1, 4);
2608
2609           _dbus_verbose ("Found sender name at offset %d\n",
2610                          fields[FIELD_NAME].offset);
2611           break;
2612           
2613         case DBUS_HEADER_FIELD_REPLY_AS_UINT32:
2614           if (fields[FIELD_REPLY_SERIAL].offset >= 0)
2615             {
2616               _dbus_verbose ("%s field provided twice\n",
2617                              DBUS_HEADER_FIELD_REPLY);
2618               return FALSE;
2619             }
2620           
2621           fields[FIELD_REPLY_SERIAL].offset = _DBUS_ALIGN_VALUE (pos + 1, 4);
2622
2623           _dbus_verbose ("Found reply serial at offset %d\n",
2624                          fields[FIELD_REPLY_SERIAL].offset);
2625           break;
2626
2627         default:
2628           _dbus_verbose ("Ignoring an unknown header field: %c%c%c%c at offset %d\n",
2629                          field[0], field[1], field[2], field[3], pos);
2630         }
2631
2632       if (!_dbus_marshal_validate_arg (data, byte_order, pos, &new_pos))
2633         {
2634           _dbus_verbose ("Failed to validate argument to named header field\n");
2635           return FALSE;
2636         }
2637
2638       if (new_pos > header_len)
2639         {
2640           _dbus_verbose ("Named header field tries to extend beyond header length\n");
2641           return FALSE;
2642         }
2643       
2644       pos = new_pos;
2645     }
2646
2647   if (pos < header_len)
2648     {
2649       /* Alignment padding, verify that it's nul */
2650       _dbus_assert ((header_len - pos) < 8);
2651
2652       if (!_dbus_string_validate_nul (data,
2653                                       pos, (header_len - pos)))
2654         {
2655           _dbus_verbose ("header alignment padding is not nul\n");
2656           return FALSE;
2657         }
2658     }
2659
2660  if (fields[FIELD_NAME].offset < 0)
2661    {
2662      _dbus_verbose ("No %s field provided\n",
2663                     DBUS_HEADER_FIELD_NAME);
2664      return FALSE;
2665    }
2666   
2667   if (message_padding)
2668     *message_padding = header_len - pos;  
2669   
2670   return TRUE;
2671 }
2672
2673 /**
2674  * Returns a buffer obtained from _dbus_message_loader_get_buffer(),
2675  * indicating to the loader how many bytes of the buffer were filled
2676  * in. This function must always be called, even if no bytes were
2677  * successfully read.
2678  *
2679  * @param loader the loader.
2680  * @param buffer the buffer.
2681  * @param bytes_read number of bytes that were read into the buffer.
2682  */
2683 void
2684 _dbus_message_loader_return_buffer (DBusMessageLoader  *loader,
2685                                     DBusString         *buffer,
2686                                     int                 bytes_read)
2687 {
2688   _dbus_assert (loader->buffer_outstanding);
2689   _dbus_assert (buffer == &loader->data);
2690
2691   loader->buffer_outstanding = FALSE;
2692 }
2693
2694 /**
2695  * Converts buffered data into messages.
2696  *
2697  * @param loader the loader.
2698  * @returns #TRUE if we had enough memory to finish.
2699  */
2700 dbus_bool_t
2701 _dbus_message_loader_queue_messages (DBusMessageLoader *loader)
2702 {
2703   if (loader->corrupted)
2704     return TRUE;
2705
2706   while (_dbus_string_get_length (&loader->data) >= 16)
2707     {
2708       DBusMessage *message;      
2709       const char *header_data;
2710       int byte_order, header_len, body_len, header_padding;
2711       dbus_uint32_t header_len_unsigned, body_len_unsigned;
2712       
2713       _dbus_string_get_const_data_len (&loader->data, &header_data, 0, 16);
2714
2715       _dbus_assert (_DBUS_ALIGN_ADDRESS (header_data, 4) == header_data);
2716
2717       if (header_data[2] != DBUS_MAJOR_PROTOCOL_VERSION)
2718         {
2719           _dbus_verbose ("Message has protocol version %d ours is %d\n",
2720                          (int) header_data[2], DBUS_MAJOR_PROTOCOL_VERSION);
2721           loader->corrupted = TRUE;
2722           return TRUE;
2723         }
2724       
2725       byte_order = header_data[0];
2726
2727       if (byte_order != DBUS_LITTLE_ENDIAN &&
2728           byte_order != DBUS_BIG_ENDIAN)
2729         {
2730           _dbus_verbose ("Message with bad byte order '%c' received\n",
2731                          byte_order);
2732           loader->corrupted = TRUE;
2733           return TRUE;
2734         }
2735
2736       header_len_unsigned = _dbus_unpack_uint32 (byte_order, header_data + 4);
2737       body_len_unsigned = _dbus_unpack_uint32 (byte_order, header_data + 8);
2738
2739       if (header_len_unsigned < 16)
2740         {
2741           _dbus_verbose ("Message had broken too-small header length %u\n",
2742                          header_len_unsigned);
2743           loader->corrupted = TRUE;
2744           return TRUE;
2745         }
2746
2747       if (header_len_unsigned > (unsigned) MAX_SANE_MESSAGE_SIZE ||
2748           body_len_unsigned > (unsigned) MAX_SANE_MESSAGE_SIZE)
2749         {
2750           _dbus_verbose ("Header or body length too large (%u %u)\n",
2751                          header_len_unsigned,
2752                          body_len_unsigned);
2753           loader->corrupted = TRUE;
2754           return TRUE;
2755         }
2756
2757       /* Now that we know the values are in signed range, get
2758        * rid of stupid unsigned, just causes bugs
2759        */
2760       header_len = header_len_unsigned;
2761       body_len = body_len_unsigned;
2762
2763       if (_DBUS_ALIGN_VALUE (header_len, 8) != header_len_unsigned)
2764         {
2765           
2766           _dbus_verbose ("header length %d is not aligned to 8 bytes\n",
2767                          header_len);
2768           loader->corrupted = TRUE;
2769           return TRUE;
2770         }
2771       
2772       if (header_len + body_len > loader->max_message_size)
2773         {
2774           _dbus_verbose ("Message claimed length header = %d body = %d exceeds max message length %ld\n",
2775                          header_len, body_len, loader->max_message_size);
2776           loader->corrupted = TRUE;
2777           return TRUE;
2778         }
2779
2780       if (_dbus_string_get_length (&loader->data) >= (header_len + body_len))
2781         {
2782           HeaderField fields[FIELD_LAST];
2783           int i;
2784           int next_arg;          
2785
2786 #if 0
2787           _dbus_verbose_bytes_of_string (&loader->data, 0, header_len + body_len);
2788 #endif    
2789           if (!decode_header_data (&loader->data, header_len, byte_order,
2790                                    fields, &header_padding))
2791             {
2792               _dbus_verbose ("Header was invalid\n");
2793               loader->corrupted = TRUE;
2794               return TRUE;
2795             }
2796           
2797           next_arg = header_len;
2798           while (next_arg < (header_len + body_len))
2799             {
2800               int prev = next_arg;
2801
2802               if (!_dbus_marshal_validate_arg (&loader->data,
2803                                                byte_order,
2804                                                next_arg,
2805                                                &next_arg))
2806                 {
2807                   loader->corrupted = TRUE;
2808                   return TRUE;
2809                 }
2810
2811               _dbus_assert (next_arg > prev);
2812             }
2813           
2814           if (next_arg > (header_len + body_len))
2815             {
2816               _dbus_verbose ("end of last arg at %d but message has len %d+%d=%d\n",
2817                              next_arg, header_len, body_len,
2818                              header_len + body_len);
2819               loader->corrupted = TRUE;
2820               return TRUE;
2821             }
2822
2823           message = dbus_message_new_empty_header ();
2824           if (message == NULL)
2825             return FALSE;
2826
2827           message->byte_order = byte_order;
2828           message->header_padding = header_padding;
2829           
2830           /* Copy in the offsets we found */
2831           i = 0;
2832           while (i < FIELD_LAST)
2833             {
2834               message->header_fields[i] = fields[i];
2835               ++i;
2836             }
2837           
2838           if (!_dbus_list_append (&loader->messages, message))
2839             {
2840               dbus_message_unref (message);
2841               return FALSE;
2842             }
2843
2844           _dbus_assert (_dbus_string_get_length (&message->header) == 0);
2845           _dbus_assert (_dbus_string_get_length (&message->body) == 0);
2846
2847           _dbus_assert (_dbus_string_get_length (&loader->data) >=
2848                         (header_len + body_len));
2849           
2850           if (!_dbus_string_move_len (&loader->data, 0, header_len, &message->header, 0))
2851             {
2852               _dbus_list_remove_last (&loader->messages, message);
2853               dbus_message_unref (message);
2854               return FALSE;
2855             }
2856           
2857           if (!_dbus_string_move_len (&loader->data, 0, body_len, &message->body, 0))
2858             {
2859               dbus_bool_t result;
2860
2861               /* put the header back, we'll try again later */
2862               result = _dbus_string_copy_len (&message->header, 0, header_len,
2863                                               &loader->data, 0);
2864               _dbus_assert (result); /* because DBusString never reallocs smaller */
2865
2866               _dbus_list_remove_last (&loader->messages, message);
2867               dbus_message_unref (message);
2868               return FALSE;
2869             }
2870
2871           _dbus_assert (_dbus_string_get_length (&message->header) == header_len);
2872           _dbus_assert (_dbus_string_get_length (&message->body) == body_len);
2873
2874           /* Fill in caches */
2875           message->reply_serial = get_int_field (message,
2876                                                  FIELD_REPLY_SERIAL);
2877           message->client_serial = get_int_field (message,
2878                                                   FIELD_CLIENT_SERIAL);
2879           
2880           _dbus_verbose ("Loaded message %p\n", message);
2881         }
2882       else
2883         return TRUE;
2884     }
2885
2886   return TRUE;
2887 }
2888
2889 /**
2890  * Peeks at first loaded message, returns #NULL if no messages have
2891  * been queued.
2892  *
2893  * @param loader the loader.
2894  * @returns the next message, or #NULL if none.
2895  */
2896 DBusMessage*
2897 _dbus_message_loader_peek_message (DBusMessageLoader *loader)
2898 {
2899   if (loader->messages)
2900     return loader->messages->data;
2901   else
2902     return NULL;
2903 }
2904
2905 /**
2906  * Pops a loaded message (passing ownership of the message
2907  * to the caller). Returns #NULL if no messages have been
2908  * queued.
2909  *
2910  * @param loader the loader.
2911  * @returns the next message, or #NULL if none.
2912  */
2913 DBusMessage*
2914 _dbus_message_loader_pop_message (DBusMessageLoader *loader)
2915 {
2916   return _dbus_list_pop_first (&loader->messages);
2917 }
2918
2919 /**
2920  * Pops a loaded message inside a list link (passing ownership of the
2921  * message and link to the caller). Returns #NULL if no messages have
2922  * been loaded.
2923  *
2924  * @param loader the loader.
2925  * @returns the next message link, or #NULL if none.
2926  */
2927 DBusList*
2928 _dbus_message_loader_pop_message_link (DBusMessageLoader *loader)
2929 {
2930   return _dbus_list_pop_first_link (&loader->messages);
2931 }
2932
2933 /**
2934  * Checks whether the loader is confused due to bad data.
2935  * If messages are received that are invalid, the
2936  * loader gets confused and gives up permanently.
2937  * This state is called "corrupted."
2938  *
2939  * @param loader the loader
2940  * @returns #TRUE if the loader is hosed.
2941  */
2942 dbus_bool_t
2943 _dbus_message_loader_get_is_corrupted (DBusMessageLoader *loader)
2944 {
2945   return loader->corrupted;
2946 }
2947
2948 /**
2949  * Sets the maximum size message we allow.
2950  *
2951  * @param loader the loader
2952  * @param size the max message size in bytes
2953  */
2954 void
2955 _dbus_message_loader_set_max_message_size (DBusMessageLoader  *loader,
2956                                            long                size)
2957 {
2958   if (size > MAX_SANE_MESSAGE_SIZE)
2959     {
2960       _dbus_verbose ("clamping requested max message size %ld to %d\n",
2961                      size, MAX_SANE_MESSAGE_SIZE);
2962       size = MAX_SANE_MESSAGE_SIZE;
2963     }
2964   loader->max_message_size = size;
2965 }
2966
2967 /**
2968  * Gets the maximum allowed message size in bytes.
2969  *
2970  * @param loader the loader
2971  * @returns max size in bytes
2972  */
2973 long
2974 _dbus_message_loader_get_max_message_size (DBusMessageLoader  *loader)
2975 {
2976   return loader->max_message_size;
2977 }
2978
2979 /** @} */
2980 #ifdef DBUS_BUILD_TESTS
2981 #include "dbus-test.h"
2982 #include <stdio.h>
2983
2984 static void
2985 message_iter_test (DBusMessage *message)
2986 {
2987   DBusMessageIter *iter;
2988   char *str;
2989   
2990   iter = dbus_message_get_args_iter (message);
2991
2992   /* String tests */
2993   if (dbus_message_iter_get_arg_type (iter) != DBUS_TYPE_STRING)
2994     _dbus_assert_not_reached ("Argument type isn't string");
2995
2996   str = dbus_message_iter_get_string (iter);
2997   if (strcmp (str, "Test string") != 0)
2998     _dbus_assert_not_reached ("Strings differ");
2999   dbus_free (str);
3000
3001   if (!dbus_message_iter_next (iter))
3002     _dbus_assert_not_reached ("Reached end of arguments");
3003
3004   /* Signed integer tests */
3005   if (dbus_message_iter_get_arg_type (iter) != DBUS_TYPE_INT32)
3006     _dbus_assert_not_reached ("Argument type isn't int32");
3007
3008   if (dbus_message_iter_get_int32 (iter) != -0x12345678)
3009     _dbus_assert_not_reached ("Signed integers differ");
3010
3011   if (!dbus_message_iter_next (iter))
3012     _dbus_assert_not_reached ("Reached end of fields");
3013   
3014   /* Unsigned integer tests */
3015   if (dbus_message_iter_get_arg_type (iter) != DBUS_TYPE_UINT32)
3016     _dbus_assert_not_reached ("Argument type isn't int32");
3017
3018   if (dbus_message_iter_get_uint32 (iter) != 0xedd1e)
3019     _dbus_assert_not_reached ("Unsigned integers differ");
3020
3021   if (!dbus_message_iter_next (iter))
3022     _dbus_assert_not_reached ("Reached end of arguments");
3023
3024   /* Double tests */
3025   if (dbus_message_iter_get_arg_type (iter) != DBUS_TYPE_DOUBLE)
3026     _dbus_assert_not_reached ("Argument type isn't double");
3027
3028   if (dbus_message_iter_get_double (iter) != 3.14159)
3029     _dbus_assert_not_reached ("Doubles differ");
3030
3031   if (dbus_message_iter_next (iter))
3032     _dbus_assert_not_reached ("Didn't reach end of arguments");
3033   
3034   dbus_message_iter_unref (iter);
3035 }
3036
3037 static dbus_bool_t
3038 check_message_handling (DBusMessage *message)
3039 {
3040   DBusMessageIter *iter;
3041   int type;
3042   dbus_bool_t retval;
3043   dbus_int32_t client_serial;
3044   
3045   retval = FALSE;
3046   iter = NULL;
3047   
3048   client_serial = dbus_message_get_serial (message);
3049
3050   /* can't use set_serial due to the assertions at the start of it */
3051   set_int_field (message, FIELD_CLIENT_SERIAL,
3052                  client_serial);
3053   
3054   if (client_serial != dbus_message_get_serial (message))
3055     {
3056       _dbus_warn ("get/set cycle for client_serial did not succeed\n");
3057       goto failed;
3058     }
3059   
3060   /* If we implement message_set_arg (message, n, value)
3061    * then we would want to test it here
3062    */
3063
3064   iter = dbus_message_get_args_iter (message);
3065   while ((type = dbus_message_iter_get_arg_type (iter)) != DBUS_TYPE_INVALID)
3066     {
3067       switch (type)
3068         {
3069         case DBUS_TYPE_NIL:
3070           break;
3071         case DBUS_TYPE_INT32:
3072           dbus_message_iter_get_int32 (iter);
3073           break;
3074         case DBUS_TYPE_UINT32:
3075           dbus_message_iter_get_uint32 (iter);
3076           break;
3077         case DBUS_TYPE_DOUBLE:
3078           dbus_message_iter_get_double (iter);
3079           break;
3080         case DBUS_TYPE_STRING:
3081           {
3082             char *str;
3083             str = dbus_message_iter_get_string (iter);
3084             dbus_free (str);
3085           }
3086           break;
3087         case DBUS_TYPE_BOOLEAN_ARRAY:
3088           {
3089             unsigned char *values;
3090             int len;
3091             
3092             if (!dbus_message_iter_get_boolean_array (iter, &values, &len))
3093               return FALSE;
3094
3095             dbus_free (values);
3096           }
3097           break;
3098         case DBUS_TYPE_INT32_ARRAY:
3099           {
3100             dbus_int32_t *values;
3101             int len;
3102             
3103             if (!dbus_message_iter_get_int32_array (iter, &values, &len))
3104               return FALSE;
3105
3106             dbus_free (values);
3107           }
3108           break;
3109         case DBUS_TYPE_UINT32_ARRAY:
3110           {
3111             dbus_uint32_t *values;
3112             int len;
3113             
3114             if (!dbus_message_iter_get_uint32_array (iter, &values, &len))
3115               return FALSE;
3116
3117             dbus_free (values);
3118           }
3119           break;
3120         case DBUS_TYPE_DOUBLE_ARRAY:
3121           {
3122             double *values;
3123             int len;
3124             
3125             if (!dbus_message_iter_get_double_array (iter, &values, &len))
3126               return FALSE;
3127
3128             dbus_free (values);
3129           }
3130           break;
3131         case DBUS_TYPE_STRING_ARRAY:
3132           {
3133             char **values;
3134             int len;
3135             
3136             if (!dbus_message_iter_get_string_array (iter, &values, &len))
3137               return FALSE;
3138
3139             dbus_free_string_array (values);
3140           }
3141           break;
3142
3143         case DBUS_TYPE_DICT:
3144           {
3145             DBusDict *dict;
3146
3147             if (!dbus_message_iter_get_dict (iter, &dict))
3148               return FALSE;
3149             dbus_dict_unref (dict);
3150           }
3151           break;
3152
3153         default:
3154           break;
3155         }
3156       
3157       if (!dbus_message_iter_next (iter))
3158         break;
3159     }
3160
3161   retval = TRUE;
3162   
3163  failed:
3164   if (iter)
3165     dbus_message_iter_unref (iter);
3166
3167   return retval;
3168 }
3169
3170 static dbus_bool_t
3171 check_have_valid_message (DBusMessageLoader *loader)
3172 {
3173   DBusMessage *message;
3174   dbus_bool_t retval;
3175
3176   message = NULL;
3177   retval = FALSE;
3178
3179   if (!_dbus_message_loader_queue_messages (loader))
3180     _dbus_assert_not_reached ("no memory to queue messages");
3181   
3182   if (_dbus_message_loader_get_is_corrupted (loader))
3183     {
3184       _dbus_warn ("loader corrupted on message that was expected to be valid\n");
3185       goto failed;
3186     }
3187   
3188   message = _dbus_message_loader_pop_message (loader);
3189   if (message == NULL)
3190     {
3191       _dbus_warn ("didn't load message that was expected to be valid (message not popped)\n");
3192       goto failed;
3193     }
3194   
3195   if (_dbus_string_get_length (&loader->data) > 0)
3196     {
3197       _dbus_warn ("had leftover bytes from expected-to-be-valid single message\n");
3198       goto failed;
3199     }
3200
3201   /* Verify that we're able to properly deal with the message.
3202    * For example, this would detect improper handling of messages
3203    * in nonstandard byte order.
3204    */
3205   if (!check_message_handling (message))
3206     goto failed;  
3207   
3208   retval = TRUE;
3209
3210  failed:
3211   if (message)
3212     dbus_message_unref (message);
3213
3214   return retval;
3215 }
3216
3217 static dbus_bool_t
3218 check_invalid_message (DBusMessageLoader *loader)
3219 {
3220   dbus_bool_t retval;
3221
3222   retval = FALSE;
3223
3224   if (!_dbus_message_loader_queue_messages (loader))
3225     _dbus_assert_not_reached ("no memory to queue messages");
3226   
3227   if (!_dbus_message_loader_get_is_corrupted (loader))
3228     {
3229       _dbus_warn ("loader not corrupted on message that was expected to be invalid\n");
3230       goto failed;
3231     }
3232
3233   retval = TRUE;
3234
3235  failed:
3236   return retval;
3237 }
3238
3239 static dbus_bool_t
3240 check_incomplete_message (DBusMessageLoader *loader)
3241 {
3242   DBusMessage *message;
3243   dbus_bool_t retval;
3244
3245   message = NULL;
3246   retval = FALSE;
3247
3248   if (!_dbus_message_loader_queue_messages (loader))
3249     _dbus_assert_not_reached ("no memory to queue messages");
3250   
3251   if (_dbus_message_loader_get_is_corrupted (loader))
3252     {
3253       _dbus_warn ("loader corrupted on message that was expected to be valid (but incomplete)\n");
3254       goto failed;
3255     }
3256   
3257   message = _dbus_message_loader_pop_message (loader);
3258   if (message != NULL)
3259     {
3260       _dbus_warn ("loaded message that was expected to be incomplete\n");
3261       goto failed;
3262     }
3263
3264   retval = TRUE;
3265
3266  failed:
3267   if (message)
3268     dbus_message_unref (message);
3269   return retval;
3270 }
3271
3272 static dbus_bool_t
3273 check_loader_results (DBusMessageLoader      *loader,
3274                       DBusMessageValidity     validity)
3275 {
3276   if (!_dbus_message_loader_queue_messages (loader))
3277     _dbus_assert_not_reached ("no memory to queue messages");
3278   
3279   switch (validity)
3280     {
3281     case _DBUS_MESSAGE_VALID:
3282       return check_have_valid_message (loader);
3283     case _DBUS_MESSAGE_INVALID:
3284       return check_invalid_message (loader);
3285     case _DBUS_MESSAGE_INCOMPLETE:
3286       return check_incomplete_message (loader);
3287     case _DBUS_MESSAGE_UNKNOWN:
3288       return TRUE;
3289     }
3290
3291   _dbus_assert_not_reached ("bad DBusMessageValidity");
3292   return FALSE;
3293 }
3294
3295
3296 /**
3297  * Loads the message in the given message file.
3298  *
3299  * @param filename filename to load
3300  * @param is_raw if #TRUE load as binary data, if #FALSE as message builder language
3301  * @param data string to load message into
3302  * @returns #TRUE if the message was loaded
3303  */
3304 dbus_bool_t
3305 dbus_internal_do_not_use_load_message_file (const DBusString    *filename,
3306                                             dbus_bool_t          is_raw,
3307                                             DBusString          *data)
3308 {
3309   dbus_bool_t retval;
3310
3311   retval = FALSE;  
3312
3313   if (is_raw)
3314     {
3315       DBusError error;
3316
3317       dbus_error_init (&error);
3318       if (!_dbus_file_get_contents (data, filename, &error))
3319         {
3320           const char *s;      
3321           _dbus_string_get_const_data (filename, &s);
3322           _dbus_warn ("Could not load message file %s: %s\n", s, error.message);
3323           dbus_error_free (&error);
3324           goto failed;
3325         }
3326     }
3327   else
3328     {
3329       if (!_dbus_message_data_load (data, filename))
3330         {
3331           const char *s;      
3332           _dbus_string_get_const_data (filename, &s);
3333           _dbus_warn ("Could not load message file %s\n", s);
3334           goto failed;
3335         }
3336     }
3337
3338   retval = TRUE;
3339   
3340  failed:
3341
3342   return retval;
3343 }
3344
3345 /**
3346  * Tries loading the message in the given message file
3347  * and verifies that DBusMessageLoader can handle it.
3348  *
3349  * @param filename filename to load
3350  * @param is_raw if #TRUE load as binary data, if #FALSE as message builder language
3351  * @param expected_validity what the message has to be like to return #TRUE
3352  * @returns #TRUE if the message has the expected validity
3353  */
3354 dbus_bool_t
3355 dbus_internal_do_not_use_try_message_file (const DBusString    *filename,
3356                                            dbus_bool_t          is_raw,
3357                                            DBusMessageValidity  expected_validity)
3358 {
3359   DBusString data;
3360   dbus_bool_t retval;
3361
3362   retval = FALSE;
3363   
3364   if (!_dbus_string_init (&data, _DBUS_INT_MAX))
3365     _dbus_assert_not_reached ("could not allocate string\n");
3366
3367   if (!dbus_internal_do_not_use_load_message_file (filename, is_raw,
3368                                                    &data))
3369     goto failed;
3370
3371   retval = dbus_internal_do_not_use_try_message_data (&data, expected_validity);
3372
3373  failed:
3374
3375   if (!retval)
3376     {
3377       const char *s;
3378
3379       if (_dbus_string_get_length (&data) > 0)
3380         _dbus_verbose_bytes_of_string (&data, 0,
3381                                        _dbus_string_get_length (&data));
3382       
3383       _dbus_string_get_const_data (filename, &s);
3384       _dbus_warn ("Failed message loader test on %s\n",
3385                   s);
3386     }
3387   
3388   _dbus_string_free (&data);
3389
3390   return retval;
3391 }
3392
3393 /**
3394  * Tries loading the given message data.
3395  *
3396  *
3397  * @param data the message data
3398  * @param expected_validity what the message has to be like to return #TRUE
3399  * @returns #TRUE if the message has the expected validity
3400  */
3401 dbus_bool_t
3402 dbus_internal_do_not_use_try_message_data (const DBusString    *data,
3403                                            DBusMessageValidity  expected_validity)
3404 {
3405   DBusMessageLoader *loader;
3406   dbus_bool_t retval;
3407   int len;
3408   int i;
3409
3410   loader = NULL;
3411   retval = FALSE;
3412
3413   /* Write the data one byte at a time */
3414   
3415   loader = _dbus_message_loader_new ();
3416
3417   len = _dbus_string_get_length (data);
3418   for (i = 0; i < len; i++)
3419     {
3420       DBusString *buffer;
3421
3422       _dbus_message_loader_get_buffer (loader, &buffer);
3423       _dbus_string_append_byte (buffer,
3424                                 _dbus_string_get_byte (data, i));
3425       _dbus_message_loader_return_buffer (loader, buffer, 1);
3426     }
3427   
3428   if (!check_loader_results (loader, expected_validity))
3429     goto failed;
3430
3431   _dbus_message_loader_unref (loader);
3432   loader = NULL;
3433
3434   /* Write the data all at once */
3435   
3436   loader = _dbus_message_loader_new ();
3437
3438   {
3439     DBusString *buffer;
3440     
3441     _dbus_message_loader_get_buffer (loader, &buffer);
3442     _dbus_string_copy (data, 0, buffer,
3443                        _dbus_string_get_length (buffer));
3444     _dbus_message_loader_return_buffer (loader, buffer, 1);
3445   }
3446   
3447   if (!check_loader_results (loader, expected_validity))
3448     goto failed;
3449
3450   _dbus_message_loader_unref (loader);
3451   loader = NULL;  
3452
3453   /* Write the data 2 bytes at a time */
3454   
3455   loader = _dbus_message_loader_new ();
3456
3457   len = _dbus_string_get_length (data);
3458   for (i = 0; i < len; i += 2)
3459     {
3460       DBusString *buffer;
3461
3462       _dbus_message_loader_get_buffer (loader, &buffer);
3463       _dbus_string_append_byte (buffer,
3464                                 _dbus_string_get_byte (data, i));
3465       if ((i+1) < len)
3466         _dbus_string_append_byte (buffer,
3467                                   _dbus_string_get_byte (data, i+1));
3468       _dbus_message_loader_return_buffer (loader, buffer, 1);
3469     }
3470   
3471   if (!check_loader_results (loader, expected_validity))
3472     goto failed;
3473
3474   _dbus_message_loader_unref (loader);
3475   loader = NULL;
3476   
3477   retval = TRUE;
3478   
3479  failed:
3480   
3481   if (loader)
3482     _dbus_message_loader_unref (loader);
3483   
3484   return retval;
3485 }
3486
3487 static dbus_bool_t
3488 process_test_subdir (const DBusString          *test_base_dir,
3489                      const char                *subdir,
3490                      DBusMessageValidity        validity,
3491                      DBusForeachMessageFileFunc function,
3492                      void                      *user_data)
3493 {
3494   DBusString test_directory;
3495   DBusString filename;
3496   DBusDirIter *dir;
3497   dbus_bool_t retval;
3498   DBusError error;
3499
3500   retval = FALSE;
3501   dir = NULL;
3502   
3503   if (!_dbus_string_init (&test_directory, _DBUS_INT_MAX))
3504     _dbus_assert_not_reached ("didn't allocate test_directory\n");
3505
3506   _dbus_string_init_const (&filename, subdir);
3507   
3508   if (!_dbus_string_copy (test_base_dir, 0,
3509                           &test_directory, 0))
3510     _dbus_assert_not_reached ("couldn't copy test_base_dir to test_directory");
3511   
3512   if (!_dbus_concat_dir_and_file (&test_directory, &filename))    
3513     _dbus_assert_not_reached ("couldn't allocate full path");
3514
3515   _dbus_string_free (&filename);
3516   if (!_dbus_string_init (&filename, _DBUS_INT_MAX))
3517     _dbus_assert_not_reached ("didn't allocate filename string\n");
3518
3519   dbus_error_init (&error);
3520   dir = _dbus_directory_open (&test_directory, &error);
3521   if (dir == NULL)
3522     {
3523       const char *s;
3524       _dbus_string_get_const_data (&test_directory, &s);
3525       _dbus_warn ("Could not open %s: %s\n", s,
3526                   error.message);
3527       dbus_error_free (&error);
3528       goto failed;
3529     }
3530
3531   printf ("Testing:\n");
3532   
3533  next:
3534   while (_dbus_directory_get_next_file (dir, &filename, &error))
3535     {
3536       DBusString full_path;
3537       dbus_bool_t is_raw;
3538       
3539       if (!_dbus_string_init (&full_path, _DBUS_INT_MAX))
3540         _dbus_assert_not_reached ("couldn't init string");
3541
3542       if (!_dbus_string_copy (&test_directory, 0, &full_path, 0))
3543         _dbus_assert_not_reached ("couldn't copy dir to full_path");
3544
3545       if (!_dbus_concat_dir_and_file (&full_path, &filename))
3546         _dbus_assert_not_reached ("couldn't concat file to dir");
3547
3548       if (_dbus_string_ends_with_c_str (&filename, ".message"))
3549         is_raw = FALSE;
3550       else if (_dbus_string_ends_with_c_str (&filename, ".message-raw"))
3551         is_raw = TRUE;
3552       else
3553         {
3554           const char *filename_c;
3555           _dbus_string_get_const_data (&filename, &filename_c);
3556           _dbus_verbose ("Skipping non-.message file %s\n",
3557                          filename_c);
3558           _dbus_string_free (&full_path);
3559           goto next;
3560         }
3561
3562       {
3563         const char *s;
3564         _dbus_string_get_const_data (&filename, &s);
3565         printf ("    %s\n", s);
3566       }
3567       
3568       _dbus_verbose (" expecting %s\n",
3569                      validity == _DBUS_MESSAGE_VALID ? "valid" :
3570                      (validity == _DBUS_MESSAGE_INVALID ? "invalid" :
3571                       (validity == _DBUS_MESSAGE_INCOMPLETE ? "incomplete" : "unknown")));
3572       
3573       if (! (*function) (&full_path, is_raw, validity, user_data))
3574         {
3575           _dbus_string_free (&full_path);
3576           goto failed;
3577         }
3578       else
3579         _dbus_string_free (&full_path);
3580     }
3581
3582   if (dbus_error_is_set (&error))
3583     {
3584       const char *s;
3585       _dbus_string_get_const_data (&test_directory, &s);
3586       _dbus_warn ("Could not get next file in %s: %s\n",
3587                   s, error.message);
3588       dbus_error_free (&error);
3589       goto failed;
3590     }
3591     
3592   retval = TRUE;
3593   
3594  failed:
3595
3596   if (dir)
3597     _dbus_directory_close (dir);
3598   _dbus_string_free (&test_directory);
3599   _dbus_string_free (&filename);
3600
3601   return retval;
3602 }
3603                      
3604 /**
3605  * Runs the given function on every message file in the test suite.
3606  * The function should return #FALSE on test failure or fatal error.
3607  *
3608  * @param test_data_dir root dir of the test suite data files (top_srcdir/test/data)
3609  * @param func the function to run
3610  * @param user_data data for function
3611  * @returns #FALSE if there's a failure
3612  */
3613 dbus_bool_t
3614 dbus_internal_do_not_use_foreach_message_file (const char                *test_data_dir,
3615                                                DBusForeachMessageFileFunc func,
3616                                                void                      *user_data)
3617 {
3618   DBusString test_directory;
3619   dbus_bool_t retval;
3620
3621   retval = FALSE;
3622   
3623   _dbus_string_init_const (&test_directory, test_data_dir);
3624
3625   if (!process_test_subdir (&test_directory, "valid-messages",
3626                             _DBUS_MESSAGE_VALID, func, user_data))
3627     goto failed;
3628
3629   if (!process_test_subdir (&test_directory, "invalid-messages",
3630                             _DBUS_MESSAGE_INVALID, func, user_data))
3631     goto failed;
3632   
3633   if (!process_test_subdir (&test_directory, "incomplete-messages",
3634                             _DBUS_MESSAGE_INCOMPLETE, func, user_data))
3635     goto failed;
3636
3637   retval = TRUE;
3638   
3639  failed:
3640
3641   _dbus_string_free (&test_directory);
3642   
3643   return retval;
3644 }
3645
3646 static void
3647 verify_test_message (DBusMessage *message)
3648 {
3649   dbus_int32_t our_int;
3650   char *our_str;
3651   double our_double;
3652   dbus_bool_t our_bool;
3653   
3654   if (!dbus_message_get_args (message, NULL,
3655                               DBUS_TYPE_INT32, &our_int,
3656                               DBUS_TYPE_STRING, &our_str,
3657                               DBUS_TYPE_DOUBLE, &our_double,
3658                               DBUS_TYPE_BOOLEAN, &our_bool,
3659                               0))
3660     _dbus_assert_not_reached ("Could not get arguments");
3661
3662   if (our_int != -0x12345678)
3663     _dbus_assert_not_reached ("integers differ!");
3664
3665   if (our_double != 3.14159)
3666     _dbus_assert_not_reached ("doubles differ!");
3667
3668   if (strcmp (our_str, "Test string") != 0)
3669     _dbus_assert_not_reached ("strings differ!");
3670
3671   if (!our_bool)
3672     _dbus_assert_not_reached ("booleans differ");
3673   
3674   dbus_free (our_str);
3675 }
3676
3677 /**
3678  * @ingroup DBusMessageInternals
3679  * Unit test for DBusMessage.
3680  *
3681  * @returns #TRUE on success.
3682  */
3683 dbus_bool_t
3684 _dbus_message_test (const char *test_data_dir)
3685 {
3686   DBusMessage *message;
3687   DBusMessageLoader *loader;
3688   int i;
3689   const char *data;
3690   DBusMessage *copy;
3691   const char *name1;
3692   const char *name2;
3693   
3694   /* Test the vararg functions */
3695   message = dbus_message_new ("org.freedesktop.DBus.Test", "testMessage");
3696   _dbus_message_set_serial (message, 1);
3697   dbus_message_append_args (message,
3698                             DBUS_TYPE_INT32, -0x12345678,
3699                             DBUS_TYPE_STRING, "Test string",
3700                             DBUS_TYPE_DOUBLE, 3.14159,
3701                             DBUS_TYPE_BOOLEAN, TRUE,
3702                             0);
3703   _dbus_verbose_bytes_of_string (&message->header, 0,
3704                                  _dbus_string_get_length (&message->header));
3705   _dbus_verbose_bytes_of_string (&message->body, 0,
3706                                  _dbus_string_get_length (&message->body));
3707
3708   verify_test_message (message);
3709
3710   copy = dbus_message_copy (message);
3711   
3712   _dbus_assert (message->client_serial == copy->client_serial);
3713   _dbus_assert (message->reply_serial == copy->reply_serial);
3714   _dbus_assert (message->header_padding == copy->header_padding);
3715   
3716   _dbus_assert (_dbus_string_get_length (&message->header) ==
3717                 _dbus_string_get_length (&copy->header));
3718
3719   _dbus_assert (_dbus_string_get_length (&message->body) ==
3720                 _dbus_string_get_length (&copy->body));
3721
3722   verify_test_message (copy);
3723
3724   name1 = dbus_message_get_name (message);
3725   name2 = dbus_message_get_name (copy);
3726
3727   _dbus_assert (strcmp (name1, name2) == 0);
3728   
3729   dbus_message_unref (message);
3730   dbus_message_unref (copy);
3731   
3732   message = dbus_message_new ("org.freedesktop.DBus.Test", "testMessage");
3733   _dbus_message_set_serial (message, 1);
3734   dbus_message_set_reply_serial (message, 0x12345678);
3735
3736   dbus_message_append_string (message, "Test string");
3737   dbus_message_append_int32 (message, -0x12345678);
3738   dbus_message_append_uint32 (message, 0xedd1e);
3739   dbus_message_append_double (message, 3.14159);
3740
3741   message_iter_test (message);
3742
3743   /* Message loader test */
3744   _dbus_message_lock (message);
3745   loader = _dbus_message_loader_new ();
3746
3747   /* Write the header data one byte at a time */
3748   _dbus_string_get_const_data (&message->header, &data);
3749   for (i = 0; i < _dbus_string_get_length (&message->header); i++)
3750     {
3751       DBusString *buffer;
3752
3753       _dbus_message_loader_get_buffer (loader, &buffer);
3754       _dbus_string_append_byte (buffer, data[i]);
3755       _dbus_message_loader_return_buffer (loader, buffer, 1);
3756     }
3757
3758   /* Write the body data one byte at a time */
3759   _dbus_string_get_const_data (&message->body, &data);
3760   for (i = 0; i < _dbus_string_get_length (&message->body); i++)
3761     {
3762       DBusString *buffer;
3763
3764       _dbus_message_loader_get_buffer (loader, &buffer);
3765       _dbus_string_append_byte (buffer, data[i]);
3766       _dbus_message_loader_return_buffer (loader, buffer, 1);
3767     }
3768
3769   dbus_message_unref (message);
3770
3771   /* Now pop back the message */
3772   if (!_dbus_message_loader_queue_messages (loader))
3773     _dbus_assert_not_reached ("no memory to queue messages");
3774   
3775   if (_dbus_message_loader_get_is_corrupted (loader))
3776     _dbus_assert_not_reached ("message loader corrupted");
3777   
3778   message = _dbus_message_loader_pop_message (loader);
3779   if (!message)
3780     _dbus_assert_not_reached ("received a NULL message");
3781
3782   if (dbus_message_get_reply_serial (message) != 0x12345678)
3783     _dbus_assert_not_reached ("reply serial fields differ");
3784   
3785   message_iter_test (message);
3786   
3787   dbus_message_unref (message);
3788   _dbus_message_loader_unref (loader);
3789
3790   /* Now load every message in test_data_dir if we have one */
3791   if (test_data_dir == NULL)
3792     return TRUE;
3793
3794   return dbus_internal_do_not_use_foreach_message_file (test_data_dir,
3795                                                         (DBusForeachMessageFileFunc)
3796                                                         dbus_internal_do_not_use_try_message_file,
3797                                                         NULL);
3798 }
3799
3800 #endif /* DBUS_BUILD_TESTS */