Bug 17803 - Fix both test case and validation logic
[platform/upstream/dbus.git] / dbus / dbus-marshal-validate.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-marshal-validate.c Validation routines for marshaled data
3  *
4  * Copyright (C) 2005 Red Hat, Inc.
5  *
6  * Licensed under the Academic Free License version 2.1
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *
22  */
23
24 #include "dbus-internals.h"
25 #include "dbus-marshal-validate.h"
26 #include "dbus-marshal-recursive.h"
27 #include "dbus-marshal-basic.h"
28 #include "dbus-signature.h"
29 #include "dbus-string.h"
30
31 /**
32  * @addtogroup DBusMarshal
33  *
34  * @{
35  */
36
37 /**
38  * Verifies that the range of type_str from type_pos to type_end is a
39  * valid signature.  If this function returns #TRUE, it will be safe
40  * to iterate over the signature with a types-only #DBusTypeReader.
41  * The range passed in should NOT include the terminating
42  * nul/DBUS_TYPE_INVALID.
43  *
44  * @param type_str the string
45  * @param type_pos where the typecodes start
46  * @param len length of typecodes
47  * @returns #DBUS_VALID if valid, reason why invalid otherwise
48  */
49 DBusValidity
50 _dbus_validate_signature_with_reason (const DBusString *type_str,
51                                       int               type_pos,
52                                       int               len)
53 {
54   const unsigned char *p;
55   const unsigned char *end;
56   int last;
57   int struct_depth;
58   int array_depth;
59   int dict_entry_depth;
60   DBusValidity result;
61
62   int element_count;
63   DBusList *element_count_stack;
64
65   result = DBUS_VALID;
66   element_count_stack = NULL;
67
68   if (!_dbus_list_append (&element_count_stack, _DBUS_INT_TO_POINTER (0)))
69     {
70       result = DBUS_VALIDITY_UNKNOWN_OOM_ERROR;
71       goto out;
72     }
73
74   _dbus_assert (type_str != NULL);
75   _dbus_assert (type_pos < _DBUS_INT32_MAX - len);
76   _dbus_assert (len >= 0);
77   _dbus_assert (type_pos >= 0);
78
79   if (len > DBUS_MAXIMUM_SIGNATURE_LENGTH)
80     {
81       result = DBUS_INVALID_SIGNATURE_TOO_LONG;
82       goto out;
83     }
84
85   p = _dbus_string_get_const_data_len (type_str, type_pos, 0);
86
87   end = _dbus_string_get_const_data_len (type_str, type_pos + len, 0);
88   struct_depth = 0;
89   array_depth = 0;
90   dict_entry_depth = 0;
91   last = DBUS_TYPE_INVALID;
92
93   while (p != end)
94     {
95       switch (*p)
96         {
97         case DBUS_TYPE_BYTE:
98         case DBUS_TYPE_BOOLEAN:
99         case DBUS_TYPE_INT16:
100         case DBUS_TYPE_UINT16:
101         case DBUS_TYPE_INT32:
102         case DBUS_TYPE_UINT32:
103         case DBUS_TYPE_INT64:
104         case DBUS_TYPE_UINT64:
105         case DBUS_TYPE_DOUBLE:
106         case DBUS_TYPE_STRING:
107         case DBUS_TYPE_OBJECT_PATH:
108         case DBUS_TYPE_SIGNATURE:
109         case DBUS_TYPE_VARIANT:
110           break;
111
112         case DBUS_TYPE_ARRAY:
113           array_depth += 1;
114           if (array_depth > DBUS_MAXIMUM_TYPE_RECURSION_DEPTH)
115             {
116               result = DBUS_INVALID_EXCEEDED_MAXIMUM_ARRAY_RECURSION;
117               goto out;
118             }
119           break;
120
121         case DBUS_STRUCT_BEGIN_CHAR:
122           struct_depth += 1;
123
124           if (struct_depth > DBUS_MAXIMUM_TYPE_RECURSION_DEPTH)
125             {
126               result = DBUS_INVALID_EXCEEDED_MAXIMUM_STRUCT_RECURSION;
127               goto out;
128             }
129           
130           if (!_dbus_list_append (&element_count_stack, 
131                              _DBUS_INT_TO_POINTER (0)))
132             {
133               result = DBUS_VALIDITY_UNKNOWN_OOM_ERROR;
134               goto out;
135             }
136
137           break;
138
139         case DBUS_STRUCT_END_CHAR:
140           if (struct_depth == 0)
141             {
142               result = DBUS_INVALID_STRUCT_ENDED_BUT_NOT_STARTED;
143               goto out;
144             }
145
146           if (last == DBUS_STRUCT_BEGIN_CHAR)
147             {
148               result = DBUS_INVALID_STRUCT_HAS_NO_FIELDS;
149               goto out;
150             }
151
152           _dbus_list_pop_last (&element_count_stack);
153
154           struct_depth -= 1;
155           break;
156
157         case DBUS_DICT_ENTRY_BEGIN_CHAR:
158           if (last != DBUS_TYPE_ARRAY)
159             {
160               result = DBUS_INVALID_DICT_ENTRY_NOT_INSIDE_ARRAY;
161               goto out;
162             }
163             
164           dict_entry_depth += 1;
165
166           if (dict_entry_depth > DBUS_MAXIMUM_TYPE_RECURSION_DEPTH)
167             {
168               result = DBUS_INVALID_EXCEEDED_MAXIMUM_DICT_ENTRY_RECURSION;
169               goto out;
170             }
171
172           if (!_dbus_list_append (&element_count_stack, 
173                              _DBUS_INT_TO_POINTER (0)))
174             {
175               result = DBUS_VALIDITY_UNKNOWN_OOM_ERROR;
176               goto out;
177             }
178
179           break;
180
181         case DBUS_DICT_ENTRY_END_CHAR:
182           if (dict_entry_depth == 0)
183             {
184               result = DBUS_INVALID_DICT_ENTRY_ENDED_BUT_NOT_STARTED;
185               goto out;
186             }
187             
188           dict_entry_depth -= 1;
189
190           element_count = 
191             _DBUS_POINTER_TO_INT (_dbus_list_pop_last (&element_count_stack));
192
193           if (element_count != 2)
194             {
195               if (element_count == 0)
196                 result = DBUS_INVALID_DICT_ENTRY_HAS_NO_FIELDS;
197               else if (element_count == 1)
198                 result = DBUS_INVALID_DICT_ENTRY_HAS_ONLY_ONE_FIELD;
199               else
200                 result = DBUS_INVALID_DICT_ENTRY_HAS_TOO_MANY_FIELDS;
201               
202               goto out;
203             }
204           break;
205           
206         case DBUS_TYPE_STRUCT:     /* doesn't appear in signatures */
207         case DBUS_TYPE_DICT_ENTRY: /* ditto */
208         default:
209           result = DBUS_INVALID_UNKNOWN_TYPECODE;
210           goto out;
211         }
212
213       if (*p != DBUS_TYPE_ARRAY && 
214           *p != DBUS_DICT_ENTRY_BEGIN_CHAR && 
215           *p != DBUS_STRUCT_BEGIN_CHAR) 
216         {
217           element_count = 
218             _DBUS_POINTER_TO_INT (_dbus_list_pop_last (&element_count_stack));
219
220           ++element_count;
221
222           if (!_dbus_list_append (&element_count_stack, 
223                              _DBUS_INT_TO_POINTER (element_count)))
224             {
225               result = DBUS_VALIDITY_UNKNOWN_OOM_ERROR;
226               goto out;
227             }
228         }
229       
230       if (array_depth > 0)
231         {
232           if (*p == DBUS_TYPE_ARRAY && p != end)
233             {
234                const char *p1;
235                p1 = p + 1;
236                if (*p1 == DBUS_STRUCT_END_CHAR ||
237                    *p1 == DBUS_DICT_ENTRY_END_CHAR)
238                  {
239                    result = DBUS_INVALID_MISSING_ARRAY_ELEMENT_TYPE;
240                    goto out;
241                  }
242             }
243           else
244             {
245               array_depth = 0;
246             }
247         }
248
249       if (last == DBUS_DICT_ENTRY_BEGIN_CHAR)
250         {
251           if (!(_dbus_type_is_valid (*p) && dbus_type_is_basic (*p)))
252             {
253               result = DBUS_INVALID_DICT_KEY_MUST_BE_BASIC_TYPE;
254               goto out;
255             }
256         }
257
258       last = *p;
259       ++p;
260     }
261
262
263   if (array_depth > 0)
264     {
265       result = DBUS_INVALID_MISSING_ARRAY_ELEMENT_TYPE;
266       goto out;
267     }
268     
269   if (struct_depth > 0)
270     {
271        result = DBUS_INVALID_STRUCT_STARTED_BUT_NOT_ENDED;
272        goto out;
273     }
274     
275   if (dict_entry_depth > 0)
276     {
277       result =  DBUS_INVALID_DICT_ENTRY_STARTED_BUT_NOT_ENDED;
278       goto out;
279     }
280     
281   _dbus_assert (last != DBUS_TYPE_ARRAY);
282   _dbus_assert (last != DBUS_STRUCT_BEGIN_CHAR);
283   _dbus_assert (last != DBUS_DICT_ENTRY_BEGIN_CHAR);
284
285   result = DBUS_VALID;
286
287 out:
288   _dbus_list_clear (&element_count_stack);
289   return result;
290 }
291
292 static DBusValidity
293 validate_body_helper (DBusTypeReader       *reader,
294                       int                   byte_order,
295                       dbus_bool_t           walk_reader_to_end,
296                       const unsigned char  *p,
297                       const unsigned char  *end,
298                       const unsigned char **new_p)
299 {
300   int current_type;
301
302   while ((current_type = _dbus_type_reader_get_current_type (reader)) != DBUS_TYPE_INVALID)
303     {
304       const unsigned char *a;
305       int alignment;
306
307 #if 0
308       _dbus_verbose ("   validating value of type %s type reader %p type_pos %d p %p end %p %d remain\n",
309                      _dbus_type_to_string (current_type), reader, reader->type_pos, p, end,
310                      (int) (end - p));
311 #endif
312
313       /* Guarantee that p has one byte to look at */
314       if (p == end)
315         return DBUS_INVALID_NOT_ENOUGH_DATA;
316
317       switch (current_type)
318         {
319         case DBUS_TYPE_BYTE:
320           ++p;
321           break;
322           
323         case DBUS_TYPE_BOOLEAN:
324         case DBUS_TYPE_INT16:
325         case DBUS_TYPE_UINT16:
326         case DBUS_TYPE_INT32:
327         case DBUS_TYPE_UINT32:
328         case DBUS_TYPE_INT64:
329         case DBUS_TYPE_UINT64:
330         case DBUS_TYPE_DOUBLE:
331           alignment = _dbus_type_get_alignment (current_type);
332           a = _DBUS_ALIGN_ADDRESS (p, alignment);
333           if (a >= end)
334             return DBUS_INVALID_NOT_ENOUGH_DATA;
335           while (p != a)
336             {
337               if (*p != '\0')
338                 return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL;
339               ++p;
340             }
341           
342           if (current_type == DBUS_TYPE_BOOLEAN)
343             {
344               dbus_uint32_t v = _dbus_unpack_uint32 (byte_order,
345                                                      p);
346               if (!(v == 0 || v == 1))
347                 return DBUS_INVALID_BOOLEAN_NOT_ZERO_OR_ONE;
348             }
349           
350           p += alignment;
351           break;
352
353         case DBUS_TYPE_ARRAY:
354         case DBUS_TYPE_STRING:
355         case DBUS_TYPE_OBJECT_PATH:
356           {
357             dbus_uint32_t claimed_len;
358
359             a = _DBUS_ALIGN_ADDRESS (p, 4);
360             if (a + 4 > end)
361               return DBUS_INVALID_NOT_ENOUGH_DATA;
362             while (p != a)
363               {
364                 if (*p != '\0')
365                   return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL;
366                 ++p;
367               }
368
369             claimed_len = _dbus_unpack_uint32 (byte_order, p);
370             p += 4;
371
372             /* p may now be == end */
373             _dbus_assert (p <= end);
374
375             if (current_type == DBUS_TYPE_ARRAY)
376               {
377                 int array_elem_type = _dbus_type_reader_get_element_type (reader);
378
379                 if (!_dbus_type_is_valid (array_elem_type))
380                   {
381                     return DBUS_INVALID_UNKNOWN_TYPECODE;
382                   }
383
384                 alignment = _dbus_type_get_alignment (array_elem_type);
385
386                 a = _DBUS_ALIGN_ADDRESS (p, alignment);
387
388                 /* a may now be == end */
389                 if (a > end)
390                   return DBUS_INVALID_NOT_ENOUGH_DATA;
391
392                 while (p != a)
393                   {
394                     if (*p != '\0')
395                       return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL;
396                     ++p;
397                   }
398               }
399
400             if (claimed_len > (unsigned long) (end - p))
401               return DBUS_INVALID_LENGTH_OUT_OF_BOUNDS;
402
403             if (current_type == DBUS_TYPE_OBJECT_PATH)
404               {
405                 DBusString str;
406                 _dbus_string_init_const_len (&str, p, claimed_len);
407                 if (!_dbus_validate_path (&str, 0,
408                                           _dbus_string_get_length (&str)))
409                   return DBUS_INVALID_BAD_PATH;
410
411                 p += claimed_len;
412               }
413             else if (current_type == DBUS_TYPE_STRING)
414               {
415                 DBusString str;
416                 _dbus_string_init_const_len (&str, p, claimed_len);
417                 if (!_dbus_string_validate_utf8 (&str, 0,
418                                                  _dbus_string_get_length (&str)))
419                   return DBUS_INVALID_BAD_UTF8_IN_STRING;
420
421                 p += claimed_len;
422               }
423             else if (current_type == DBUS_TYPE_ARRAY && claimed_len > 0)
424               {
425                 DBusTypeReader sub;
426                 DBusValidity validity;
427                 const unsigned char *array_end;
428                 int array_elem_type;
429
430                 if (claimed_len > DBUS_MAXIMUM_ARRAY_LENGTH)
431                   return DBUS_INVALID_ARRAY_LENGTH_EXCEEDS_MAXIMUM;
432                 
433                 /* Remember that the reader is types only, so we can't
434                  * use it to iterate over elements. It stays the same
435                  * for all elements.
436                  */
437                 _dbus_type_reader_recurse (reader, &sub);
438
439                 array_end = p + claimed_len;
440
441                 array_elem_type = _dbus_type_reader_get_element_type (reader);
442
443                 /* avoid recursive call to validate_body_helper if this is an array
444                  * of fixed-size elements
445                  */ 
446                 if (dbus_type_is_fixed (array_elem_type))
447                   {
448                     /* bools need to be handled differently, because they can
449                      * have an invalid value
450                      */
451                     if (array_elem_type == DBUS_TYPE_BOOLEAN)
452                       {
453                         dbus_uint32_t v;
454                         alignment = _dbus_type_get_alignment (array_elem_type);
455
456                         while (p < array_end)
457                           {
458                             v = _dbus_unpack_uint32 (byte_order, p);
459
460                             if (!(v == 0 || v == 1))
461                               return DBUS_INVALID_BOOLEAN_NOT_ZERO_OR_ONE;
462
463                             p += alignment;
464                           }
465                       }
466
467                     else
468                       {
469                         p = array_end;
470                       }
471                   }
472
473                 else
474                   {
475                     while (p < array_end)
476                       {
477                         validity = validate_body_helper (&sub, byte_order, FALSE, p, end, &p);
478                         if (validity != DBUS_VALID)
479                           return validity;
480                       }
481                   }
482
483                 if (p != array_end)
484                   return DBUS_INVALID_ARRAY_LENGTH_INCORRECT;
485               }
486
487             /* check nul termination */
488             if (current_type != DBUS_TYPE_ARRAY)
489               {
490                 if (p == end)
491                   return DBUS_INVALID_NOT_ENOUGH_DATA;
492
493                 if (*p != '\0')
494                   return DBUS_INVALID_STRING_MISSING_NUL;
495                 ++p;
496               }
497           }
498           break;
499
500         case DBUS_TYPE_SIGNATURE:
501           {
502             dbus_uint32_t claimed_len;
503             DBusString str;
504             DBusValidity validity;
505
506             claimed_len = *p;
507             ++p;
508
509             /* 1 is for nul termination */
510             if (claimed_len + 1 > (unsigned long) (end - p))
511               return DBUS_INVALID_SIGNATURE_LENGTH_OUT_OF_BOUNDS;
512
513             _dbus_string_init_const_len (&str, p, claimed_len);
514             validity =
515               _dbus_validate_signature_with_reason (&str, 0,
516                                                     _dbus_string_get_length (&str));
517
518             if (validity != DBUS_VALID)
519               return validity;
520
521             p += claimed_len;
522
523             _dbus_assert (p < end);
524             if (*p != DBUS_TYPE_INVALID)
525               return DBUS_INVALID_SIGNATURE_MISSING_NUL;
526
527             ++p;
528
529             _dbus_verbose ("p = %p end = %p claimed_len %u\n", p, end, claimed_len);
530           }
531           break;
532
533         case DBUS_TYPE_VARIANT:
534           {
535             /* 1 byte sig len, sig typecodes, align to
536              * contained-type-boundary, values.
537              */
538
539             /* In addition to normal signature validation, we need to be sure
540              * the signature contains only a single (possibly container) type.
541              */
542             dbus_uint32_t claimed_len;
543             DBusString sig;
544             DBusTypeReader sub;
545             DBusValidity validity;
546             int contained_alignment;
547             int contained_type;
548             DBusValidity reason;
549
550             claimed_len = *p;
551             ++p;
552
553             /* + 1 for nul */
554             if (claimed_len + 1 > (unsigned long) (end - p))
555               return DBUS_INVALID_VARIANT_SIGNATURE_LENGTH_OUT_OF_BOUNDS;
556
557             _dbus_string_init_const_len (&sig, p, claimed_len);
558             reason = _dbus_validate_signature_with_reason (&sig, 0,
559                                            _dbus_string_get_length (&sig));
560             if (!(reason == DBUS_VALID))
561               {
562                 if (reason == DBUS_VALIDITY_UNKNOWN_OOM_ERROR)
563                   return reason;
564                 else 
565                   return DBUS_INVALID_VARIANT_SIGNATURE_BAD;
566               }
567
568             p += claimed_len;
569             
570             if (*p != DBUS_TYPE_INVALID)
571               return DBUS_INVALID_VARIANT_SIGNATURE_MISSING_NUL;
572             ++p;
573
574             contained_type = _dbus_first_type_in_signature (&sig, 0);
575             if (contained_type == DBUS_TYPE_INVALID)
576               return DBUS_INVALID_VARIANT_SIGNATURE_EMPTY;
577             
578             contained_alignment = _dbus_type_get_alignment (contained_type);
579             
580             a = _DBUS_ALIGN_ADDRESS (p, contained_alignment);
581             if (a > end)
582               return DBUS_INVALID_NOT_ENOUGH_DATA;
583             while (p != a)
584               {
585                 if (*p != '\0')
586                   return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL;
587                 ++p;
588               }
589
590             _dbus_type_reader_init_types_only (&sub, &sig, 0);
591
592             _dbus_assert (_dbus_type_reader_get_current_type (&sub) != DBUS_TYPE_INVALID);
593
594             validity = validate_body_helper (&sub, byte_order, FALSE, p, end, &p);
595             if (validity != DBUS_VALID)
596               return validity;
597
598             if (_dbus_type_reader_next (&sub))
599               return DBUS_INVALID_VARIANT_SIGNATURE_SPECIFIES_MULTIPLE_VALUES;
600
601             _dbus_assert (_dbus_type_reader_get_current_type (&sub) == DBUS_TYPE_INVALID);
602           }
603           break;
604
605         case DBUS_TYPE_DICT_ENTRY:
606         case DBUS_TYPE_STRUCT:
607           {
608             DBusTypeReader sub;
609             DBusValidity validity;
610
611             a = _DBUS_ALIGN_ADDRESS (p, 8);
612             if (a > end)
613               return DBUS_INVALID_NOT_ENOUGH_DATA;
614             while (p != a)
615               {
616                 if (*p != '\0')
617                   return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL;
618                 ++p;
619               }
620
621             _dbus_type_reader_recurse (reader, &sub);
622
623             validity = validate_body_helper (&sub, byte_order, TRUE, p, end, &p);
624             if (validity != DBUS_VALID)
625               return validity;
626           }
627           break;
628
629         default:
630           _dbus_assert_not_reached ("invalid typecode in supposedly-validated signature");
631           break;
632         }
633
634 #if 0
635       _dbus_verbose ("   validated value of type %s type reader %p type_pos %d p %p end %p %d remain\n",
636                      _dbus_type_to_string (current_type), reader, reader->type_pos, p, end,
637                      (int) (end - p));
638 #endif
639
640       if (p > end)
641         {
642           _dbus_verbose ("not enough data!!! p = %p end = %p end-p = %d\n",
643                          p, end, (int) (end - p));
644           return DBUS_INVALID_NOT_ENOUGH_DATA;
645         }
646
647       if (walk_reader_to_end)
648         _dbus_type_reader_next (reader);
649       else
650         break;
651     }
652
653   if (new_p)
654     *new_p = p;
655
656   return DBUS_VALID;
657 }
658
659 /**
660  * Verifies that the range of value_str from value_pos to value_end is
661  * a legitimate value of type expected_signature.  If this function
662  * returns #TRUE, it will be safe to iterate over the values with
663  * #DBusTypeReader. The signature is assumed to be already valid.
664  *
665  * If bytes_remaining is not #NULL, then leftover bytes will be stored
666  * there and #DBUS_VALID returned. If it is #NULL, then
667  * #DBUS_INVALID_TOO_MUCH_DATA will be returned if bytes are left
668  * over.
669  *
670  * @param expected_signature the expected types in the value_str
671  * @param expected_signature_start where in expected_signature is the signature
672  * @param byte_order the byte order
673  * @param bytes_remaining place to store leftover bytes
674  * @param value_str the string containing the body
675  * @param value_pos where the values start
676  * @param len length of values after value_pos
677  * @returns #DBUS_VALID if valid, reason why invalid otherwise
678  */
679 DBusValidity
680 _dbus_validate_body_with_reason (const DBusString *expected_signature,
681                                  int               expected_signature_start,
682                                  int               byte_order,
683                                  int              *bytes_remaining,
684                                  const DBusString *value_str,
685                                  int               value_pos,
686                                  int               len)
687 {
688   DBusTypeReader reader;
689   const unsigned char *p;
690   const unsigned char *end;
691   DBusValidity validity;
692
693   _dbus_assert (len >= 0);
694   _dbus_assert (value_pos >= 0);
695   _dbus_assert (value_pos <= _dbus_string_get_length (value_str) - len);
696
697   _dbus_verbose ("validating body from pos %d len %d sig '%s'\n",
698                  value_pos, len, _dbus_string_get_const_data_len (expected_signature,
699                                                                   expected_signature_start,
700                                                                   0));
701
702   _dbus_type_reader_init_types_only (&reader,
703                                      expected_signature, expected_signature_start);
704
705   p = _dbus_string_get_const_data_len (value_str, value_pos, len);
706   end = p + len;
707
708   validity = validate_body_helper (&reader, byte_order, TRUE, p, end, &p);
709   if (validity != DBUS_VALID)
710     return validity;
711   
712   if (bytes_remaining)
713     {
714       *bytes_remaining = end - p;
715       return DBUS_VALID;
716     }
717   else if (p < end)
718     return DBUS_INVALID_TOO_MUCH_DATA;
719   else
720     {
721       _dbus_assert (p == end);
722       return DBUS_VALID;
723     }
724 }
725
726 /**
727  * Determine wether the given character is valid as the first character
728  * in a name.
729  */
730 #define VALID_INITIAL_NAME_CHARACTER(c)         \
731   ( ((c) >= 'A' && (c) <= 'Z') ||               \
732     ((c) >= 'a' && (c) <= 'z') ||               \
733     ((c) == '_') )
734
735 /**
736  * Determine wether the given character is valid as a second or later
737  * character in a name
738  */
739 #define VALID_NAME_CHARACTER(c)                 \
740   ( ((c) >= '0' && (c) <= '9') ||               \
741     ((c) >= 'A' && (c) <= 'Z') ||               \
742     ((c) >= 'a' && (c) <= 'z') ||               \
743     ((c) == '_') )
744
745 /**
746  * Checks that the given range of the string is a valid object path
747  * name in the D-Bus protocol. Part of the validation ensures that
748  * the object path contains only ASCII.
749  *
750  * @todo this is inconsistent with most of DBusString in that
751  * it allows a start,len range that extends past the string end.
752  *
753  * @todo change spec to disallow more things, such as spaces in the
754  * path name
755  *
756  * @param str the string
757  * @param start first byte index to check
758  * @param len number of bytes to check
759  * @returns #TRUE if the byte range exists and is a valid name
760  */
761 dbus_bool_t
762 _dbus_validate_path (const DBusString  *str,
763                      int                start,
764                      int                len)
765 {
766   const unsigned char *s;
767   const unsigned char *end;
768   const unsigned char *last_slash;
769
770   _dbus_assert (start >= 0);
771   _dbus_assert (len >= 0);
772   _dbus_assert (start <= _dbus_string_get_length (str));
773   
774   if (len > _dbus_string_get_length (str) - start)
775     return FALSE;
776
777   if (len == 0)
778     return FALSE;
779
780   s = _dbus_string_get_const_data (str) + start;
781   end = s + len;
782
783   if (*s != '/')
784     return FALSE;
785   last_slash = s;
786   ++s;
787
788   while (s != end)
789     {
790       if (*s == '/')
791         {
792           if ((s - last_slash) < 2)
793             return FALSE; /* no empty path components allowed */
794
795           last_slash = s;
796         }
797       else
798         {
799           if (_DBUS_UNLIKELY (!VALID_NAME_CHARACTER (*s)))
800             return FALSE;
801         }
802
803       ++s;
804     }
805
806   if ((end - last_slash) < 2 &&
807       len > 1)
808     return FALSE; /* trailing slash not allowed unless the string is "/" */
809
810   return TRUE;
811 }
812
813 /**
814  * Checks that the given range of the string is a valid interface name
815  * in the D-Bus protocol. This includes a length restriction and an
816  * ASCII subset, see the specification.
817  *
818  * @todo this is inconsistent with most of DBusString in that
819  * it allows a start,len range that extends past the string end.
820  *
821  * @param str the string
822  * @param start first byte index to check
823  * @param len number of bytes to check
824  * @returns #TRUE if the byte range exists and is a valid name
825  */
826 dbus_bool_t
827 _dbus_validate_interface (const DBusString  *str,
828                           int                start,
829                           int                len)
830 {
831   const unsigned char *s;
832   const unsigned char *end;
833   const unsigned char *iface;
834   const unsigned char *last_dot;
835
836   _dbus_assert (start >= 0);
837   _dbus_assert (len >= 0);
838   _dbus_assert (start <= _dbus_string_get_length (str));
839
840   if (len > _dbus_string_get_length (str) - start)
841     return FALSE;
842
843   if (len > DBUS_MAXIMUM_NAME_LENGTH)
844     return FALSE;
845
846   if (len == 0)
847     return FALSE;
848
849   last_dot = NULL;
850   iface = _dbus_string_get_const_data (str) + start;
851   end = iface + len;
852   s = iface;
853
854   /* check special cases of first char so it doesn't have to be done
855    * in the loop. Note we know len > 0
856    */
857   if (_DBUS_UNLIKELY (*s == '.')) /* disallow starting with a . */
858     return FALSE;
859   else if (_DBUS_UNLIKELY (!VALID_INITIAL_NAME_CHARACTER (*s)))
860     return FALSE;
861   else
862     ++s;
863
864   while (s != end)
865     {
866       if (*s == '.')
867         {
868           if (_DBUS_UNLIKELY ((s + 1) == end))
869             return FALSE;
870           else if (_DBUS_UNLIKELY (!VALID_INITIAL_NAME_CHARACTER (*(s + 1))))
871             return FALSE;
872           last_dot = s;
873           ++s; /* we just validated the next char, so skip two */
874         }
875       else if (_DBUS_UNLIKELY (!VALID_NAME_CHARACTER (*s)))
876         {
877           return FALSE;
878         }
879
880       ++s;
881     }
882
883   if (_DBUS_UNLIKELY (last_dot == NULL))
884     return FALSE;
885
886   return TRUE;
887 }
888
889 /**
890  * Checks that the given range of the string is a valid member name
891  * in the D-Bus protocol. This includes a length restriction, etc.,
892  * see the specification.
893  *
894  * @todo this is inconsistent with most of DBusString in that
895  * it allows a start,len range that extends past the string end.
896  *
897  * @param str the string
898  * @param start first byte index to check
899  * @param len number of bytes to check
900  * @returns #TRUE if the byte range exists and is a valid name
901  */
902 dbus_bool_t
903 _dbus_validate_member (const DBusString  *str,
904                        int                start,
905                        int                len)
906 {
907   const unsigned char *s;
908   const unsigned char *end;
909   const unsigned char *member;
910
911   _dbus_assert (start >= 0);
912   _dbus_assert (len >= 0);
913   _dbus_assert (start <= _dbus_string_get_length (str));
914
915   if (len > _dbus_string_get_length (str) - start)
916     return FALSE;
917
918   if (len > DBUS_MAXIMUM_NAME_LENGTH)
919     return FALSE;
920
921   if (len == 0)
922     return FALSE;
923
924   member = _dbus_string_get_const_data (str) + start;
925   end = member + len;
926   s = member;
927
928   /* check special cases of first char so it doesn't have to be done
929    * in the loop. Note we know len > 0
930    */
931
932   if (_DBUS_UNLIKELY (!VALID_INITIAL_NAME_CHARACTER (*s)))
933     return FALSE;
934   else
935     ++s;
936
937   while (s != end)
938     {
939       if (_DBUS_UNLIKELY (!VALID_NAME_CHARACTER (*s)))
940         {
941           return FALSE;
942         }
943
944       ++s;
945     }
946
947   return TRUE;
948 }
949
950 /**
951  * Checks that the given range of the string is a valid error name
952  * in the D-Bus protocol. This includes a length restriction, etc.,
953  * see the specification.
954  *
955  * @todo this is inconsistent with most of DBusString in that
956  * it allows a start,len range that extends past the string end.
957  *
958  * @param str the string
959  * @param start first byte index to check
960  * @param len number of bytes to check
961  * @returns #TRUE if the byte range exists and is a valid name
962  */
963 dbus_bool_t
964 _dbus_validate_error_name (const DBusString  *str,
965                            int                start,
966                            int                len)
967 {
968   /* Same restrictions as interface name at the moment */
969   return _dbus_validate_interface (str, start, len);
970 }
971
972 /**
973  * Determine wether the given character is valid as the first character
974  * in a bus name.
975  */
976 #define VALID_INITIAL_BUS_NAME_CHARACTER(c)         \
977   ( ((c) >= 'A' && (c) <= 'Z') ||               \
978     ((c) >= 'a' && (c) <= 'z') ||               \
979     ((c) == '_') || ((c) == '-'))
980
981 /**
982  * Determine wether the given character is valid as a second or later
983  * character in a bus name
984  */
985 #define VALID_BUS_NAME_CHARACTER(c)                 \
986   ( ((c) >= '0' && (c) <= '9') ||               \
987     ((c) >= 'A' && (c) <= 'Z') ||               \
988     ((c) >= 'a' && (c) <= 'z') ||               \
989     ((c) == '_') || ((c) == '-'))
990
991 /**
992  * Checks that the given range of the string is a valid bus name in
993  * the D-Bus protocol. This includes a length restriction, etc., see
994  * the specification.
995  *
996  * @todo this is inconsistent with most of DBusString in that
997  * it allows a start,len range that extends past the string end.
998  *
999  * @param str the string
1000  * @param start first byte index to check
1001  * @param len number of bytes to check
1002  * @returns #TRUE if the byte range exists and is a valid name
1003  */
1004 dbus_bool_t
1005 _dbus_validate_bus_name (const DBusString  *str,
1006                          int                start,
1007                          int                len)
1008 {
1009   const unsigned char *s;
1010   const unsigned char *end;
1011   const unsigned char *iface;
1012   const unsigned char *last_dot;
1013
1014   _dbus_assert (start >= 0);
1015   _dbus_assert (len >= 0);
1016   _dbus_assert (start <= _dbus_string_get_length (str));
1017
1018   if (len > _dbus_string_get_length (str) - start)
1019     return FALSE;
1020
1021   if (len > DBUS_MAXIMUM_NAME_LENGTH)
1022     return FALSE;
1023
1024   if (len == 0)
1025     return FALSE;
1026
1027   last_dot = NULL;
1028   iface = _dbus_string_get_const_data (str) + start;
1029   end = iface + len;
1030   s = iface;
1031
1032   /* check special cases of first char so it doesn't have to be done
1033    * in the loop. Note we know len > 0
1034    */
1035   if (*s == ':')
1036   {
1037     /* unique name */
1038     ++s;
1039     while (s != end)
1040       {
1041         if (*s == '.')
1042           {
1043             if (_DBUS_UNLIKELY ((s + 1) == end))
1044               return FALSE;
1045             if (_DBUS_UNLIKELY (!VALID_BUS_NAME_CHARACTER (*(s + 1))))
1046               return FALSE;
1047             ++s; /* we just validated the next char, so skip two */
1048           }
1049         else if (_DBUS_UNLIKELY (!VALID_BUS_NAME_CHARACTER (*s)))
1050           {
1051             return FALSE;
1052           }
1053
1054         ++s;
1055       }
1056
1057     return TRUE;
1058   }
1059   else if (_DBUS_UNLIKELY (*s == '.')) /* disallow starting with a . */
1060     return FALSE;
1061   else if (_DBUS_UNLIKELY (!VALID_INITIAL_BUS_NAME_CHARACTER (*s)))
1062     return FALSE;
1063   else
1064     ++s;
1065
1066   while (s != end)
1067     {
1068       if (*s == '.')
1069         {
1070           if (_DBUS_UNLIKELY ((s + 1) == end))
1071             return FALSE;
1072           else if (_DBUS_UNLIKELY (!VALID_INITIAL_BUS_NAME_CHARACTER (*(s + 1))))
1073             return FALSE;
1074           last_dot = s;
1075           ++s; /* we just validated the next char, so skip two */
1076         }
1077       else if (_DBUS_UNLIKELY (!VALID_BUS_NAME_CHARACTER (*s)))
1078         {
1079           return FALSE;
1080         }
1081
1082       ++s;
1083     }
1084
1085   if (_DBUS_UNLIKELY (last_dot == NULL))
1086     return FALSE;
1087
1088   return TRUE;
1089 }
1090
1091 /**
1092  * Checks that the given range of the string is a valid message type
1093  * signature in the D-Bus protocol.
1094  *
1095  * @todo this is inconsistent with most of DBusString in that
1096  * it allows a start,len range that extends past the string end.
1097  *
1098  * @param str the string
1099  * @param start first byte index to check
1100  * @param len number of bytes to check
1101  * @returns #TRUE if the byte range exists and is a valid signature
1102  */
1103 dbus_bool_t
1104 _dbus_validate_signature (const DBusString  *str,
1105                           int                start,
1106                           int                len)
1107 {
1108   _dbus_assert (start >= 0);
1109   _dbus_assert (start <= _dbus_string_get_length (str));
1110   _dbus_assert (len >= 0);
1111
1112   if (len > _dbus_string_get_length (str) - start)
1113     return FALSE;
1114
1115   return _dbus_validate_signature_with_reason (str, start, len) == DBUS_VALID;
1116 }
1117
1118 /** define _dbus_check_is_valid_path() */
1119 DEFINE_DBUS_NAME_CHECK(path)
1120 /** define _dbus_check_is_valid_interface() */
1121 DEFINE_DBUS_NAME_CHECK(interface)
1122 /** define _dbus_check_is_valid_member() */
1123 DEFINE_DBUS_NAME_CHECK(member)
1124 /** define _dbus_check_is_valid_error_name() */
1125 DEFINE_DBUS_NAME_CHECK(error_name)
1126 /** define _dbus_check_is_valid_bus_name() */
1127 DEFINE_DBUS_NAME_CHECK(bus_name)
1128 /** define _dbus_check_is_valid_signature() */
1129 DEFINE_DBUS_NAME_CHECK(signature)
1130
1131 /** @} */
1132
1133 /* tests in dbus-marshal-validate-util.c */