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