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