2003-02-26 Havoc Pennington <hp@redhat.com>
[platform/upstream/dbus.git] / dbus / dbus-string.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-string.c String utility class (internal to D-BUS implementation)
3  * 
4  * Copyright (C) 2002, 2003 Red Hat, Inc.
5  *
6  * Licensed under the Academic Free License version 1.2
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-string.h"
26 /* we allow a system header here, for speed/convenience */
27 #include <string.h>
28
29 /**
30  * @defgroup DBusString string class
31  * @ingroup  DBusInternals
32  * @brief DBusString data structure
33  *
34  * Types and functions related to DBusString. DBusString is intended
35  * to be a string class that makes it hard to mess up security issues
36  * (and just in general harder to write buggy code).  It should be
37  * used (or extended and then used) rather than the libc stuff in
38  * string.h.  The string class is a bit inconvenient at spots because
39  * it handles out-of-memory failures and tries to be extra-robust.
40  * 
41  * A DBusString has a maximum length set at initialization time; this
42  * can be used to ensure that a buffer doesn't get too big.  The
43  * _dbus_string_lengthen() method checks for overflow, and for max
44  * length being exceeded.
45  * 
46  * Try to avoid conversion to a plain C string, i.e. add methods on
47  * the string object instead, only convert to C string when passing
48  * things out to the public API. In particular, no sprintf, strcpy,
49  * strcat, any of that should be used. The GString feature of
50  * accepting negative numbers for "length of string" is also absent,
51  * because it could keep us from detecting bogus huge lengths. i.e. if
52  * we passed in some bogus huge length it would be taken to mean
53  * "current length of string" instead of "broken crack"
54  */
55
56 /**
57  * @defgroup DBusStringInternals DBusString implementation details
58  * @ingroup  DBusInternals
59  * @brief DBusString implementation details
60  *
61  * The guts of DBusString.
62  *
63  * @{
64  */
65
66 /**
67  * @brief Internals of DBusString.
68  * 
69  * DBusString internals. DBusString is an opaque objects, it must be
70  * used via accessor functions.
71  */
72 typedef struct
73 {
74   unsigned char *str;            /**< String data, plus nul termination */
75   int            len;            /**< Length without nul */
76   int            allocated;      /**< Allocated size of data */
77   int            max_length;     /**< Max length of this string, without nul byte */
78   unsigned int   constant : 1;   /**< String data is not owned by DBusString */
79   unsigned int   locked : 1;     /**< DBusString has been locked and can't be changed */
80   unsigned int   invalid : 1;    /**< DBusString is invalid (e.g. already freed) */
81   unsigned int   align_offset : 3; /**< str - align_offset is the actual malloc block */
82 } DBusRealString;
83
84 /**
85  * We allocate 1 byte for nul termination, plus 7 bytes for possible
86  * align_offset, so we always need 8 bytes on top of the string's
87  * length to be in the allocated block.
88  */
89 #define ALLOCATION_PADDING 8
90
91 /**
92  * This is the maximum max length (and thus also the maximum length)
93  * of a DBusString
94  */
95 #define MAX_MAX_LENGTH (_DBUS_INT_MAX - ALLOCATION_PADDING)
96
97 /**
98  * Checks a bunch of assertions about a string object
99  *
100  * @param real the DBusRealString
101  */
102 #define DBUS_GENERIC_STRING_PREAMBLE(real) _dbus_assert ((real) != NULL); _dbus_assert (!(real)->invalid); _dbus_assert ((real)->len >= 0); _dbus_assert ((real)->allocated >= 0); _dbus_assert ((real)->max_length >= 0); _dbus_assert ((real)->len <= ((real)->allocated - ALLOCATION_PADDING)); _dbus_assert ((real)->len <= (real)->max_length)
103
104 /**
105  * Checks assertions about a string object that needs to be
106  * modifiable - may not be locked or const. Also declares
107  * the "real" variable pointing to DBusRealString. 
108  * @param str the string
109  */
110 #define DBUS_STRING_PREAMBLE(str) DBusRealString *real = (DBusRealString*) str; \
111   DBUS_GENERIC_STRING_PREAMBLE (real);                                          \
112   _dbus_assert (!(real)->constant);                                             \
113   _dbus_assert (!(real)->locked)
114
115 /**
116  * Checks assertions about a string object that may be locked but
117  * can't be const. i.e. a string object that we can free.  Also
118  * declares the "real" variable pointing to DBusRealString.
119  *
120  * @param str the string
121  */
122 #define DBUS_LOCKED_STRING_PREAMBLE(str) DBusRealString *real = (DBusRealString*) str; \
123   DBUS_GENERIC_STRING_PREAMBLE (real);                                                 \
124   _dbus_assert (!(real)->constant)
125
126 /**
127  * Checks assertions about a string that may be const or locked.  Also
128  * declares the "real" variable pointing to DBusRealString.
129  * @param str the string.
130  */
131 #define DBUS_CONST_STRING_PREAMBLE(str) const DBusRealString *real = (DBusRealString*) str; \
132   DBUS_GENERIC_STRING_PREAMBLE (real)
133
134 /** @} */
135
136 /**
137  * @addtogroup DBusString
138  * @{
139  */
140
141 static void
142 fixup_alignment (DBusRealString *real)
143 {
144   char *aligned;
145   char *real_block;
146   unsigned int old_align_offset;
147
148   /* we have to have extra space in real->allocated for the align offset and nul byte */
149   _dbus_assert (real->len <= real->allocated - ALLOCATION_PADDING);
150   
151   old_align_offset = real->align_offset;
152   real_block = real->str - old_align_offset;
153   
154   aligned = _DBUS_ALIGN_ADDRESS (real_block, 8);
155
156   real->align_offset = aligned - real_block;
157   real->str = aligned;
158   
159   if (old_align_offset != real->align_offset)
160     {
161       /* Here comes the suck */
162       memmove (real_block + real->align_offset,
163                real_block + old_align_offset,
164                real->len + 1);
165     }
166
167   _dbus_assert (real->align_offset < 8);
168   _dbus_assert (_DBUS_ALIGN_ADDRESS (real->str, 8) == real->str);
169 }
170
171 /**
172  * Initializes a string. The maximum length may be _DBUS_INT_MAX for
173  * no maximum. The string starts life with zero length.
174  * The string must eventually be freed with _dbus_string_free().
175  *
176  * @todo the max length feature is useless, because it looks to the
177  * app like out of memory, and the app might try to "recover" - but
178  * recovery in this case is impossible, as we can't ever "get more
179  * memory" - so should delete the max length feature I think. Well, at
180  * least there's a strong caveat that it can only be used when
181  * out-of-memory is a permanent fatal error.
182  *
183  * @todo we could make this init routine not alloc any memory and
184  * return void, would simplify a lot of code, however it might
185  * complexify things elsewhere because _dbus_string_get_data()
186  * etc. could suddenly fail as they'd need to alloc new memory.
187  * 
188  * @param str memory to hold the string
189  * @param max_length the maximum size of the string
190  * @returns #TRUE on success */
191 dbus_bool_t
192 _dbus_string_init (DBusString *str,
193                    int         max_length)
194 {
195   DBusRealString *real;
196   
197   _dbus_assert (str != NULL);
198   _dbus_assert (max_length >= 0);
199
200   _dbus_assert (sizeof (DBusString) == sizeof (DBusRealString));
201   
202   real = (DBusRealString*) str;
203
204   /* It's very important not to touch anything
205    * other than real->str if we're going to fail,
206    * since we also use this function to reset
207    * an existing string, e.g. in _dbus_string_steal_data()
208    */
209   
210   real->str = dbus_malloc (ALLOCATION_PADDING);
211   if (real->str == NULL)
212     return FALSE;  
213   
214   real->allocated = ALLOCATION_PADDING;
215   real->len = 0;
216   real->str[real->len] = '\0';
217   
218   real->max_length = max_length;
219   if (real->max_length > MAX_MAX_LENGTH)
220     real->max_length = MAX_MAX_LENGTH;
221   real->constant = FALSE;
222   real->locked = FALSE;
223   real->invalid = FALSE;
224   real->align_offset = 0;
225   
226   fixup_alignment (real);
227   
228   return TRUE;
229 }
230
231 /**
232  * Initializes a constant string. The value parameter is not copied
233  * (should be static), and the string may never be modified.
234  * It is safe but not necessary to call _dbus_string_free()
235  * on a const string. The string has a length limit of MAXINT - 8.
236  * 
237  * @param str memory to use for the string
238  * @param value a string to be stored in str (not copied!!!)
239  */
240 void
241 _dbus_string_init_const (DBusString *str,
242                          const char *value)
243 {
244   _dbus_assert (value != NULL);
245   
246   _dbus_string_init_const_len (str, value,
247                                strlen (value));
248 }
249
250 /**
251  * Initializes a constant string with a length. The value parameter is
252  * not copied (should be static), and the string may never be
253  * modified.  It is safe but not necessary to call _dbus_string_free()
254  * on a const string.
255  * 
256  * @param str memory to use for the string
257  * @param value a string to be stored in str (not copied!!!)
258  * @param len the length to use
259  */
260 void
261 _dbus_string_init_const_len (DBusString *str,
262                              const char *value,
263                              int         len)
264 {
265   DBusRealString *real;
266   
267   _dbus_assert (str != NULL);
268   _dbus_assert (value != NULL);
269   _dbus_assert (len <= MAX_MAX_LENGTH);
270   _dbus_assert (len >= 0);
271   
272   real = (DBusRealString*) str;
273   
274   real->str = (char*) value;
275   real->len = len;
276   real->allocated = real->len + ALLOCATION_PADDING; /* a lie, just to avoid special-case assertions... */
277   real->max_length = real->len + 1;
278   real->constant = TRUE;
279   real->invalid = FALSE;
280
281   /* We don't require const strings to be 8-byte aligned as the
282    * memory is coming from elsewhere.
283    */
284 }
285
286 /**
287  * Frees a string created by _dbus_string_init().
288  *
289  * @param str memory where the string is stored.
290  */
291 void
292 _dbus_string_free (DBusString *str)
293 {
294   DBusRealString *real = (DBusRealString*) str;
295   DBUS_GENERIC_STRING_PREAMBLE (real);
296   
297   if (real->constant)
298     return;
299   dbus_free (real->str);
300
301   real->invalid = TRUE;
302 }
303
304 /**
305  * Locks a string such that any attempts to change the string will
306  * result in aborting the program. Also, if the string is wasting a
307  * lot of memory (allocation is sufficiently larger than what the
308  * string is really using), _dbus_string_lock() will realloc the
309  * string's data to "compact" it.
310  *
311  * @param str the string to lock.
312  */
313 void
314 _dbus_string_lock (DBusString *str)
315 {  
316   DBUS_LOCKED_STRING_PREAMBLE (str); /* can lock multiple times */
317
318   real->locked = TRUE;
319
320   /* Try to realloc to avoid excess memory usage, since
321    * we know we won't change the string further
322    */
323 #define MAX_WASTE 48
324   if (real->allocated - MAX_WASTE > real->len)
325     {
326       char *new_str;
327       int new_allocated;
328
329       new_allocated = real->len + ALLOCATION_PADDING;
330
331       new_str = dbus_realloc (real->str - real->align_offset,
332                               new_allocated);
333       if (new_str != NULL)
334         {
335           real->str = new_str + real->align_offset;
336           real->allocated = new_allocated;
337           fixup_alignment (real);
338         }
339     }
340 }
341
342 static dbus_bool_t
343 set_length (DBusRealString *real,
344             int             new_length)
345 {
346   /* Note, we are setting the length without nul termination */
347
348   /* exceeding max length is the same as failure to allocate memory */
349   if (new_length > real->max_length)
350     return FALSE;
351   
352   if (new_length > (real->allocated - ALLOCATION_PADDING))
353     {
354       int new_allocated;
355       char *new_str;
356
357       /* at least double our old allocation to avoid O(n), avoiding
358        * overflow
359        */
360       if (real->allocated > (MAX_MAX_LENGTH + ALLOCATION_PADDING) / 2)
361         new_allocated = MAX_MAX_LENGTH + ALLOCATION_PADDING;
362       else
363         new_allocated = real->allocated * 2;
364
365       /* But be sure we always alloc at least space for the new length */
366       new_allocated = MAX (real->allocated, new_length + ALLOCATION_PADDING);
367         
368       new_str = dbus_realloc (real->str - real->align_offset, new_allocated);
369       if (new_str == NULL)
370         return FALSE;
371
372       real->str = new_str + real->align_offset;
373       real->allocated = new_allocated;
374       fixup_alignment (real);
375     }
376
377   real->len = new_length;
378   real->str[real->len] = '\0';
379
380   return TRUE;
381 }
382
383 static dbus_bool_t
384 open_gap (int             len,
385           DBusRealString *dest,
386           int             insert_at)
387 {
388   if (len == 0)
389     return TRUE;
390
391   if (len > dest->max_length - dest->len)
392     return FALSE; /* detected overflow of dest->len + len below */
393   
394   if (!set_length (dest, dest->len + len))
395     return FALSE;
396
397   memmove (dest->str + insert_at + len, 
398            dest->str + insert_at,
399            dest->len - len - insert_at);
400
401   return TRUE;
402 }
403
404 /**
405  * Gets the raw character buffer from the string.  The returned buffer
406  * will be nul-terminated, but note that strings may contain binary
407  * data so there may be extra nul characters prior to the termination.
408  * This function should be little-used, extend DBusString or add
409  * stuff to dbus-sysdeps.c instead. It's an error to use this
410  * function on a const string.
411  *
412  * @param str the string
413  * @param data_return place to store the returned data
414  */
415 void
416 _dbus_string_get_data (DBusString        *str,
417                        char             **data_return)
418 {
419   DBUS_STRING_PREAMBLE (str);
420   _dbus_assert (data_return != NULL);
421   
422   *data_return = real->str;
423 }
424
425 /**
426  * Gets the raw character buffer from a const string.
427  *
428  * @todo should return the const char* instead of using an out param;
429  * the temporary variable encourages a bug where you use const data
430  * after modifying the string and possibly causing a realloc.
431  *
432  * @param str the string
433  * @param data_return location to store returned data
434  */
435 void
436 _dbus_string_get_const_data (const DBusString  *str,
437                              const char       **data_return)
438 {
439   DBUS_CONST_STRING_PREAMBLE (str);
440   _dbus_assert (data_return != NULL);
441   
442   *data_return = real->str;
443 }
444
445 /**
446  * Gets a sub-portion of the raw character buffer from the
447  * string. The "len" field is required simply for error
448  * checking, to be sure you don't try to use more
449  * string than exists. The nul termination of the
450  * returned buffer remains at the end of the entire
451  * string, not at start + len.
452  *
453  * @param str the string
454  * @param data_return location to return the buffer
455  * @param start byte offset to return
456  * @param len length of segment to return
457  */
458 void
459 _dbus_string_get_data_len (DBusString *str,
460                            char      **data_return,
461                            int         start,
462                            int         len)
463 {
464   DBUS_STRING_PREAMBLE (str);
465   _dbus_assert (data_return != NULL);
466   _dbus_assert (start >= 0);
467   _dbus_assert (len >= 0);
468   _dbus_assert (start <= real->len);
469   _dbus_assert (len <= real->len - start);
470   
471   *data_return = real->str + start;
472 }
473
474 /**
475  * const version of _dbus_string_get_data_len().
476  *
477  * @todo should return the const char* instead of using an out param;
478  * the temporary variable encourages a bug where you use const data
479  * after modifying the string and possibly causing a realloc.
480  * 
481  * @param str the string
482  * @param data_return location to return the buffer
483  * @param start byte offset to return
484  * @param len length of segment to return
485  */
486 void
487 _dbus_string_get_const_data_len (const DBusString  *str,
488                                  const char       **data_return,
489                                  int                start,
490                                  int                len)
491 {
492   DBUS_CONST_STRING_PREAMBLE (str);
493   _dbus_assert (data_return != NULL);
494   _dbus_assert (start >= 0);
495   _dbus_assert (len >= 0);
496   _dbus_assert (start <= real->len);
497   _dbus_assert (len <= real->len - start);
498   
499   *data_return = real->str + start;
500 }
501
502 /**
503  * Sets the value of the byte at the given position.
504  *
505  * @param str the string
506  * @param i the position
507  * @param byte the new value
508  */
509 void
510 _dbus_string_set_byte (DBusString    *str,
511                        int            i,
512                        unsigned char  byte)
513 {
514   DBUS_STRING_PREAMBLE (str);
515   _dbus_assert (i < real->len);
516   _dbus_assert (i >= 0);
517   
518   real->str[i] = byte;
519 }
520
521 /**
522  * Gets the byte at the given position.
523  *
524  * @param str the string
525  * @param start the position
526  * @returns the byte at that position
527  */
528 unsigned char
529 _dbus_string_get_byte (const DBusString  *str,
530                        int                start)
531 {
532   DBUS_CONST_STRING_PREAMBLE (str);
533   _dbus_assert (start < real->len);
534   _dbus_assert (start >= 0);
535   
536   return real->str[start];
537 }
538
539 /**
540  * Inserts the given byte at the given position.
541  *
542  * @param str the string
543  * @param i the position
544  * @param byte the value to insert
545  * @returns #TRUE on success
546  */
547 dbus_bool_t
548 _dbus_string_insert_byte (DBusString   *str,
549                           int           i,
550                           unsigned char byte)
551 {
552   DBUS_STRING_PREAMBLE (str);
553   _dbus_assert (i <= real->len);
554   _dbus_assert (i >= 0);
555   
556   if (!open_gap (1, real, i))
557     return FALSE;
558   
559   real->str[i] = byte;
560
561   return TRUE;
562 }
563
564 /**
565  * Like _dbus_string_get_data(), but removes the
566  * gotten data from the original string. The caller
567  * must free the data returned. This function may
568  * fail due to lack of memory, and return #FALSE.
569  *
570  * @param str the string
571  * @param data_return location to return the buffer
572  * @returns #TRUE on success
573  */
574 dbus_bool_t
575 _dbus_string_steal_data (DBusString        *str,
576                          char             **data_return)
577 {
578   DBUS_STRING_PREAMBLE (str);
579   _dbus_assert (data_return != NULL);
580   
581   *data_return = real->str;
582
583   /* reset the string */
584   if (!_dbus_string_init (str, real->max_length))
585     {
586       /* hrm, put it back then */
587       real->str = *data_return;
588       *data_return = NULL;
589       return FALSE;
590     }
591
592   return TRUE;
593 }
594
595 /**
596  * Like _dbus_string_get_data_len(), but removes the gotten data from
597  * the original string. The caller must free the data returned. This
598  * function may fail due to lack of memory, and return #FALSE.
599  * The returned string is nul-terminated and has length len.
600  *
601  * @todo this function is broken because on failure it
602  * may corrupt the source string.
603  * 
604  * @param str the string
605  * @param data_return location to return the buffer
606  * @param start the start of segment to steal
607  * @param len the length of segment to steal
608  * @returns #TRUE on success
609  */
610 dbus_bool_t
611 _dbus_string_steal_data_len (DBusString        *str,
612                              char             **data_return,
613                              int                start,
614                              int                len)
615 {
616   DBusString dest;
617   
618   DBUS_STRING_PREAMBLE (str);
619   _dbus_assert (data_return != NULL);
620   _dbus_assert (start >= 0);
621   _dbus_assert (len >= 0);
622   _dbus_assert (start <= real->len);
623   _dbus_assert (len <= real->len - start);
624
625   if (!_dbus_string_init (&dest, real->max_length))
626     return FALSE;
627
628   if (!_dbus_string_move_len (str, start, len, &dest, 0))
629     {
630       _dbus_string_free (&dest);
631       return FALSE;
632     }
633
634   _dbus_warn ("Broken code in _dbus_string_steal_data_len(), FIXME\n");
635   if (!_dbus_string_steal_data (&dest, data_return))
636     {
637       _dbus_string_free (&dest);
638       return FALSE;
639     }
640
641   _dbus_string_free (&dest);
642   return TRUE;
643 }
644
645 /**
646  * Gets the length of a string (not including nul termination).
647  *
648  * @returns the length.
649  */
650 int
651 _dbus_string_get_length (const DBusString  *str)
652 {
653   DBUS_CONST_STRING_PREAMBLE (str);
654   
655   return real->len;
656 }
657
658 /**
659  * Makes a string longer by the given number of bytes.  Checks whether
660  * adding additional_length to the current length would overflow an
661  * integer, and checks for exceeding a string's max length.
662  * The new bytes are not initialized, other than nul-terminating
663  * the end of the string. The uninitialized bytes may contain
664  * nul bytes or other junk.
665  *
666  * @param str a string
667  * @param additional_length length to add to the string.
668  * @returns #TRUE on success.
669  */
670 dbus_bool_t
671 _dbus_string_lengthen (DBusString *str,
672                        int         additional_length)
673 {
674   DBUS_STRING_PREAMBLE (str);  
675   _dbus_assert (additional_length >= 0);
676
677   if (additional_length > real->max_length - real->len)
678     return FALSE; /* would overflow */
679   
680   return set_length (real,
681                      real->len + additional_length);
682 }
683
684 /**
685  * Makes a string shorter by the given number of bytes.
686  *
687  * @param str a string
688  * @param length_to_remove length to remove from the string.
689  */
690 void
691 _dbus_string_shorten (DBusString *str,
692                       int         length_to_remove)
693 {
694   DBUS_STRING_PREAMBLE (str);
695   _dbus_assert (length_to_remove >= 0);
696   _dbus_assert (length_to_remove <= real->len);
697
698   set_length (real,
699               real->len - length_to_remove);
700 }
701
702 /**
703  * Sets the length of a string. Can be used to truncate or lengthen
704  * the string. If the string is lengthened, the function may fail and
705  * return #FALSE. Newly-added bytes are not initialized, as with
706  * _dbus_string_lengthen().
707  *
708  * @param str a string
709  * @param length new length of the string.
710  * @returns #FALSE on failure.
711  */
712 dbus_bool_t
713 _dbus_string_set_length (DBusString *str,
714                          int         length)
715 {
716   DBUS_STRING_PREAMBLE (str);
717   _dbus_assert (length >= 0);
718
719   return set_length (real, length);
720 }
721
722 /**
723  * Align the length of a string to a specific alignment (typically 4 or 8)
724  * by appending nul bytes to the string.
725  *
726  * @param str a string
727  * @param alignment the alignment
728  * @returns #FALSE if no memory
729  */
730 dbus_bool_t
731 _dbus_string_align_length (DBusString *str,
732                            int         alignment)
733 {
734   unsigned long new_len; /* ulong to avoid _DBUS_ALIGN_VALUE overflow */
735   int delta;
736   DBUS_STRING_PREAMBLE (str);
737   _dbus_assert (alignment >= 1);
738   _dbus_assert (alignment <= 8); /* it has to be a bug if > 8 */
739
740   new_len = _DBUS_ALIGN_VALUE (real->len, alignment);
741   if (new_len > (unsigned long) real->max_length)
742     return FALSE;
743   
744   delta = new_len - real->len;
745   _dbus_assert (delta >= 0);
746
747   if (delta == 0)
748     return TRUE;
749
750   if (!set_length (real, new_len))
751     return FALSE;
752
753   memset (real->str + (new_len - delta),
754           '\0', delta);
755
756   return TRUE;
757 }
758
759 static dbus_bool_t
760 append (DBusRealString *real,
761         const char     *buffer,
762         int             buffer_len)
763 {
764   if (buffer_len == 0)
765     return TRUE;
766
767   if (!_dbus_string_lengthen ((DBusString*)real, buffer_len))
768     return FALSE;
769
770   memcpy (real->str + (real->len - buffer_len),
771           buffer,
772           buffer_len);
773
774   return TRUE;
775 }
776
777 /**
778  * Appends a nul-terminated C-style string to a DBusString.
779  *
780  * @param str the DBusString
781  * @param buffer the nul-terminated characters to append
782  * @returns #FALSE if not enough memory.
783  */
784 dbus_bool_t
785 _dbus_string_append (DBusString *str,
786                      const char *buffer)
787 {
788   unsigned long buffer_len;
789   
790   DBUS_STRING_PREAMBLE (str);
791   _dbus_assert (buffer != NULL);
792   
793   buffer_len = strlen (buffer);
794   if (buffer_len > (unsigned long) real->max_length)
795     return FALSE;
796   
797   return append (real, buffer, buffer_len);
798 }
799
800 /**
801  * Appends block of bytes with the given length to a DBusString.
802  *
803  * @param str the DBusString
804  * @param buffer the bytes to append
805  * @param len the number of bytes to append
806  * @returns #FALSE if not enough memory.
807  */
808 dbus_bool_t
809 _dbus_string_append_len (DBusString *str,
810                          const char *buffer,
811                          int         len)
812 {
813   DBUS_STRING_PREAMBLE (str);
814   _dbus_assert (buffer != NULL);
815   _dbus_assert (len >= 0);
816
817   return append (real, buffer, len);
818 }
819
820 /**
821  * Appends a single byte to the string, returning #FALSE
822  * if not enough memory.
823  *
824  * @param str the string
825  * @param byte the byte to append
826  * @returns #TRUE on success
827  */
828 dbus_bool_t
829 _dbus_string_append_byte (DBusString    *str,
830                           unsigned char  byte)
831 {
832   DBUS_STRING_PREAMBLE (str);
833
834   if (!set_length (real, real->len + 1))
835     return FALSE;
836
837   real->str[real->len-1] = byte;
838
839   return TRUE;
840 }
841
842 /**
843  * Appends a single Unicode character, encoding the character
844  * in UTF-8 format.
845  *
846  * @param str the string
847  * @param ch the Unicode character
848  */
849 dbus_bool_t
850 _dbus_string_append_unichar (DBusString    *str,
851                              dbus_unichar_t ch)
852 {
853   int len;
854   int first;
855   int i;
856   char *out;
857   
858   DBUS_STRING_PREAMBLE (str);
859
860   /* this code is from GLib but is pretty standard I think */
861   
862   len = 0;
863   
864   if (ch < 0x80)
865     {
866       first = 0;
867       len = 1;
868     }
869   else if (ch < 0x800)
870     {
871       first = 0xc0;
872       len = 2;
873     }
874   else if (ch < 0x10000)
875     {
876       first = 0xe0;
877       len = 3;
878     }
879    else if (ch < 0x200000)
880     {
881       first = 0xf0;
882       len = 4;
883     }
884   else if (ch < 0x4000000)
885     {
886       first = 0xf8;
887       len = 5;
888     }
889   else
890     {
891       first = 0xfc;
892       len = 6;
893     }
894
895   if (len > (real->max_length - real->len))
896     return FALSE; /* real->len + len would overflow */
897   
898   if (!set_length (real, real->len + len))
899     return FALSE;
900
901   out = real->str + (real->len - len);
902   
903   for (i = len - 1; i > 0; --i)
904     {
905       out[i] = (ch & 0x3f) | 0x80;
906       ch >>= 6;
907     }
908   out[0] = ch | first;
909
910   return TRUE;
911 }
912
913 static void
914 delete (DBusRealString *real,
915         int             start,
916         int             len)
917 {
918   if (len == 0)
919     return;
920   
921   memmove (real->str + start, real->str + start + len, real->len - (start + len));
922   real->len -= len;
923   real->str[real->len] = '\0';
924 }
925
926 /**
927  * Deletes a segment of a DBusString with length len starting at
928  * start. (Hint: to clear an entire string, setting length to 0
929  * with _dbus_string_set_length() is easier.)
930  *
931  * @param str the DBusString
932  * @param start where to start deleting
933  * @param len the number of bytes to delete
934  */
935 void
936 _dbus_string_delete (DBusString       *str,
937                      int               start,
938                      int               len)
939 {
940   DBUS_STRING_PREAMBLE (str);
941   _dbus_assert (start >= 0);
942   _dbus_assert (len >= 0);
943   _dbus_assert (start <= real->len);
944   _dbus_assert (len <= real->len - start);
945   
946   delete (real, start, len);
947 }
948
949 static dbus_bool_t
950 copy (DBusRealString *source,
951       int             start,
952       int             len,
953       DBusRealString *dest,
954       int             insert_at)
955 {
956   if (len == 0)
957     return TRUE;
958
959   if (!open_gap (len, dest, insert_at))
960     return FALSE;
961   
962   memcpy (dest->str + insert_at,
963           source->str + start,
964           len);
965
966   return TRUE;
967 }
968
969 /**
970  * Checks assertions for two strings we're copying a segment between,
971  * and declares real_source/real_dest variables.
972  *
973  * @param source the source string
974  * @param start the starting offset
975  * @param dest the dest string
976  * @param insert_at where the copied segment is inserted
977  */
978 #define DBUS_STRING_COPY_PREAMBLE(source, start, dest, insert_at)       \
979   DBusRealString *real_source = (DBusRealString*) source;               \
980   DBusRealString *real_dest = (DBusRealString*) dest;                   \
981   _dbus_assert ((source) != (dest));                                    \
982   DBUS_GENERIC_STRING_PREAMBLE (real_source);                           \
983   DBUS_GENERIC_STRING_PREAMBLE (real_dest);                             \
984   _dbus_assert (!real_dest->constant);                                  \
985   _dbus_assert (!real_dest->locked);                                    \
986   _dbus_assert ((start) >= 0);                                          \
987   _dbus_assert ((start) <= real_source->len);                           \
988   _dbus_assert ((insert_at) >= 0);                                      \
989   _dbus_assert ((insert_at) <= real_dest->len)
990
991 /**
992  * Moves the end of one string into another string. Both strings
993  * must be initialized, valid strings.
994  *
995  * @param source the source string
996  * @param start where to chop off the source string
997  * @param dest the destination string
998  * @param insert_at where to move the chopped-off part of source string
999  * @returns #FALSE if not enough memory
1000  */
1001 dbus_bool_t
1002 _dbus_string_move (DBusString       *source,
1003                    int               start,
1004                    DBusString       *dest,
1005                    int               insert_at)
1006 {
1007   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1008   
1009   if (!copy (real_source, start,
1010              real_source->len - start,
1011              real_dest,
1012              insert_at))
1013     return FALSE;
1014
1015   delete (real_source, start,
1016           real_source->len - start);
1017
1018   return TRUE;
1019 }
1020
1021 /**
1022  * Like _dbus_string_move(), but does not delete the section
1023  * of the source string that's copied to the dest string.
1024  *
1025  * @param source the source string
1026  * @param start where to start copying the source string
1027  * @param dest the destination string
1028  * @param insert_at where to place the copied part of source string
1029  * @returns #FALSE if not enough memory
1030  */
1031 dbus_bool_t
1032 _dbus_string_copy (const DBusString *source,
1033                    int               start,
1034                    DBusString       *dest,
1035                    int               insert_at)
1036 {
1037   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1038
1039   return copy (real_source, start,
1040                real_source->len - start,
1041                real_dest,
1042                insert_at);
1043 }
1044
1045 /**
1046  * Like _dbus_string_move(), but can move a segment from
1047  * the middle of the source string.
1048  * 
1049  * @param source the source string
1050  * @param start first byte of source string to move
1051  * @param len length of segment to move
1052  * @param dest the destination string
1053  * @param insert_at where to move the bytes from the source string
1054  * @returns #FALSE if not enough memory
1055  */
1056 dbus_bool_t
1057 _dbus_string_move_len (DBusString       *source,
1058                        int               start,
1059                        int               len,
1060                        DBusString       *dest,
1061                        int               insert_at)
1062
1063 {
1064   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1065   _dbus_assert (len >= 0);
1066   _dbus_assert ((start + len) <= real_source->len);
1067
1068   if (!copy (real_source, start, len,
1069              real_dest,
1070              insert_at))
1071     return FALSE;
1072
1073   delete (real_source, start,
1074           len);
1075
1076   return TRUE;
1077 }
1078
1079 /**
1080  * Like _dbus_string_copy(), but can copy a segment from the middle of
1081  * the source string.
1082  *
1083  * @param source the source string
1084  * @param start where to start copying the source string
1085  * @param len length of segment to copy
1086  * @param dest the destination string
1087  * @param insert_at where to place the copied segment of source string
1088  * @returns #FALSE if not enough memory
1089  */
1090 dbus_bool_t
1091 _dbus_string_copy_len (const DBusString *source,
1092                        int               start,
1093                        int               len,
1094                        DBusString       *dest,
1095                        int               insert_at)
1096 {
1097   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1098   _dbus_assert (len >= 0);
1099   _dbus_assert (start <= real_source->len);
1100   _dbus_assert (len <= real_source->len - start);
1101   
1102   return copy (real_source, start, len,
1103                real_dest,
1104                insert_at);
1105 }
1106
1107 /**
1108  * Replaces a segment of dest string with a segment of source string.
1109  *
1110  * @todo optimize the case where the two lengths are the same, and
1111  * avoid memmoving the data in the trailing part of the string twice.
1112  *
1113  * @todo avoid inserting the source into dest, then deleting
1114  * the replaced chunk of dest (which creates a potentially large
1115  * intermediate string). Instead, extend the replaced chunk
1116  * of dest with padding to the same size as the source chunk,
1117  * then copy in the source bytes.
1118  * 
1119  * @param source the source string
1120  * @param start where to start copying the source string
1121  * @param len length of segment to copy
1122  * @param dest the destination string
1123  * @param replace_at start of segment of dest string to replace
1124  * @param replace_len length of segment of dest string to replace
1125  * @returns #FALSE if not enough memory
1126  *
1127  */
1128 dbus_bool_t
1129 _dbus_string_replace_len (const DBusString *source,
1130                           int               start,
1131                           int               len,
1132                           DBusString       *dest,
1133                           int               replace_at,
1134                           int               replace_len)
1135 {
1136   DBUS_STRING_COPY_PREAMBLE (source, start, dest, replace_at);
1137   _dbus_assert (len >= 0);
1138   _dbus_assert (start <= real_source->len);
1139   _dbus_assert (len <= real_source->len - start);
1140   _dbus_assert (replace_at >= 0);
1141   _dbus_assert (replace_at <= real_dest->len);
1142   _dbus_assert (replace_len <= real_dest->len - replace_at);
1143
1144   if (!copy (real_source, start, len,
1145              real_dest, replace_at))
1146     return FALSE;
1147
1148   delete (real_dest, replace_at + len, replace_len);
1149
1150   return TRUE;
1151 }
1152
1153 /* Unicode macros from GLib */
1154
1155 /** computes length and mask of a unicode character
1156  * @param Char the char
1157  * @param Mask the mask variable to assign to
1158  * @param Len the length variable to assign to
1159  */
1160 #define UTF8_COMPUTE(Char, Mask, Len)                                         \
1161   if (Char < 128)                                                             \
1162     {                                                                         \
1163       Len = 1;                                                                \
1164       Mask = 0x7f;                                                            \
1165     }                                                                         \
1166   else if ((Char & 0xe0) == 0xc0)                                             \
1167     {                                                                         \
1168       Len = 2;                                                                \
1169       Mask = 0x1f;                                                            \
1170     }                                                                         \
1171   else if ((Char & 0xf0) == 0xe0)                                             \
1172     {                                                                         \
1173       Len = 3;                                                                \
1174       Mask = 0x0f;                                                            \
1175     }                                                                         \
1176   else if ((Char & 0xf8) == 0xf0)                                             \
1177     {                                                                         \
1178       Len = 4;                                                                \
1179       Mask = 0x07;                                                            \
1180     }                                                                         \
1181   else if ((Char & 0xfc) == 0xf8)                                             \
1182     {                                                                         \
1183       Len = 5;                                                                \
1184       Mask = 0x03;                                                            \
1185     }                                                                         \
1186   else if ((Char & 0xfe) == 0xfc)                                             \
1187     {                                                                         \
1188       Len = 6;                                                                \
1189       Mask = 0x01;                                                            \
1190     }                                                                         \
1191   else                                                                        \
1192     Len = -1;
1193
1194 /**
1195  * computes length of a unicode character in UTF-8
1196  * @param Char the char
1197  */
1198 #define UTF8_LENGTH(Char)              \
1199   ((Char) < 0x80 ? 1 :                 \
1200    ((Char) < 0x800 ? 2 :               \
1201     ((Char) < 0x10000 ? 3 :            \
1202      ((Char) < 0x200000 ? 4 :          \
1203       ((Char) < 0x4000000 ? 5 : 6)))))
1204    
1205 /**
1206  * Gets a UTF-8 value.
1207  *
1208  * @param Result variable for extracted unicode char.
1209  * @param Chars the bytes to decode
1210  * @param Count counter variable
1211  * @param Mask mask for this char
1212  * @param Len length for this char in bytes
1213  */
1214 #define UTF8_GET(Result, Chars, Count, Mask, Len)                             \
1215   (Result) = (Chars)[0] & (Mask);                                             \
1216   for ((Count) = 1; (Count) < (Len); ++(Count))                               \
1217     {                                                                         \
1218       if (((Chars)[(Count)] & 0xc0) != 0x80)                                  \
1219         {                                                                     \
1220           (Result) = -1;                                                      \
1221           break;                                                              \
1222         }                                                                     \
1223       (Result) <<= 6;                                                         \
1224       (Result) |= ((Chars)[(Count)] & 0x3f);                                  \
1225     }
1226
1227 /**
1228  * Check whether a unicode char is in a valid range.
1229  *
1230  * @param Char the character
1231  */
1232 #define UNICODE_VALID(Char)                   \
1233     ((Char) < 0x110000 &&                     \
1234      ((Char) < 0xD800 || (Char) >= 0xE000) && \
1235      (Char) != 0xFFFE && (Char) != 0xFFFF)   
1236
1237 /**
1238  * Gets a unicode character from a UTF-8 string. Does no validation;
1239  * you must verify that the string is valid UTF-8 in advance and must
1240  * pass in the start of a character.
1241  *
1242  * @param str the string
1243  * @param start the start of the UTF-8 character.
1244  * @param ch_return location to return the character
1245  * @param end_return location to return the byte index of next character
1246  */
1247 void
1248 _dbus_string_get_unichar (const DBusString *str,
1249                           int               start,
1250                           dbus_unichar_t   *ch_return,
1251                           int              *end_return)
1252 {
1253   int i, mask, len;
1254   dbus_unichar_t result;
1255   unsigned char c;
1256   unsigned char *p;
1257   DBUS_CONST_STRING_PREAMBLE (str);
1258   _dbus_assert (start >= 0);
1259   _dbus_assert (start <= real->len);
1260   
1261   if (ch_return)
1262     *ch_return = 0;
1263   if (end_return)
1264     *end_return = real->len;
1265   
1266   mask = 0;
1267   p = real->str + start;
1268   c = *p;
1269   
1270   UTF8_COMPUTE (c, mask, len);
1271   if (len == -1)
1272     return;
1273   UTF8_GET (result, p, i, mask, len);
1274
1275   if (result == (dbus_unichar_t)-1)
1276     return;
1277
1278   if (ch_return)
1279     *ch_return = result;
1280   if (end_return)
1281     *end_return = start + len;
1282 }
1283
1284 /**
1285  * Finds the given substring in the string,
1286  * returning #TRUE and filling in the byte index
1287  * where the substring was found, if it was found.
1288  * Returns #FALSE if the substring wasn't found.
1289  * Sets *start to the length of the string if the substring
1290  * is not found.
1291  *
1292  * @param str the string
1293  * @param start where to start looking
1294  * @param substr the substring
1295  * @param found return location for where it was found, or #NULL
1296  * @returns #TRUE if found
1297  */
1298 dbus_bool_t
1299 _dbus_string_find (const DBusString *str,
1300                    int               start,
1301                    const char       *substr,
1302                    int              *found)
1303 {
1304   return _dbus_string_find_to (str, start,
1305                                ((const DBusRealString*)str)->len,
1306                                substr, found);
1307 }
1308
1309 /**
1310  * Finds the given substring in the string,
1311  * up to a certain position,
1312  * returning #TRUE and filling in the byte index
1313  * where the substring was found, if it was found.
1314  * Returns #FALSE if the substring wasn't found.
1315  * Sets *start to the length of the string if the substring
1316  * is not found.
1317  *
1318  * @param str the string
1319  * @param start where to start looking
1320  * @param end where to stop looking
1321  * @param substr the substring
1322  * @param found return location for where it was found, or #NULL
1323  * @returns #TRUE if found
1324  */
1325 dbus_bool_t
1326 _dbus_string_find_to (const DBusString *str,
1327                       int               start,
1328                       int               end,
1329                       const char       *substr,
1330                       int              *found)
1331 {
1332   int i;
1333   DBUS_CONST_STRING_PREAMBLE (str);
1334   _dbus_assert (substr != NULL);
1335   _dbus_assert (start <= real->len);
1336   _dbus_assert (start >= 0);
1337   _dbus_assert (substr != NULL);
1338   _dbus_assert (end <= real->len);
1339   _dbus_assert (start <= end);
1340
1341   /* we always "find" an empty string */
1342   if (*substr == '\0')
1343     {
1344       if (found)
1345         *found = start;
1346       return TRUE;
1347     }
1348
1349   i = start;
1350   while (i < end)
1351     {
1352       if (real->str[i] == substr[0])
1353         {
1354           int j = i + 1;
1355           
1356           while (j < end)
1357             {
1358               if (substr[j - i] == '\0')
1359                 break;
1360               else if (real->str[j] != substr[j - i])
1361                 break;
1362               
1363               ++j;
1364             }
1365
1366           if (substr[j - i] == '\0')
1367             {
1368               if (found)
1369                 *found = i;
1370               return TRUE;
1371             }
1372         }
1373       
1374       ++i;
1375     }
1376
1377   if (found)
1378     *found = end;
1379   
1380   return FALSE;  
1381 }
1382
1383 /**
1384  * Finds a blank (space or tab) in the string. Returns #TRUE
1385  * if found, #FALSE otherwise. If a blank is not found sets
1386  * *found to the length of the string.
1387  *
1388  * @param str the string
1389  * @param start byte index to start looking
1390  * @param found place to store the location of the first blank
1391  * @returns #TRUE if a blank was found
1392  */
1393 dbus_bool_t
1394 _dbus_string_find_blank (const DBusString *str,
1395                          int               start,
1396                          int              *found)
1397 {
1398   int i;
1399   DBUS_CONST_STRING_PREAMBLE (str);
1400   _dbus_assert (start <= real->len);
1401   _dbus_assert (start >= 0);
1402   
1403   i = start;
1404   while (i < real->len)
1405     {
1406       if (real->str[i] == ' ' ||
1407           real->str[i] == '\t')
1408         {
1409           if (found)
1410             *found = i;
1411           return TRUE;
1412         }
1413       
1414       ++i;
1415     }
1416
1417   if (found)
1418     *found = real->len;
1419   
1420   return FALSE;
1421 }
1422
1423 /**
1424  * Skips blanks from start, storing the first non-blank in *end
1425  *
1426  * @param str the string
1427  * @param start where to start
1428  * @param end where to store the first non-blank byte index
1429  */
1430 void
1431 _dbus_string_skip_blank (const DBusString *str,
1432                          int               start,
1433                          int              *end)
1434 {
1435   int i;
1436   DBUS_CONST_STRING_PREAMBLE (str);
1437   _dbus_assert (start <= real->len);
1438   _dbus_assert (start >= 0);
1439   
1440   i = start;
1441   while (i < real->len)
1442     {
1443       if (!(real->str[i] == ' ' ||
1444             real->str[i] == '\t'))
1445         break;
1446       
1447       ++i;
1448     }
1449
1450   _dbus_assert (i == real->len || !(real->str[i] == ' ' ||
1451                                     real->str[i] == '\t'));
1452   
1453   if (end)
1454     *end = i;
1455 }
1456
1457 /**
1458  * Assigns a newline-terminated or \r\n-terminated line from the front
1459  * of the string to the given dest string. The dest string's previous
1460  * contents are deleted. If the source string contains no newline,
1461  * moves the entire source string to the dest string.
1462  *
1463  * @todo owen correctly notes that this is a stupid function (it was
1464  * written purely for test code,
1465  * e.g. dbus-message-builder.c). Probably should be enforced as test
1466  * code only with #ifdef DBUS_BUILD_TESTS
1467  * 
1468  * @param source the source string
1469  * @param dest the destination string (contents are replaced)
1470  * @returns #FALSE if no memory, or source has length 0
1471  */
1472 dbus_bool_t
1473 _dbus_string_pop_line (DBusString *source,
1474                        DBusString *dest)
1475 {
1476   int eol;
1477   dbus_bool_t have_newline;
1478   
1479   _dbus_string_set_length (dest, 0);
1480   
1481   eol = 0;
1482   if (_dbus_string_find (source, 0, "\n", &eol))
1483     {
1484       have_newline = TRUE;
1485       eol += 1; /* include newline */
1486     }
1487   else
1488     {
1489       eol = _dbus_string_get_length (source);
1490       have_newline = FALSE;
1491     }
1492
1493   if (eol == 0)
1494     return FALSE; /* eof */
1495   
1496   if (!_dbus_string_move_len (source, 0, eol,
1497                               dest, 0))
1498     {
1499       return FALSE;
1500     }
1501
1502   /* dump the newline and the \r if we have one */
1503   if (have_newline)
1504     {
1505       dbus_bool_t have_cr;
1506       
1507       _dbus_assert (_dbus_string_get_length (dest) > 0);
1508
1509       if (_dbus_string_get_length (dest) > 1 &&
1510           _dbus_string_get_byte (dest,
1511                                  _dbus_string_get_length (dest) - 2) == '\r')
1512         have_cr = TRUE;
1513       else
1514         have_cr = FALSE;
1515         
1516       _dbus_string_set_length (dest,
1517                                _dbus_string_get_length (dest) -
1518                                (have_cr ? 2 : 1));
1519     }
1520   
1521   return TRUE;
1522 }
1523
1524 /**
1525  * Deletes up to and including the first blank space
1526  * in the string.
1527  *
1528  * @param str the string
1529  */
1530 void
1531 _dbus_string_delete_first_word (DBusString *str)
1532 {
1533   int i;
1534   
1535   if (_dbus_string_find_blank (str, 0, &i))
1536     _dbus_string_skip_blank (str, i, &i);
1537
1538   _dbus_string_delete (str, 0, i);
1539 }
1540
1541 /**
1542  * Deletes any leading blanks in the string
1543  *
1544  * @param str the string
1545  */
1546 void
1547 _dbus_string_delete_leading_blanks (DBusString *str)
1548 {
1549   int i;
1550   
1551   _dbus_string_skip_blank (str, 0, &i);
1552
1553   if (i > 0)
1554     _dbus_string_delete (str, 0, i);
1555 }
1556
1557 /**
1558  * Tests two DBusString for equality.
1559  *
1560  * @todo memcmp is probably faster
1561  *
1562  * @param a first string
1563  * @param b second string
1564  * @returns #TRUE if equal
1565  */
1566 dbus_bool_t
1567 _dbus_string_equal (const DBusString *a,
1568                     const DBusString *b)
1569 {
1570   const unsigned char *ap;
1571   const unsigned char *bp;
1572   const unsigned char *a_end;
1573   const DBusRealString *real_a = (const DBusRealString*) a;
1574   const DBusRealString *real_b = (const DBusRealString*) b;
1575   DBUS_GENERIC_STRING_PREAMBLE (real_a);
1576   DBUS_GENERIC_STRING_PREAMBLE (real_b);
1577
1578   if (real_a->len != real_b->len)
1579     return FALSE;
1580
1581   ap = real_a->str;
1582   bp = real_b->str;
1583   a_end = real_a->str + real_a->len;
1584   while (ap != a_end)
1585     {
1586       if (*ap != *bp)
1587         return FALSE;
1588       
1589       ++ap;
1590       ++bp;
1591     }
1592
1593   return TRUE;
1594 }
1595
1596 /**
1597  * Tests two DBusString for equality up to the given length.
1598  *
1599  * @todo write a unit test
1600  *
1601  * @todo memcmp is probably faster
1602  *
1603  * @param a first string
1604  * @param b second string
1605  * @param len the lengh
1606  * @returns #TRUE if equal for the given number of bytes
1607  */
1608 dbus_bool_t
1609 _dbus_string_equal_len (const DBusString *a,
1610                         const DBusString *b,
1611                         int               len)
1612 {
1613   const unsigned char *ap;
1614   const unsigned char *bp;
1615   const unsigned char *a_end;
1616   const DBusRealString *real_a = (const DBusRealString*) a;
1617   const DBusRealString *real_b = (const DBusRealString*) b;
1618   DBUS_GENERIC_STRING_PREAMBLE (real_a);
1619   DBUS_GENERIC_STRING_PREAMBLE (real_b);
1620
1621   if (real_a->len != real_b->len &&
1622       (real_a->len < len || real_b->len < len))
1623     return FALSE;
1624
1625   ap = real_a->str;
1626   bp = real_b->str;
1627   a_end = real_a->str + MIN (real_a->len, len);
1628   while (ap != a_end)
1629     {
1630       if (*ap != *bp)
1631         return FALSE;
1632       
1633       ++ap;
1634       ++bp;
1635     }
1636
1637   return TRUE;
1638 }
1639
1640 /**
1641  * Checks whether a string is equal to a C string.
1642  *
1643  * @param a the string
1644  * @param c_str the C string
1645  * @returns #TRUE if equal
1646  */
1647 dbus_bool_t
1648 _dbus_string_equal_c_str (const DBusString *a,
1649                           const char       *c_str)
1650 {
1651   const unsigned char *ap;
1652   const unsigned char *bp;
1653   const unsigned char *a_end;
1654   const DBusRealString *real_a = (const DBusRealString*) a;
1655   DBUS_GENERIC_STRING_PREAMBLE (real_a);
1656   _dbus_assert (c_str != NULL);
1657   
1658   ap = real_a->str;
1659   bp = (const unsigned char*) c_str;
1660   a_end = real_a->str + real_a->len;
1661   while (ap != a_end && *bp)
1662     {
1663       if (*ap != *bp)
1664         return FALSE;
1665       
1666       ++ap;
1667       ++bp;
1668     }
1669
1670   if (ap != a_end || *bp)
1671     return FALSE;
1672   
1673   return TRUE;
1674 }
1675
1676 /**
1677  * Checks whether a string starts with the given C string.
1678  *
1679  * @param a the string
1680  * @param c_str the C string
1681  * @returns #TRUE if string starts with it
1682  */
1683 dbus_bool_t
1684 _dbus_string_starts_with_c_str (const DBusString *a,
1685                                 const char       *c_str)
1686 {
1687   const unsigned char *ap;
1688   const unsigned char *bp;
1689   const unsigned char *a_end;
1690   const DBusRealString *real_a = (const DBusRealString*) a;
1691   DBUS_GENERIC_STRING_PREAMBLE (real_a);
1692   _dbus_assert (c_str != NULL);
1693   
1694   ap = real_a->str;
1695   bp = (const unsigned char*) c_str;
1696   a_end = real_a->str + real_a->len;
1697   while (ap != a_end && *bp)
1698     {
1699       if (*ap != *bp)
1700         return FALSE;
1701       
1702       ++ap;
1703       ++bp;
1704     }
1705
1706   if (*bp == '\0')
1707     return TRUE;
1708   else
1709     return FALSE;
1710 }
1711
1712 /**
1713  * Returns whether a string ends with the given suffix
1714  *
1715  * @todo memcmp might make this faster.
1716  * 
1717  * @param a the string
1718  * @param c_str the C-style string
1719  * @returns #TRUE if the string ends with the suffix
1720  */
1721 dbus_bool_t
1722 _dbus_string_ends_with_c_str (const DBusString *a,
1723                               const char       *c_str)
1724 {
1725   const unsigned char *ap;
1726   const unsigned char *bp;
1727   const unsigned char *a_end;
1728   unsigned long c_str_len;
1729   const DBusRealString *real_a = (const DBusRealString*) a;
1730   DBUS_GENERIC_STRING_PREAMBLE (real_a);
1731   _dbus_assert (c_str != NULL);
1732   
1733   c_str_len = strlen (c_str);
1734   if (((unsigned long)real_a->len) < c_str_len)
1735     return FALSE;
1736   
1737   ap = real_a->str + (real_a->len - c_str_len);
1738   bp = (const unsigned char*) c_str;
1739   a_end = real_a->str + real_a->len;
1740   while (ap != a_end)
1741     {
1742       if (*ap != *bp)
1743         return FALSE;
1744       
1745       ++ap;
1746       ++bp;
1747     }
1748
1749   _dbus_assert (*ap == '\0');
1750   _dbus_assert (*bp == '\0');
1751   
1752   return TRUE;
1753 }
1754
1755 static const signed char base64_table[] = {
1756   /* 0 */ 'A',
1757   /* 1 */ 'B',
1758   /* 2 */ 'C',
1759   /* 3 */ 'D',
1760   /* 4 */ 'E',
1761   /* 5 */ 'F',
1762   /* 6 */ 'G',
1763   /* 7 */ 'H',
1764   /* 8 */ 'I',
1765   /* 9 */ 'J',
1766   /* 10 */ 'K',
1767   /* 11 */ 'L',
1768   /* 12 */ 'M',
1769   /* 13 */ 'N',
1770   /* 14 */ 'O',
1771   /* 15 */ 'P',
1772   /* 16 */ 'Q',
1773   /* 17 */ 'R',
1774   /* 18 */ 'S',
1775   /* 19 */ 'T',
1776   /* 20 */ 'U',
1777   /* 21 */ 'V',
1778   /* 22 */ 'W',
1779   /* 23 */ 'X',
1780   /* 24 */ 'Y',
1781   /* 25 */ 'Z',
1782   /* 26 */ 'a',
1783   /* 27 */ 'b',
1784   /* 28 */ 'c',
1785   /* 29 */ 'd',
1786   /* 30 */ 'e',
1787   /* 31 */ 'f',
1788   /* 32 */ 'g',
1789   /* 33 */ 'h',
1790   /* 34 */ 'i',
1791   /* 35 */ 'j',
1792   /* 36 */ 'k',
1793   /* 37 */ 'l',
1794   /* 38 */ 'm',
1795   /* 39 */ 'n',
1796   /* 40 */ 'o',
1797   /* 41 */ 'p',
1798   /* 42 */ 'q',
1799   /* 43 */ 'r',
1800   /* 44 */ 's',
1801   /* 45 */ 't',
1802   /* 46 */ 'u',
1803   /* 47 */ 'v',
1804   /* 48 */ 'w',
1805   /* 49 */ 'x',
1806   /* 50 */ 'y',
1807   /* 51 */ 'z',
1808   /* 52 */ '0',
1809   /* 53 */ '1',
1810   /* 54 */ '2',
1811   /* 55 */ '3',
1812   /* 56 */ '4',
1813   /* 57 */ '5',
1814   /* 58 */ '6',
1815   /* 59 */ '7',
1816   /* 60 */ '8',
1817   /* 61 */ '9',
1818   /* 62 */ '+',
1819   /* 63 */ '/'
1820 };
1821
1822 /** The minimum char that's a valid char in Base64-encoded text */
1823 #define UNBASE64_MIN_CHAR (43)
1824 /** The maximum char that's a valid char in Base64-encoded text */
1825 #define UNBASE64_MAX_CHAR (122)
1826 /** Must subtract this from a char's integer value before offsetting
1827  * into unbase64_table
1828  */
1829 #define UNBASE64_TABLE_OFFSET UNBASE64_MIN_CHAR
1830 static const signed char unbase64_table[] = {
1831   /* 43 + */ 62,
1832   /* 44 , */ -1,
1833   /* 45 - */ -1,
1834   /* 46 . */ -1,
1835   /* 47 / */ 63,
1836   /* 48 0 */ 52,
1837   /* 49 1 */ 53,
1838   /* 50 2 */ 54,
1839   /* 51 3 */ 55,
1840   /* 52 4 */ 56,
1841   /* 53 5 */ 57,
1842   /* 54 6 */ 58,
1843   /* 55 7 */ 59,
1844   /* 56 8 */ 60,
1845   /* 57 9 */ 61,
1846   /* 58 : */ -1,
1847   /* 59 ; */ -1,
1848   /* 60 < */ -1,
1849   /* 61 = */ -1,
1850   /* 62 > */ -1,
1851   /* 63 ? */ -1,
1852   /* 64 @ */ -1,
1853   /* 65 A */ 0,
1854   /* 66 B */ 1,
1855   /* 67 C */ 2,
1856   /* 68 D */ 3,
1857   /* 69 E */ 4,
1858   /* 70 F */ 5,
1859   /* 71 G */ 6,
1860   /* 72 H */ 7,
1861   /* 73 I */ 8,
1862   /* 74 J */ 9,
1863   /* 75 K */ 10,
1864   /* 76 L */ 11,
1865   /* 77 M */ 12,
1866   /* 78 N */ 13,
1867   /* 79 O */ 14,
1868   /* 80 P */ 15,
1869   /* 81 Q */ 16,
1870   /* 82 R */ 17,
1871   /* 83 S */ 18,
1872   /* 84 T */ 19,
1873   /* 85 U */ 20,
1874   /* 86 V */ 21,
1875   /* 87 W */ 22,
1876   /* 88 X */ 23,
1877   /* 89 Y */ 24,
1878   /* 90 Z */ 25,
1879   /* 91 [ */ -1,
1880   /* 92 \ */ -1,
1881   /* 93 ] */ -1,
1882   /* 94 ^ */ -1,
1883   /* 95 _ */ -1,
1884   /* 96 ` */ -1,
1885   /* 97 a */ 26,
1886   /* 98 b */ 27,
1887   /* 99 c */ 28,
1888   /* 100 d */ 29,
1889   /* 101 e */ 30,
1890   /* 102 f */ 31,
1891   /* 103 g */ 32,
1892   /* 104 h */ 33,
1893   /* 105 i */ 34,
1894   /* 106 j */ 35,
1895   /* 107 k */ 36,
1896   /* 108 l */ 37,
1897   /* 109 m */ 38,
1898   /* 110 n */ 39,
1899   /* 111 o */ 40,
1900   /* 112 p */ 41,
1901   /* 113 q */ 42,
1902   /* 114 r */ 43,
1903   /* 115 s */ 44,
1904   /* 116 t */ 45,
1905   /* 117 u */ 46,
1906   /* 118 v */ 47,
1907   /* 119 w */ 48,
1908   /* 120 x */ 49,
1909   /* 121 y */ 50,
1910   /* 122 z */ 51
1911 };
1912
1913 /**
1914  * Encodes a string using Base64, as documented in RFC 2045.
1915  *
1916  * @param source the string to encode
1917  * @param start byte index to start encoding
1918  * @param dest string where encoded data should be placed
1919  * @param insert_at where to place encoded data
1920  * @returns #TRUE if encoding was successful, #FALSE if no memory etc.
1921  */
1922 dbus_bool_t
1923 _dbus_string_base64_encode (const DBusString *source,
1924                             int               start,
1925                             DBusString       *dest,
1926                             int               insert_at)
1927 {
1928   int source_len;
1929   unsigned int dest_len; /* unsigned for overflow checks below */
1930   const unsigned char *s;
1931   unsigned char *d;
1932   const unsigned char *triplet_end;
1933   const unsigned char *final_end;
1934   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);  
1935   _dbus_assert (source != dest);
1936   
1937   /* For each 24 bits (3 bytes) of input, we have 4 bytes of
1938    * output.
1939    */
1940   source_len = real_source->len - start;
1941   dest_len = (source_len / 3) * 4;
1942   if (source_len % 3 != 0)
1943     dest_len += 4;
1944
1945   if (dest_len > (unsigned int) real_dest->max_length)
1946     return FALSE;
1947   
1948   if (source_len == 0)
1949     return TRUE;
1950   
1951   if (!open_gap (dest_len, real_dest, insert_at))
1952     return FALSE;
1953
1954   d = real_dest->str + insert_at;
1955   s = real_source->str + start;
1956   final_end = real_source->str + (start + source_len);
1957   triplet_end = final_end - (source_len % 3);
1958   _dbus_assert (triplet_end <= final_end);
1959   _dbus_assert ((final_end - triplet_end) < 3);
1960
1961 #define ENCODE_64(v) (base64_table[ (unsigned char) (v) ])
1962 #define SIX_BITS_MASK (0x3f)
1963   _dbus_assert (SIX_BITS_MASK < _DBUS_N_ELEMENTS (base64_table));
1964   
1965   while (s != triplet_end)
1966     {
1967       unsigned int triplet;
1968
1969       triplet = s[2] | (s[1] << 8) | (s[0] << 16);
1970
1971       /* Encode each 6 bits. */
1972
1973       *d++ = ENCODE_64 (triplet >> 18);
1974       *d++ = ENCODE_64 ((triplet >> 12) & SIX_BITS_MASK);
1975       *d++ = ENCODE_64 ((triplet >> 6) & SIX_BITS_MASK);
1976       *d++ = ENCODE_64 (triplet & SIX_BITS_MASK);
1977       
1978       s += 3;
1979     }
1980
1981   switch (final_end - triplet_end)
1982     {
1983     case 2:
1984       {
1985         unsigned int doublet;
1986         
1987         doublet = s[1] | (s[0] << 8);        
1988
1989         *d++ = ENCODE_64 (doublet >> 12);
1990         *d++ = ENCODE_64 ((doublet >> 6) & SIX_BITS_MASK);
1991         *d++ = ENCODE_64 (doublet & SIX_BITS_MASK);
1992         *d++ = '=';
1993       }
1994       break;
1995     case 1:
1996       {
1997         unsigned int singlet;
1998         
1999         singlet = s[0];
2000
2001         *d++ = ENCODE_64 ((singlet >> 6) & SIX_BITS_MASK);
2002         *d++ = ENCODE_64 (singlet & SIX_BITS_MASK);
2003         *d++ = '=';
2004         *d++ = '=';
2005       }
2006       break;
2007     case 0:
2008       break;
2009     }
2010
2011   _dbus_assert (d == (real_dest->str + (insert_at + dest_len)));
2012
2013   return TRUE;
2014 }
2015
2016 /**
2017  * Decodes a string from Base64, as documented in RFC 2045.
2018  *
2019  * @todo sort out the AUDIT comment in here. The case it mentions
2020  * ("====" or "x===") is not allowed in correct base64, so need to
2021  * decide what to do with that kind of input. Probably ignore it
2022  * since we ignore any other junk seen.
2023  *
2024  * @param source the string to decode
2025  * @param start byte index to start decode
2026  * @param dest string where decoded data should be placed
2027  * @param insert_at where to place decoded data
2028  * @returns #TRUE if decoding was successful, #FALSE if no memory etc.
2029  */
2030 dbus_bool_t
2031 _dbus_string_base64_decode (const DBusString *source,
2032                             int               start,
2033                             DBusString       *dest,
2034                             int               insert_at)
2035 {
2036   int source_len;
2037   const char *s;
2038   const char *end;
2039   DBusString result;
2040   unsigned int triplet = 0;
2041   int sextet_count;
2042   int pad_count;
2043   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
2044   _dbus_assert (source != dest);
2045   
2046   source_len = real_source->len - start;
2047   s = real_source->str + start;
2048   end = real_source->str + source_len;
2049
2050   if (source_len == 0)
2051     return TRUE;
2052
2053   if (!_dbus_string_init (&result, _DBUS_INT_MAX))
2054     return FALSE;
2055
2056   pad_count = 0;
2057   sextet_count = 0;
2058   while (s != end)
2059     {
2060       /* The idea is to just skip anything that isn't
2061        * a base64 char - it's allowed to have whitespace,
2062        * newlines, etc. in here. We also ignore trailing
2063        * base64 chars, though that's suspicious.
2064        */
2065       
2066       if (*s >= UNBASE64_MIN_CHAR &&
2067           *s <= UNBASE64_MAX_CHAR)
2068         {
2069           if (*s == '=')
2070             {
2071               /* '=' is padding, doesn't represent additional data
2072                * but does increment our count.
2073                */
2074               pad_count += 1;
2075               sextet_count += 1;
2076             }
2077           else
2078             {
2079               int val;
2080
2081               val = unbase64_table[(*s) - UNBASE64_TABLE_OFFSET];
2082
2083               if (val >= 0)
2084                 {
2085                   triplet <<= 6;
2086                   triplet |= (unsigned int) val;
2087                   sextet_count += 1;
2088                 }
2089             }
2090
2091           if (sextet_count == 4)
2092             {
2093               /* no pad = 3 bytes, 1 pad = 2 bytes, 2 pad = 1 byte */
2094
2095
2096               /* AUDIT: Comment doesn't mention 4 pad => 0,
2097                *         3 pad => 1 byte, though the code should
2098                *        work fine if those are the required outputs.
2099                *
2100                *        I assume that the spec requires dropping
2101                *        the top two bits of, say, ///= which is > 2 
2102                *        bytes worth of bits. (Or otherwise, you couldn't
2103                *        actually represent 2 byte sequences.
2104                */
2105               
2106               if (pad_count < 1)
2107                 _dbus_string_append_byte (&result,
2108                                           triplet >> 16);
2109               
2110               if (pad_count < 2)
2111                 _dbus_string_append_byte (&result,
2112                                           (triplet >> 8) & 0xff);              
2113               
2114               _dbus_string_append_byte (&result,
2115                                         triplet & 0xff);
2116               
2117               sextet_count = 0;
2118               pad_count = 0;
2119               triplet = 0;
2120             }
2121         }
2122       
2123       ++s;
2124     }
2125
2126   if (!_dbus_string_move (&result, 0, dest, insert_at))
2127     {
2128       _dbus_string_free (&result);
2129       return FALSE;
2130     }
2131
2132   _dbus_string_free (&result);
2133
2134   return TRUE;
2135 }
2136
2137 /**
2138  * Encodes a string in hex, the way MD5 and SHA-1 are usually
2139  * encoded. (Each byte is two hex digits.)
2140  *
2141  * @param source the string to encode
2142  * @param start byte index to start encoding
2143  * @param dest string where encoded data should be placed
2144  * @param insert_at where to place encoded data
2145  * @returns #TRUE if encoding was successful, #FALSE if no memory etc.
2146  */
2147 dbus_bool_t
2148 _dbus_string_hex_encode (const DBusString *source,
2149                          int               start,
2150                          DBusString       *dest,
2151                          int               insert_at)
2152 {
2153   DBusString result;
2154   const char hexdigits[16] = {
2155     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
2156     'a', 'b', 'c', 'd', 'e', 'f'
2157   };
2158   const unsigned char *p;
2159   const unsigned char *end;
2160   dbus_bool_t retval;
2161   
2162   _dbus_assert (start <= _dbus_string_get_length (source));
2163
2164   if (!_dbus_string_init (&result, _DBUS_INT_MAX))
2165     return FALSE;
2166
2167   retval = FALSE;
2168   
2169   _dbus_string_get_const_data (source, (const char**) &p);
2170   end = p + _dbus_string_get_length (source);
2171   p += start;
2172   
2173   while (p != end)
2174     {
2175       if (!_dbus_string_append_byte (&result,
2176                                      hexdigits[(*p >> 4)]))
2177         goto out;
2178       
2179       if (!_dbus_string_append_byte (&result,
2180                                      hexdigits[(*p & 0x0f)]))
2181         goto out;
2182
2183       ++p;
2184     }
2185
2186   if (!_dbus_string_move (&result, 0, dest, insert_at))
2187     goto out;
2188
2189   retval = TRUE;
2190
2191  out:
2192   _dbus_string_free (&result);
2193   return retval;
2194 }
2195
2196 /**
2197  * Decodes a string from hex encoding.
2198  *
2199  * @param source the string to decode
2200  * @param start byte index to start decode
2201  * @param dest string where decoded data should be placed
2202  * @param insert_at where to place decoded data
2203  * @returns #TRUE if decoding was successful, #FALSE if no memory etc.
2204  */
2205 dbus_bool_t
2206 _dbus_string_hex_decode (const DBusString *source,
2207                          int               start,
2208                          DBusString       *dest,
2209                          int               insert_at)
2210 {
2211   DBusString result;
2212   const unsigned char *p;
2213   const unsigned char *end;
2214   dbus_bool_t retval;
2215   dbus_bool_t high_bits;
2216   
2217   _dbus_assert (start <= _dbus_string_get_length (source));
2218
2219   if (!_dbus_string_init (&result, _DBUS_INT_MAX))
2220     return FALSE;
2221
2222   retval = FALSE;
2223
2224   high_bits = TRUE;
2225   _dbus_string_get_const_data (source, (const char**) &p);
2226   end = p + _dbus_string_get_length (source);
2227   p += start;
2228   
2229   while (p != end)
2230     {
2231       unsigned int val;
2232
2233       switch (*p)
2234         {
2235         case '0':
2236           val = 0;
2237           break;
2238         case '1':
2239           val = 1;
2240           break;
2241         case '2':
2242           val = 2;
2243           break;
2244         case '3':
2245           val = 3;
2246           break;
2247         case '4':
2248           val = 4;
2249           break;
2250         case '5':
2251           val = 5;
2252           break;
2253         case '6':
2254           val = 6;
2255           break;
2256         case '7':
2257           val = 7;
2258           break;
2259         case '8':
2260           val = 8;
2261           break;
2262         case '9':
2263           val = 9;
2264           break;
2265         case 'a':
2266         case 'A':
2267           val = 10;
2268           break;
2269         case 'b':
2270         case 'B':
2271           val = 11;
2272           break;
2273         case 'c':
2274         case 'C':
2275           val = 12;
2276           break;
2277         case 'd':
2278         case 'D':
2279           val = 13;
2280           break;
2281         case 'e':
2282         case 'E':
2283           val = 14;
2284           break;
2285         case 'f':
2286         case 'F':
2287           val = 15;
2288           break;
2289         default:
2290           val = 0;
2291           _dbus_verbose ("invalid character '%c' in hex encoded text\n",
2292                          *p);
2293           goto out;
2294         }
2295
2296       if (high_bits)
2297         {
2298           if (!_dbus_string_append_byte (&result,
2299                                          val << 4))
2300             goto out;
2301         }
2302       else
2303         {
2304           int len;
2305           unsigned char b;
2306
2307           len = _dbus_string_get_length (&result);
2308           
2309           b = _dbus_string_get_byte (&result, len - 1);
2310
2311           b |= val;
2312
2313           _dbus_string_set_byte (&result, len - 1, b);
2314         }
2315
2316       high_bits = !high_bits;
2317
2318       ++p;
2319     }
2320
2321   if (!_dbus_string_move (&result, 0, dest, insert_at))
2322     goto out;
2323
2324   retval = TRUE;
2325   
2326  out:
2327   _dbus_string_free (&result);  
2328   return retval;
2329 }
2330
2331 /**
2332  * Checks that the given range of the string is valid ASCII with no
2333  * nul bytes. If the given range is not entirely contained in the
2334  * string, returns #FALSE.
2335  *
2336  * @todo this is inconsistent with most of DBusString in that
2337  * it allows a start,len range that isn't in the string.
2338  * 
2339  * @param str the string
2340  * @param start first byte index to check
2341  * @param len number of bytes to check
2342  * @returns #TRUE if the byte range exists and is all valid ASCII
2343  */
2344 dbus_bool_t
2345 _dbus_string_validate_ascii (const DBusString *str,
2346                              int               start,
2347                              int               len)
2348 {
2349   const unsigned char *s;
2350   const unsigned char *end;
2351   DBUS_CONST_STRING_PREAMBLE (str);
2352   _dbus_assert (start >= 0);
2353   _dbus_assert (start <= real->len);
2354   _dbus_assert (len >= 0);
2355   
2356   if (len > real->len - start)
2357     return FALSE;
2358   
2359   s = real->str + start;
2360   end = s + len;
2361   while (s != end)
2362     {
2363       if (*s == '\0' ||
2364           ((*s & ~0x7f) != 0))
2365         return FALSE;
2366         
2367       ++s;
2368     }
2369   
2370   return TRUE;
2371 }
2372
2373 /**
2374  * Checks that the given range of the string is valid UTF-8. If the
2375  * given range is not entirely contained in the string, returns
2376  * #FALSE. If the string contains any nul bytes in the given range,
2377  * returns #FALSE.
2378  *
2379  * @todo right now just calls _dbus_string_validate_ascii()
2380  *
2381  * @todo this is inconsistent with most of DBusString in that
2382  * it allows a start,len range that isn't in the string.
2383  * 
2384  * @param str the string
2385  * @param start first byte index to check
2386  * @param len number of bytes to check
2387  * @returns #TRUE if the byte range exists and is all valid UTF-8
2388  */
2389 dbus_bool_t
2390 _dbus_string_validate_utf8  (const DBusString *str,
2391                              int               start,
2392                              int               len)
2393 {
2394   /* FIXME actually validate UTF-8 */
2395   return _dbus_string_validate_ascii (str, start, len);
2396 }
2397
2398 /**
2399  * Checks that the given range of the string is all nul bytes. If the
2400  * given range is not entirely contained in the string, returns
2401  * #FALSE.
2402  *
2403  * @todo this is inconsistent with most of DBusString in that
2404  * it allows a start,len range that isn't in the string.
2405  * 
2406  * @param str the string
2407  * @param start first byte index to check
2408  * @param len number of bytes to check
2409  * @returns #TRUE if the byte range exists and is all nul bytes
2410  */
2411 dbus_bool_t
2412 _dbus_string_validate_nul (const DBusString *str,
2413                            int               start,
2414                            int               len)
2415 {
2416   const unsigned char *s;
2417   const unsigned char *end;
2418   DBUS_CONST_STRING_PREAMBLE (str);
2419   _dbus_assert (start >= 0);
2420   _dbus_assert (len >= 0);
2421   _dbus_assert (start <= real->len);
2422   
2423   if (len > real->len - start)
2424     return FALSE;
2425   
2426   s = real->str + start;
2427   end = s + len;
2428   while (s != end)
2429     {
2430       if (*s != '\0')
2431         return FALSE;
2432       ++s;
2433     }
2434   
2435   return TRUE;
2436 }
2437
2438 /**
2439  * Clears all allocated bytes in the string to zero.
2440  *
2441  * @param str the string
2442  */
2443 void
2444 _dbus_string_zero (DBusString *str)
2445 {
2446   DBUS_STRING_PREAMBLE (str);
2447
2448   memset (real->str, '\0', real->allocated);
2449 }
2450
2451 /** @} */
2452
2453 #ifdef DBUS_BUILD_TESTS
2454 #include "dbus-test.h"
2455 #include <stdio.h>
2456
2457 static void
2458 test_max_len (DBusString *str,
2459               int         max_len)
2460 {
2461   if (max_len > 0)
2462     {
2463       if (!_dbus_string_set_length (str, max_len - 1))
2464         _dbus_assert_not_reached ("setting len to one less than max should have worked");
2465     }
2466
2467   if (!_dbus_string_set_length (str, max_len))
2468     _dbus_assert_not_reached ("setting len to max len should have worked");
2469
2470   if (_dbus_string_set_length (str, max_len + 1))
2471     _dbus_assert_not_reached ("setting len to one more than max len should not have worked");
2472
2473   if (!_dbus_string_set_length (str, 0))
2474     _dbus_assert_not_reached ("setting len to zero should have worked");
2475 }
2476
2477 static void
2478 test_base64_roundtrip (const unsigned char *data,
2479                        int                  len)
2480 {
2481   DBusString orig;
2482   DBusString encoded;
2483   DBusString decoded;
2484
2485   if (len < 0)
2486     len = strlen (data);
2487   
2488   if (!_dbus_string_init (&orig, _DBUS_INT_MAX))
2489     _dbus_assert_not_reached ("could not init string");
2490
2491   if (!_dbus_string_init (&encoded, _DBUS_INT_MAX))
2492     _dbus_assert_not_reached ("could not init string");
2493   
2494   if (!_dbus_string_init (&decoded, _DBUS_INT_MAX))
2495     _dbus_assert_not_reached ("could not init string");
2496
2497   if (!_dbus_string_append_len (&orig, data, len))
2498     _dbus_assert_not_reached ("couldn't append orig data");
2499
2500   if (!_dbus_string_base64_encode (&orig, 0, &encoded, 0))
2501     _dbus_assert_not_reached ("could not encode");
2502
2503   if (!_dbus_string_base64_decode (&encoded, 0, &decoded, 0))
2504     _dbus_assert_not_reached ("could not decode");
2505
2506   if (!_dbus_string_equal (&orig, &decoded))
2507     {
2508       const char *s;
2509       
2510       printf ("Original string %d bytes encoded %d bytes decoded %d bytes\n",
2511               _dbus_string_get_length (&orig),
2512               _dbus_string_get_length (&encoded),
2513               _dbus_string_get_length (&decoded));
2514       printf ("Original: %s\n", data);
2515       _dbus_string_get_const_data (&decoded, &s);
2516       printf ("Decoded: %s\n", s);
2517       _dbus_assert_not_reached ("original string not the same as string decoded from base64");
2518     }
2519   
2520   _dbus_string_free (&orig);
2521   _dbus_string_free (&encoded);
2522   _dbus_string_free (&decoded);  
2523 }
2524
2525 static void
2526 test_hex_roundtrip (const unsigned char *data,
2527                     int                  len)
2528 {
2529   DBusString orig;
2530   DBusString encoded;
2531   DBusString decoded;
2532
2533   if (len < 0)
2534     len = strlen (data);
2535   
2536   if (!_dbus_string_init (&orig, _DBUS_INT_MAX))
2537     _dbus_assert_not_reached ("could not init string");
2538
2539   if (!_dbus_string_init (&encoded, _DBUS_INT_MAX))
2540     _dbus_assert_not_reached ("could not init string");
2541   
2542   if (!_dbus_string_init (&decoded, _DBUS_INT_MAX))
2543     _dbus_assert_not_reached ("could not init string");
2544
2545   if (!_dbus_string_append_len (&orig, data, len))
2546     _dbus_assert_not_reached ("couldn't append orig data");
2547
2548   if (!_dbus_string_hex_encode (&orig, 0, &encoded, 0))
2549     _dbus_assert_not_reached ("could not encode");
2550
2551   if (!_dbus_string_hex_decode (&encoded, 0, &decoded, 0))
2552     _dbus_assert_not_reached ("could not decode");
2553     
2554   if (!_dbus_string_equal (&orig, &decoded))
2555     {
2556       const char *s;
2557       
2558       printf ("Original string %d bytes encoded %d bytes decoded %d bytes\n",
2559               _dbus_string_get_length (&orig),
2560               _dbus_string_get_length (&encoded),
2561               _dbus_string_get_length (&decoded));
2562       printf ("Original: %s\n", data);
2563       _dbus_string_get_const_data (&decoded, &s);
2564       printf ("Decoded: %s\n", s);
2565       _dbus_assert_not_reached ("original string not the same as string decoded from base64");
2566     }
2567   
2568   _dbus_string_free (&orig);
2569   _dbus_string_free (&encoded);
2570   _dbus_string_free (&decoded);  
2571 }
2572
2573 typedef void (* TestRoundtripFunc) (const unsigned char *data,
2574                                     int                  len);
2575 static void
2576 test_roundtrips (TestRoundtripFunc func)
2577 {
2578   (* func) ("Hello this is a string\n", -1);
2579   (* func) ("Hello this is a string\n1", -1);
2580   (* func) ("Hello this is a string\n12", -1);
2581   (* func) ("Hello this is a string\n123", -1);
2582   (* func) ("Hello this is a string\n1234", -1);
2583   (* func) ("Hello this is a string\n12345", -1);
2584   (* func) ("", 0);
2585   (* func) ("1", 1);
2586   (* func) ("12", 2);
2587   (* func) ("123", 3);
2588   (* func) ("1234", 4);
2589   (* func) ("12345", 5);
2590   (* func) ("", 1);
2591   (* func) ("1", 2);
2592   (* func) ("12", 3);
2593   (* func) ("123", 4);
2594   (* func) ("1234", 5);
2595   (* func) ("12345", 6);
2596   {
2597     unsigned char buf[512];
2598     int i;
2599     
2600     i = 0;
2601     while (i < _DBUS_N_ELEMENTS (buf))
2602       {
2603         buf[i] = i;
2604         ++i;
2605       }
2606     i = 0;
2607     while (i < _DBUS_N_ELEMENTS (buf))
2608       {
2609         (* func) (buf, i);
2610         ++i;
2611       }
2612   }
2613 }
2614
2615
2616 /**
2617  * @ingroup DBusStringInternals
2618  * Unit test for DBusString.
2619  *
2620  * @todo Need to write tests for _dbus_string_copy() and
2621  * _dbus_string_move() moving to/from each of start/middle/end of a
2622  * string. Also need tests for _dbus_string_move_len ()
2623  * 
2624  * @returns #TRUE on success.
2625  */
2626 dbus_bool_t
2627 _dbus_string_test (void)
2628 {
2629   DBusString str;
2630   DBusString other;
2631   int i, end;
2632   long v;
2633   double d;
2634   int lens[] = { 0, 1, 2, 3, 4, 5, 10, 16, 17, 18, 25, 31, 32, 33, 34, 35, 63, 64, 65, 66, 67, 68, 69, 70, 71, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136 };
2635   char *s;
2636   dbus_unichar_t ch;
2637   
2638   i = 0;
2639   while (i < _DBUS_N_ELEMENTS (lens))
2640     {
2641       if (!_dbus_string_init (&str, lens[i]))
2642         _dbus_assert_not_reached ("failed to init string");
2643       
2644       test_max_len (&str, lens[i]);
2645       _dbus_string_free (&str);
2646
2647       ++i;
2648     }
2649
2650   /* Test shortening and setting length */
2651   i = 0;
2652   while (i < _DBUS_N_ELEMENTS (lens))
2653     {
2654       int j;
2655       
2656       if (!_dbus_string_init (&str, lens[i]))
2657         _dbus_assert_not_reached ("failed to init string");
2658       
2659       if (!_dbus_string_set_length (&str, lens[i]))
2660         _dbus_assert_not_reached ("failed to set string length");
2661
2662       j = lens[i];
2663       while (j > 0)
2664         {
2665           _dbus_assert (_dbus_string_get_length (&str) == j);
2666           if (j > 0)
2667             {
2668               _dbus_string_shorten (&str, 1);
2669               _dbus_assert (_dbus_string_get_length (&str) == (j - 1));
2670             }
2671           --j;
2672         }
2673       
2674       _dbus_string_free (&str);
2675
2676       ++i;
2677     }
2678
2679   /* Test appending data */
2680   if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2681     _dbus_assert_not_reached ("failed to init string");
2682
2683   i = 0;
2684   while (i < 10)
2685     {
2686       if (!_dbus_string_append (&str, "a"))
2687         _dbus_assert_not_reached ("failed to append string to string\n");
2688
2689       _dbus_assert (_dbus_string_get_length (&str) == i * 2 + 1);
2690
2691       if (!_dbus_string_append_byte (&str, 'b'))
2692         _dbus_assert_not_reached ("failed to append byte to string\n");
2693
2694       _dbus_assert (_dbus_string_get_length (&str) == i * 2 + 2);
2695                     
2696       ++i;
2697     }
2698
2699   _dbus_string_free (&str);
2700
2701   /* Check steal_data */
2702   
2703   if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2704     _dbus_assert_not_reached ("failed to init string");
2705
2706   if (!_dbus_string_append (&str, "Hello World"))
2707     _dbus_assert_not_reached ("could not append to string");
2708
2709   i = _dbus_string_get_length (&str);
2710   
2711   if (!_dbus_string_steal_data (&str, &s))
2712     _dbus_assert_not_reached ("failed to steal data");
2713
2714   _dbus_assert (_dbus_string_get_length (&str) == 0);
2715   _dbus_assert (((int)strlen (s)) == i);
2716
2717   dbus_free (s);
2718
2719   /* Check move */
2720   
2721   if (!_dbus_string_append (&str, "Hello World"))
2722     _dbus_assert_not_reached ("could not append to string");
2723
2724   i = _dbus_string_get_length (&str);
2725
2726   if (!_dbus_string_init (&other, _DBUS_INT_MAX))
2727     _dbus_assert_not_reached ("could not init string");
2728   
2729   if (!_dbus_string_move (&str, 0, &other, 0))
2730     _dbus_assert_not_reached ("could not move");
2731
2732   _dbus_assert (_dbus_string_get_length (&str) == 0);
2733   _dbus_assert (_dbus_string_get_length (&other) == i);
2734
2735   if (!_dbus_string_append (&str, "Hello World"))
2736     _dbus_assert_not_reached ("could not append to string");
2737   
2738   if (!_dbus_string_move (&str, 0, &other, _dbus_string_get_length (&other)))
2739     _dbus_assert_not_reached ("could not move");
2740
2741   _dbus_assert (_dbus_string_get_length (&str) == 0);
2742   _dbus_assert (_dbus_string_get_length (&other) == i * 2);
2743
2744     if (!_dbus_string_append (&str, "Hello World"))
2745     _dbus_assert_not_reached ("could not append to string");
2746   
2747   if (!_dbus_string_move (&str, 0, &other, _dbus_string_get_length (&other) / 2))
2748     _dbus_assert_not_reached ("could not move");
2749
2750   _dbus_assert (_dbus_string_get_length (&str) == 0);
2751   _dbus_assert (_dbus_string_get_length (&other) == i * 3);
2752   
2753   _dbus_string_free (&other);
2754
2755   /* Check copy */
2756   
2757   if (!_dbus_string_append (&str, "Hello World"))
2758     _dbus_assert_not_reached ("could not append to string");
2759
2760   i = _dbus_string_get_length (&str);
2761   
2762   if (!_dbus_string_init (&other, _DBUS_INT_MAX))
2763     _dbus_assert_not_reached ("could not init string");
2764   
2765   if (!_dbus_string_copy (&str, 0, &other, 0))
2766     _dbus_assert_not_reached ("could not copy");
2767
2768   _dbus_assert (_dbus_string_get_length (&str) == i);
2769   _dbus_assert (_dbus_string_get_length (&other) == i);
2770
2771   if (!_dbus_string_copy (&str, 0, &other, _dbus_string_get_length (&other)))
2772     _dbus_assert_not_reached ("could not copy");
2773
2774   _dbus_assert (_dbus_string_get_length (&str) == i);
2775   _dbus_assert (_dbus_string_get_length (&other) == i * 2);
2776   _dbus_assert (_dbus_string_equal_c_str (&other,
2777                                           "Hello WorldHello World"));
2778
2779   if (!_dbus_string_copy (&str, 0, &other, _dbus_string_get_length (&other) / 2))
2780     _dbus_assert_not_reached ("could not copy");
2781
2782   _dbus_assert (_dbus_string_get_length (&str) == i);
2783   _dbus_assert (_dbus_string_get_length (&other) == i * 3);
2784   _dbus_assert (_dbus_string_equal_c_str (&other,
2785                                           "Hello WorldHello WorldHello World"));
2786   
2787   _dbus_string_free (&str);
2788   _dbus_string_free (&other);
2789
2790   /* Check replace */
2791
2792   if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2793     _dbus_assert_not_reached ("failed to init string");
2794   
2795   if (!_dbus_string_append (&str, "Hello World"))
2796     _dbus_assert_not_reached ("could not append to string");
2797
2798   i = _dbus_string_get_length (&str);
2799   
2800   if (!_dbus_string_init (&other, _DBUS_INT_MAX))
2801     _dbus_assert_not_reached ("could not init string");
2802   
2803   if (!_dbus_string_replace_len (&str, 0, _dbus_string_get_length (&str),
2804                                  &other, 0, _dbus_string_get_length (&other)))
2805     _dbus_assert_not_reached ("could not replace");
2806
2807   _dbus_assert (_dbus_string_get_length (&str) == i);
2808   _dbus_assert (_dbus_string_get_length (&other) == i);
2809   _dbus_assert (_dbus_string_equal_c_str (&other, "Hello World"));
2810   
2811   if (!_dbus_string_replace_len (&str, 0, _dbus_string_get_length (&str),
2812                                  &other, 5, 1))
2813     _dbus_assert_not_reached ("could not replace center space");
2814
2815   _dbus_assert (_dbus_string_get_length (&str) == i);
2816   _dbus_assert (_dbus_string_get_length (&other) == i * 2 - 1);
2817   _dbus_assert (_dbus_string_equal_c_str (&other,
2818                                           "HelloHello WorldWorld"));
2819
2820   
2821   if (!_dbus_string_replace_len (&str, 1, 1,
2822                                  &other,
2823                                  _dbus_string_get_length (&other) - 1,
2824                                  1))
2825     _dbus_assert_not_reached ("could not replace end character");
2826   
2827   _dbus_assert (_dbus_string_get_length (&str) == i);
2828   _dbus_assert (_dbus_string_get_length (&other) == i * 2 - 1);
2829   _dbus_assert (_dbus_string_equal_c_str (&other,
2830                                           "HelloHello WorldWorle"));
2831   
2832   _dbus_string_free (&str);
2833   _dbus_string_free (&other);
2834   
2835   /* Check append/get unichar */
2836   
2837   if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2838     _dbus_assert_not_reached ("failed to init string");
2839
2840   ch = 0;
2841   if (!_dbus_string_append_unichar (&str, 0xfffc))
2842     _dbus_assert_not_reached ("failed to append unichar");
2843
2844   _dbus_string_get_unichar (&str, 0, &ch, &i);
2845
2846   _dbus_assert (ch == 0xfffc);
2847   _dbus_assert (i == _dbus_string_get_length (&str));
2848
2849   _dbus_string_free (&str);
2850
2851   /* Check insert/set/get byte */
2852   
2853   if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2854     _dbus_assert_not_reached ("failed to init string");
2855
2856   if (!_dbus_string_append (&str, "Hello"))
2857     _dbus_assert_not_reached ("failed to append Hello");
2858
2859   _dbus_assert (_dbus_string_get_byte (&str, 0) == 'H');
2860   _dbus_assert (_dbus_string_get_byte (&str, 1) == 'e');
2861   _dbus_assert (_dbus_string_get_byte (&str, 2) == 'l');
2862   _dbus_assert (_dbus_string_get_byte (&str, 3) == 'l');
2863   _dbus_assert (_dbus_string_get_byte (&str, 4) == 'o');
2864
2865   _dbus_string_set_byte (&str, 1, 'q');
2866   _dbus_assert (_dbus_string_get_byte (&str, 1) == 'q');
2867
2868   if (!_dbus_string_insert_byte (&str, 0, 255))
2869     _dbus_assert_not_reached ("can't insert byte");
2870
2871   if (!_dbus_string_insert_byte (&str, 2, 'Z'))
2872     _dbus_assert_not_reached ("can't insert byte");
2873
2874   if (!_dbus_string_insert_byte (&str, _dbus_string_get_length (&str), 'W'))
2875     _dbus_assert_not_reached ("can't insert byte");
2876   
2877   _dbus_assert (_dbus_string_get_byte (&str, 0) == 255);
2878   _dbus_assert (_dbus_string_get_byte (&str, 1) == 'H');
2879   _dbus_assert (_dbus_string_get_byte (&str, 2) == 'Z');
2880   _dbus_assert (_dbus_string_get_byte (&str, 3) == 'q');
2881   _dbus_assert (_dbus_string_get_byte (&str, 4) == 'l');
2882   _dbus_assert (_dbus_string_get_byte (&str, 5) == 'l');
2883   _dbus_assert (_dbus_string_get_byte (&str, 6) == 'o');
2884   _dbus_assert (_dbus_string_get_byte (&str, 7) == 'W');
2885
2886   _dbus_string_free (&str);
2887   
2888   /* Check append/parse int/double */
2889   
2890   if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2891     _dbus_assert_not_reached ("failed to init string");
2892
2893   if (!_dbus_string_append_int (&str, 27))
2894     _dbus_assert_not_reached ("failed to append int");
2895
2896   i = _dbus_string_get_length (&str);
2897
2898   if (!_dbus_string_parse_int (&str, 0, &v, &end))
2899     _dbus_assert_not_reached ("failed to parse int");
2900
2901   _dbus_assert (v == 27);
2902   _dbus_assert (end == i);
2903
2904   _dbus_string_free (&str);
2905   
2906   if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2907     _dbus_assert_not_reached ("failed to init string");
2908   
2909   if (!_dbus_string_append_double (&str, 50.3))
2910     _dbus_assert_not_reached ("failed to append float");
2911
2912   i = _dbus_string_get_length (&str);
2913
2914   if (!_dbus_string_parse_double (&str, 0, &d, &end))
2915     _dbus_assert_not_reached ("failed to parse float");
2916
2917   _dbus_assert (d > (50.3 - 1e-6) && d < (50.3 + 1e-6));
2918   _dbus_assert (end == i);
2919
2920   _dbus_string_free (&str);
2921
2922   /* Test find */
2923   if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2924     _dbus_assert_not_reached ("failed to init string");
2925
2926   if (!_dbus_string_append (&str, "Hello"))
2927     _dbus_assert_not_reached ("couldn't append to string");
2928   
2929   if (!_dbus_string_find (&str, 0, "He", &i))
2930     _dbus_assert_not_reached ("didn't find 'He'");
2931   _dbus_assert (i == 0);
2932
2933   if (!_dbus_string_find (&str, 0, "Hello", &i))
2934     _dbus_assert_not_reached ("didn't find 'Hello'");
2935   _dbus_assert (i == 0);
2936   
2937   if (!_dbus_string_find (&str, 0, "ello", &i))
2938     _dbus_assert_not_reached ("didn't find 'ello'");
2939   _dbus_assert (i == 1);
2940
2941   if (!_dbus_string_find (&str, 0, "lo", &i))
2942     _dbus_assert_not_reached ("didn't find 'lo'");
2943   _dbus_assert (i == 3);
2944
2945   if (!_dbus_string_find (&str, 2, "lo", &i))
2946     _dbus_assert_not_reached ("didn't find 'lo'");
2947   _dbus_assert (i == 3);
2948
2949   if (_dbus_string_find (&str, 4, "lo", &i))
2950     _dbus_assert_not_reached ("did find 'lo'");
2951   
2952   if (!_dbus_string_find (&str, 0, "l", &i))
2953     _dbus_assert_not_reached ("didn't find 'l'");
2954   _dbus_assert (i == 2);
2955
2956   if (!_dbus_string_find (&str, 0, "H", &i))
2957     _dbus_assert_not_reached ("didn't find 'H'");
2958   _dbus_assert (i == 0);
2959
2960   if (!_dbus_string_find (&str, 0, "", &i))
2961     _dbus_assert_not_reached ("didn't find ''");
2962   _dbus_assert (i == 0);
2963   
2964   if (_dbus_string_find (&str, 0, "Hello!", NULL))
2965     _dbus_assert_not_reached ("Did find 'Hello!'");
2966
2967   if (_dbus_string_find (&str, 0, "Oh, Hello", NULL))
2968     _dbus_assert_not_reached ("Did find 'Oh, Hello'");
2969   
2970   if (_dbus_string_find (&str, 0, "ill", NULL))
2971     _dbus_assert_not_reached ("Did find 'ill'");
2972
2973   if (_dbus_string_find (&str, 0, "q", NULL))
2974     _dbus_assert_not_reached ("Did find 'q'");
2975
2976   if (!_dbus_string_find_to (&str, 0, 2, "He", NULL))
2977     _dbus_assert_not_reached ("Didn't find 'He'");
2978
2979   if (_dbus_string_find_to (&str, 0, 2, "Hello", NULL))
2980     _dbus_assert_not_reached ("Did find 'Hello'");
2981   
2982   _dbus_string_free (&str);
2983
2984   /* Base 64 and Hex encoding */
2985   test_roundtrips (test_base64_roundtrip);
2986   test_roundtrips (test_hex_roundtrip);
2987   
2988   return TRUE;
2989 }
2990
2991 #endif /* DBUS_BUILD_TESTS */