5a918617ee27a5a97ed98fddfd30f1a9e219bbed
[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  Red Hat, Inc.
5  *
6  * Licensed under the Academic Free License version 1.2
7  * 
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  * 
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *
22  */
23
24 #include "dbus-internals.h"
25 #include "dbus-string.h"
26 /* we allow a system header here, for speed/convenience */
27 #include <string.h>
28
29 /**
30  * @defgroup DBusString string class
31  * @ingroup  DBusInternals
32  * @brief DBusString data structure
33  *
34  * Types and functions related to DBusString. DBusString is intended
35  * to be a string class that makes it hard to mess up security issues
36  * (and just in general harder to write buggy code).  It should be
37  * used (or extended and then used) rather than the libc stuff in
38  * string.h.  The string class is a bit inconvenient at spots because
39  * it handles out-of-memory failures and tries to be extra-robust.
40  * 
41  * A DBusString has a maximum length set at initialization time; this
42  * can be used to ensure that a buffer doesn't get too big.  The
43  * _dbus_string_lengthen() method checks for overflow, and for max
44  * length being exceeded.
45  * 
46  * Try to avoid conversion to a plain C string, i.e. add methods on
47  * the string object instead, only convert to C string when passing
48  * things out to the public API. In particular, no sprintf, strcpy,
49  * strcat, any of that should be used. The GString feature of
50  * accepting negative numbers for "length of string" is also absent,
51  * because it could keep us from detecting bogus huge lengths. i.e. if
52  * we passed in some bogus huge length it would be taken to mean
53  * "current length of string" instead of "broken crack"
54  */
55
56 /**
57  * @defgroup DBusStringInternals DBusString implementation details
58  * @ingroup  DBusInternals
59  * @brief DBusString implementation details
60  *
61  * The guts of DBusString.
62  *
63  * @{
64  */
65
66 /**
67  * @brief Internals of DBusString.
68  * 
69  * DBusString internals. DBusString is an opaque objects, it must be
70  * used via accessor functions.
71  */
72 typedef struct
73 {
74   unsigned char *str;            /**< String data, plus nul termination */
75   int            len;            /**< Length without nul */
76   int            allocated;      /**< Allocated size of data */
77   int            max_length;     /**< Max length of this string. */
78   unsigned int   constant : 1;   /**< String data is not owned by DBusString */
79   unsigned int   locked : 1;     /**< DBusString has been locked and can't be changed */
80   unsigned int   invalid : 1;    /**< DBusString is invalid (e.g. already freed) */
81 } DBusRealString;
82
83 /**
84  * Checks a bunch of assertions about a string object
85  *
86  * @param real the DBusRealString
87  */
88 #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); _dbus_assert ((real)->len <= (real)->max_length)
89
90 /**
91  * Checks assertions about a string object that needs to be
92  * modifiable - may not be locked or const. Also declares
93  * the "real" variable pointing to DBusRealString. 
94  * @param str the string
95  */
96 #define DBUS_STRING_PREAMBLE(str) DBusRealString *real = (DBusRealString*) str; \
97   DBUS_GENERIC_STRING_PREAMBLE (real);                                          \
98   _dbus_assert (!(real)->constant);                                             \
99   _dbus_assert (!(real)->locked)
100
101 /**
102  * Checks assertions about a string object that may be locked but
103  * can't be const. i.e. a string object that we can free.  Also
104  * declares the "real" variable pointing to DBusRealString.
105  *
106  * @param str the string
107  */
108 #define DBUS_LOCKED_STRING_PREAMBLE(str) DBusRealString *real = (DBusRealString*) str; \
109   DBUS_GENERIC_STRING_PREAMBLE (real);                                                 \
110   _dbus_assert (!(real)->constant)
111
112 /**
113  * Checks assertions about a string that may be const or locked.  Also
114  * declares the "real" variable pointing to DBusRealString.
115  * @param str the string.
116  */
117 #define DBUS_CONST_STRING_PREAMBLE(str) const DBusRealString *real = (DBusRealString*) str; \
118   DBUS_GENERIC_STRING_PREAMBLE (real)
119
120 /** @} */
121
122 /**
123  * @addtogroup DBusString
124  * @{
125  */
126
127 /** Assert that the string's memory is 8-byte aligned.
128  *
129  *  @todo Currently we just hope libc returns 8-byte aligned memory
130  *  (which is true for GNU libc), but really we need to ensure it by
131  *  allocating 8 extra bytes and keeping an "align_offset : 3" field
132  *  in DBusString, or something along those lines.
133  */
134 #define ASSERT_8_BYTE_ALIGNED(s) \
135   _dbus_assert (_DBUS_ALIGN_ADDRESS (((const DBusRealString*)s)->str, 8) == ((const DBusRealString*)s)->str)
136
137 /**
138  * Initializes a string. The maximum length may be _DBUS_INT_MAX for
139  * no maximum. The string starts life with zero length.
140  * The string must eventually be freed with _dbus_string_free().
141  *
142  * @param str memory to hold the string
143  * @param max_length the maximum size of the string
144  * @returns #TRUE on success
145  */
146 dbus_bool_t
147 _dbus_string_init (DBusString *str,
148                    int         max_length)
149 {
150   DBusRealString *real;
151   
152   _dbus_assert (str != NULL);
153   _dbus_assert (max_length >= 0);
154
155   _dbus_assert (sizeof (DBusString) == sizeof (DBusRealString));
156   
157   real = (DBusRealString*) str;
158
159   /* It's very important not to touch anything
160    * other than real->str if we're going to fail,
161    * since we also use this function to reset
162    * an existing string, e.g. in _dbus_string_steal_data()
163    */
164   
165 #define INITIAL_ALLOC 2
166   
167   real->str = dbus_malloc (INITIAL_ALLOC);
168   if (real->str == NULL)
169     return FALSE;  
170   
171   real->allocated = INITIAL_ALLOC;
172   real->len = 0;
173   real->str[real->len] = '\0';
174   
175   real->max_length = max_length;
176   real->constant = FALSE;
177   real->locked = FALSE;
178   real->invalid = FALSE;
179
180   ASSERT_8_BYTE_ALIGNED (str);
181   
182   return TRUE;
183 }
184
185 /**
186  * Initializes a constant string. The value parameter is not copied
187  * (should be static), and the string may never be modified.
188  * It is safe but not necessary to call _dbus_string_free()
189  * on a const string.
190  * 
191  * @param str memory to use for the string
192  * @param value a string to be stored in str (not copied!!!)
193  */
194 void
195 _dbus_string_init_const (DBusString *str,
196                          const char *value)
197 {
198   DBusRealString *real;
199   
200   _dbus_assert (str != NULL);
201   _dbus_assert (value != NULL);
202
203   real = (DBusRealString*) str;
204   
205   real->str = (char*) value;
206   real->len = strlen (real->str);
207   real->allocated = real->len;
208   real->max_length = real->len;
209   real->constant = TRUE;
210   real->invalid = FALSE;
211
212   /* We don't require const strings to be 8-byte aligned as the
213    * memory is coming from elsewhere.
214    */
215 }
216
217 /**
218  * Frees a string created by _dbus_string_init().
219  *
220  * @param str memory where the string is stored.
221  */
222 void
223 _dbus_string_free (DBusString *str)
224 {
225   DBUS_LOCKED_STRING_PREAMBLE (str);
226   
227   if (real->constant)
228     return;
229   
230   dbus_free (real->str);
231
232   real->invalid = TRUE;
233 }
234
235 /**
236  * Locks a string such that any attempts to change the string
237  * will result in aborting the program. Also, if the string
238  * is wasting a lot of memory (allocation is larger than what
239  * the string is really using), _dbus_string_lock() will realloc
240  * the string's data to "compact" it.
241  *
242  * @param str the string to lock.
243  */
244 void
245 _dbus_string_lock (DBusString *str)
246 {  
247   DBUS_LOCKED_STRING_PREAMBLE (str); /* can lock multiple times */
248
249   real->locked = TRUE;
250
251   /* Try to realloc to avoid excess memory usage, since
252    * we know we won't change the string further
253    */
254 #define MAX_WASTE 24
255   if (real->allocated > (real->len + MAX_WASTE))
256     {
257       char *new_str;
258       int new_allocated;
259
260       new_allocated = real->len + 1;
261
262       new_str = dbus_realloc (real->str, new_allocated);
263       if (new_str != NULL)
264         {
265           real->str = new_str;
266           real->allocated = new_allocated;
267           ASSERT_8_BYTE_ALIGNED (str);
268         }
269     }
270 }
271
272 /**
273  * Gets the raw character buffer from the string.  The returned buffer
274  * will be nul-terminated, but note that strings may contain binary
275  * data so there may be extra nul characters prior to the termination.
276  * This function should be little-used, extend DBusString or add
277  * stuff to dbus-sysdeps.c instead. It's an error to use this
278  * function on a const string.
279  *
280  * @param str the string
281  * @param data_return place to store the returned data
282  */
283 void
284 _dbus_string_get_data (DBusString        *str,
285                        char             **data_return)
286 {
287   DBUS_STRING_PREAMBLE (str);
288   _dbus_assert (data_return != NULL);
289   
290   *data_return = real->str;
291 }
292
293 /**
294  * Gets the raw character buffer from a const string. 
295  *
296  * @param str the string
297  * @param data_return location to store returned data
298  */
299 void
300 _dbus_string_get_const_data (const DBusString  *str,
301                              const char       **data_return)
302 {
303   DBUS_CONST_STRING_PREAMBLE (str);
304   _dbus_assert (data_return != NULL);
305   
306   *data_return = real->str;
307 }
308
309 /**
310  * Gets a sub-portion of the raw character buffer from the
311  * string. The "len" field is required simply for error
312  * checking, to be sure you don't try to use more
313  * string than exists. The nul termination of the
314  * returned buffer remains at the end of the entire
315  * string, not at start + len.
316  *
317  * @param str the string
318  * @param data_return location to return the buffer
319  * @param start byte offset to return
320  * @param len length of segment to return
321  */
322 void
323 _dbus_string_get_data_len (DBusString *str,
324                            char      **data_return,
325                            int         start,
326                            int         len)
327 {
328   DBUS_STRING_PREAMBLE (str);
329   _dbus_assert (data_return != NULL);
330   _dbus_assert (start >= 0);
331   _dbus_assert (len >= 0);
332   _dbus_assert ((start + len) <= real->len);
333   
334   *data_return = real->str + start;
335 }
336
337 /**
338  * const version of _dbus_string_get_data_len().
339  *
340  * @param str the string
341  * @param data_return location to return the buffer
342  * @param start byte offset to return
343  * @param len length of segment to return
344  */
345 void
346 _dbus_string_get_const_data_len (const DBusString  *str,
347                                  const char       **data_return,
348                                  int                start,
349                                  int                len)
350 {
351   DBUS_CONST_STRING_PREAMBLE (str);
352   _dbus_assert (data_return != NULL);
353   _dbus_assert (start >= 0);
354   _dbus_assert (len >= 0);
355   _dbus_assert ((start + len) <= real->len);
356   
357   *data_return = real->str + start;
358 }
359
360 /**
361  * Like _dbus_string_get_data(), but removes the
362  * gotten data from the original string. The caller
363  * must free the data returned. This function may
364  * fail due to lack of memory, and return #FALSE.
365  *
366  * @param str the string
367  * @param data_return location to return the buffer
368  * @returns #TRUE on success
369  */
370 dbus_bool_t
371 _dbus_string_steal_data (DBusString        *str,
372                          char             **data_return)
373 {
374   DBUS_STRING_PREAMBLE (str);
375   _dbus_assert (data_return != NULL);
376   
377   *data_return = real->str;
378
379   /* reset the string */
380   if (!_dbus_string_init (str, real->max_length))
381     {
382       /* hrm, put it back then */
383       real->str = *data_return;
384       *data_return = NULL;
385       return FALSE;
386     }
387
388   return TRUE;
389 }
390
391 /**
392  * Like _dbus_string_get_data_len(), but removes the gotten data from
393  * the original string. The caller must free the data returned. This
394  * function may fail due to lack of memory, and return #FALSE.
395  * The returned string is nul-terminated and has length len.
396  *
397  * @param str the string
398  * @param data_return location to return the buffer
399  * @param start the start of segment to steal
400  * @param len the length of segment to steal
401  * @returns #TRUE on success
402  */
403 dbus_bool_t
404 _dbus_string_steal_data_len (DBusString        *str,
405                              char             **data_return,
406                              int                start,
407                              int                len)
408 {
409   DBusString dest;
410   
411   DBUS_STRING_PREAMBLE (str);
412   _dbus_assert (data_return != NULL);
413   _dbus_assert (start >= 0);
414   _dbus_assert (len >= 0);
415   _dbus_assert ((start + len) <= real->len);
416
417   if (!_dbus_string_init (&dest, real->max_length))
418     return FALSE;
419
420   if (!_dbus_string_move_len (str, start, len, &dest, 0))
421     {
422       _dbus_string_free (&dest);
423       return FALSE;
424     }
425   
426   if (!_dbus_string_steal_data (&dest, data_return))
427     {
428       _dbus_string_free (&dest);
429       return FALSE;
430     }
431
432   _dbus_string_free (&dest);
433   return TRUE;
434 }
435
436 /**
437  * Gets the length of a string (not including nul termination).
438  *
439  * @returns the length.
440  */
441 int
442 _dbus_string_get_length (const DBusString  *str)
443 {
444   DBUS_CONST_STRING_PREAMBLE (str);
445   
446   return real->len;
447 }
448
449 static dbus_bool_t
450 set_length (DBusRealString *real,
451             int             new_length)
452 {
453   /* Note, we are setting the length without nul termination */
454
455   /* exceeding max length is the same as failure to allocate memory */
456   if (new_length > real->max_length)
457     return FALSE;
458   
459   while (new_length >= real->allocated)
460     {
461       int new_allocated;
462       char *new_str;
463       
464       new_allocated = 2 + real->allocated * 2;
465       if (new_allocated < real->allocated)
466         return FALSE; /* overflow */
467         
468       new_str = dbus_realloc (real->str, new_allocated);
469       if (new_str == NULL)
470         return FALSE;
471
472       real->str = new_str;
473       real->allocated = new_allocated;
474
475       ASSERT_8_BYTE_ALIGNED (real);
476     }
477
478   real->len = new_length;
479   real->str[real->len] = '\0';
480
481   return TRUE;
482 }
483
484 /**
485  * Makes a string longer by the given number of bytes.  Checks whether
486  * adding additional_length to the current length would overflow an
487  * integer, and checks for exceeding a string's max length.
488  * The new bytes are not initialized, other than nul-terminating
489  * the end of the string. The uninitialized bytes may contain
490  * unexpected nul bytes or other junk.
491  *
492  * @param str a string
493  * @param additional_length length to add to the string.
494  * @returns #TRUE on success.
495  */
496 dbus_bool_t
497 _dbus_string_lengthen (DBusString *str,
498                        int         additional_length)
499 {
500   DBUS_STRING_PREAMBLE (str);  
501   _dbus_assert (additional_length >= 0);
502   
503   if ((real->len + additional_length) < real->len)
504     return FALSE; /* overflow */
505   
506   return set_length (real,
507                      real->len + additional_length);
508 }
509
510 /**
511  * Makes a string shorter by the given number of bytes.
512  *
513  * @param str a string
514  * @param length_to_remove length to remove from the string.
515  */
516 void
517 _dbus_string_shorten (DBusString *str,
518                       int         length_to_remove)
519 {
520   DBUS_STRING_PREAMBLE (str);
521   _dbus_assert (length_to_remove >= 0);
522   _dbus_assert (length_to_remove <= real->len);
523
524   set_length (real,
525               real->len - length_to_remove);
526 }
527
528 /**
529  * Sets the length of a string. Can be used to truncate or lengthen
530  * the string. If the string is lengthened, the function may fail and
531  * return #FALSE. Newly-added bytes are not initialized, as with
532  * _dbus_string_lengthen().
533  *
534  * @param str a string
535  * @param length new length of the string.
536  * @returns #FALSE on failure.
537  */
538 dbus_bool_t
539 _dbus_string_set_length (DBusString *str,
540                          int         length)
541 {
542   DBUS_STRING_PREAMBLE (str);
543   _dbus_assert (length >= 0);
544
545   return set_length (real, length);
546 }
547
548 /**
549  * Align the length of a string to a specific alignment (typically 4 or 8)
550  * by appending nul bytes to the string.
551  *
552  * @param str a string
553  * @param alignment the alignment
554  * @returns #FALSE if no memory
555  */
556 dbus_bool_t
557 _dbus_string_align_length (DBusString *str,
558                            int         alignment)
559 {
560   int new_len;
561   int delta;
562   DBUS_STRING_PREAMBLE (str);
563   _dbus_assert (alignment >= 1);
564   _dbus_assert (alignment <= 16); /* arbitrary */
565
566   new_len = _DBUS_ALIGN_VALUE (real->len, alignment);
567
568   delta = new_len - real->len;
569   _dbus_assert (delta >= 0);
570
571   if (delta == 0)
572     return TRUE;
573
574   if (!set_length (real, new_len))
575     return FALSE;
576
577   memset (real->str + (new_len - delta),
578           '\0', delta);
579
580   return TRUE;
581 }
582
583 static dbus_bool_t
584 append (DBusRealString *real,
585         const char     *buffer,
586         int             buffer_len)
587 {
588   if (buffer_len == 0)
589     return TRUE;
590
591   if (!_dbus_string_lengthen ((DBusString*)real, buffer_len))
592     return FALSE;
593
594   memcpy (real->str + (real->len - buffer_len),
595           buffer,
596           buffer_len);
597
598   return TRUE;
599 }
600
601 /**
602  * Appends a nul-terminated C-style string to a DBusString.
603  *
604  * @param str the DBusString
605  * @param buffer the nul-terminated characters to append
606  * @returns #FALSE if not enough memory.
607  */
608 dbus_bool_t
609 _dbus_string_append (DBusString *str,
610                      const char *buffer)
611 {
612   int buffer_len;
613   
614   DBUS_STRING_PREAMBLE (str);
615   _dbus_assert (buffer != NULL);
616   
617   buffer_len = strlen (buffer);
618
619   return append (real, buffer, buffer_len);
620 }
621
622 /**
623  * Appends block of bytes with the given length to a DBusString.
624  *
625  * @param str the DBusString
626  * @param buffer the bytes to append
627  * @param len the number of bytes to append
628  * @returns #FALSE if not enough memory.
629  */
630 dbus_bool_t
631 _dbus_string_append_len (DBusString *str,
632                          const char *buffer,
633                          int         len)
634 {
635   DBUS_STRING_PREAMBLE (str);
636   _dbus_assert (buffer != NULL);
637   _dbus_assert (len >= 0);
638
639   return append (real, buffer, len);
640 }
641
642 /**
643  * Appends a single byte to the string, returning #FALSE
644  * if not enough memory.
645  *
646  * @param str the string
647  * @param byte the byte to append
648  * @returns #TRUE on success
649  */
650 dbus_bool_t
651 _dbus_string_append_byte (DBusString    *str,
652                           unsigned char  byte)
653 {
654   DBUS_STRING_PREAMBLE (str);
655
656   if (!set_length (real, real->len + 1))
657     return FALSE;
658
659   real->str[real->len-1] = byte;
660
661   return TRUE;
662 }
663
664 /**
665  * Appends a single Unicode character, encoding the character
666  * in UTF-8 format.
667  *
668  * @param str the string
669  * @param ch the Unicode character
670  */
671 dbus_bool_t
672 _dbus_string_append_unichar (DBusString    *str,
673                              dbus_unichar_t ch)
674 {
675   int len;
676   int first;
677   int i;
678   char *out;
679   
680   DBUS_STRING_PREAMBLE (str);
681
682   /* this code is from GLib but is pretty standard I think */
683   
684   len = 0;
685   
686   if (ch < 0x80)
687     {
688       first = 0;
689       len = 1;
690     }
691   else if (ch < 0x800)
692     {
693       first = 0xc0;
694       len = 2;
695     }
696   else if (ch < 0x10000)
697     {
698       first = 0xe0;
699       len = 3;
700     }
701    else if (ch < 0x200000)
702     {
703       first = 0xf0;
704       len = 4;
705     }
706   else if (ch < 0x4000000)
707     {
708       first = 0xf8;
709       len = 5;
710     }
711   else
712     {
713       first = 0xfc;
714       len = 6;
715     }
716
717   if (!set_length (real, real->len + len))
718     return FALSE;
719
720   out = real->str + (real->len - len);
721   
722   for (i = len - 1; i > 0; --i)
723     {
724       out[i] = (ch & 0x3f) | 0x80;
725       ch >>= 6;
726     }
727   out[0] = ch | first;
728
729   return TRUE;
730 }
731
732 static void
733 delete (DBusRealString *real,
734         int             start,
735         int             len)
736 {
737   if (len == 0)
738     return;
739   
740   memmove (real->str + start, real->str + start + len, real->len - (start + len));
741   real->len -= len;
742   real->str[real->len] = '\0';
743 }
744
745 /**
746  * Deletes a segment of a DBusString with length len starting at
747  * start. (Hint: to clear an entire string, setting length to 0
748  * with _dbus_string_set_length() is easier.)
749  *
750  * @param str the DBusString
751  * @param start where to start deleting
752  * @param len the number of bytes to delete
753  */
754 void
755 _dbus_string_delete (DBusString       *str,
756                      int               start,
757                      int               len)
758 {
759   DBUS_STRING_PREAMBLE (str);
760   _dbus_assert (start >= 0);
761   _dbus_assert (len >= 0);
762   _dbus_assert ((start + len) <= real->len);
763
764   delete (real, start, len);
765 }
766
767 static dbus_bool_t
768 open_gap (int             len,
769           DBusRealString *dest,
770           int             insert_at)
771 {
772   if (len == 0)
773     return TRUE;
774
775   if (!set_length (dest, dest->len + len))
776     return FALSE;
777
778   memmove (dest->str + insert_at + len, 
779            dest->str + insert_at,
780            dest->len - len - insert_at);
781
782   return TRUE;
783 }
784
785 static dbus_bool_t
786 copy (DBusRealString *source,
787       int             start,
788       int             len,
789       DBusRealString *dest,
790       int             insert_at)
791 {
792   if (!open_gap (len, dest, insert_at))
793     return FALSE;
794     
795   memcpy (dest->str + insert_at,
796           source->str + start,
797           len);
798
799   return TRUE;
800 }
801
802 /**
803  * Checks assertions for two strings we're copying a segment between,
804  * and declares real_source/real_dest variables.
805  *
806  * @param source the source string
807  * @param start the starting offset
808  * @param dest the dest string
809  * @param insert_at where the copied segment is inserted
810  */
811 #define DBUS_STRING_COPY_PREAMBLE(source, start, dest, insert_at)       \
812   DBusRealString *real_source = (DBusRealString*) source;               \
813   DBusRealString *real_dest = (DBusRealString*) dest;                   \
814   _dbus_assert ((source) != (dest));                                    \
815   DBUS_GENERIC_STRING_PREAMBLE (real_source);                           \
816   DBUS_GENERIC_STRING_PREAMBLE (real_dest);                             \
817   _dbus_assert (!real_source->constant);                                \
818   _dbus_assert (!real_source->locked);                                  \
819   _dbus_assert (!real_dest->constant);                                  \
820   _dbus_assert (!real_dest->locked);                                    \
821   _dbus_assert ((start) >= 0);                                          \
822   _dbus_assert ((start) <= real_source->len);                           \
823   _dbus_assert ((insert_at) >= 0);                                      \
824   _dbus_assert ((insert_at) <= real_dest->len)
825
826 /**
827  * Moves the end of one string into another string. Both strings
828  * must be initialized, valid strings.
829  *
830  * @param source the source string
831  * @param start where to chop off the source string
832  * @param dest the destination string
833  * @param insert_at where to move the chopped-off part of source string
834  * @returns #FALSE if not enough memory
835  */
836 dbus_bool_t
837 _dbus_string_move (DBusString       *source,
838                    int               start,
839                    DBusString       *dest,
840                    int               insert_at)
841 {
842   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
843   
844   if (!copy (real_source, start,
845              real_source->len - start,
846              real_dest,
847              insert_at))
848     return FALSE;
849
850   delete (real_source, start,
851           real_source->len - start);
852
853   return TRUE;
854 }
855
856 /**
857  * Like _dbus_string_move(), but does not delete the section
858  * of the source string that's copied to the dest string.
859  *
860  * @param source the source string
861  * @param start where to start copying the source string
862  * @param dest the destination string
863  * @param insert_at where to place the copied part of source string
864  * @returns #FALSE if not enough memory
865  */
866 dbus_bool_t
867 _dbus_string_copy (const DBusString *source,
868                    int               start,
869                    DBusString       *dest,
870                    int               insert_at)
871 {
872   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
873
874   return copy (real_source, start,
875                real_source->len - start,
876                real_dest,
877                insert_at);
878 }
879
880 /**
881  * Like _dbus_string_move(), but can move a segment from
882  * the middle of the source string.
883  * 
884  * @param source the source string
885  * @param start first byte of source string to move
886  * @param len length of segment to move
887  * @param dest the destination string
888  * @param insert_at where to move the bytes from the source string
889  * @returns #FALSE if not enough memory
890  */
891 dbus_bool_t
892 _dbus_string_move_len (DBusString       *source,
893                        int               start,
894                        int               len,
895                        DBusString       *dest,
896                        int               insert_at)
897
898 {
899   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
900   _dbus_assert (len >= 0);
901   _dbus_assert ((start + len) <= real_source->len);
902
903   if (!copy (real_source, start, len,
904              real_dest,
905              insert_at))
906     return FALSE;
907
908   delete (real_source, start,
909           real_source->len - start);
910
911   return TRUE;
912 }
913
914 /**
915  * Like _dbus_string_copy(), but can copy a segment from the middle of
916  * the source string.
917  *
918  * @param source the source string
919  * @param start where to start copying the source string
920  * @param len length of segment to copy
921  * @param dest the destination string
922  * @param insert_at where to place the copied segment of source string
923  * @returns #FALSE if not enough memory
924  */
925 dbus_bool_t
926 _dbus_string_copy_len (const DBusString *source,
927                        int               start,
928                        int               len,
929                        DBusString       *dest,
930                        int               insert_at)
931 {
932   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
933   _dbus_assert (len >= 0);
934   _dbus_assert ((start + len) <= real_source->len);
935   
936   return copy (real_source, start, len,
937                real_dest,
938                insert_at);
939 }
940
941 /* Unicode macros from GLib */
942
943 /** computes length and mask of a unicode character
944  * @param Char the char
945  * @param Mask the mask variable to assign to
946  * @param Len the length variable to assign to
947  */
948 #define UTF8_COMPUTE(Char, Mask, Len)                                         \
949   if (Char < 128)                                                             \
950     {                                                                         \
951       Len = 1;                                                                \
952       Mask = 0x7f;                                                            \
953     }                                                                         \
954   else if ((Char & 0xe0) == 0xc0)                                             \
955     {                                                                         \
956       Len = 2;                                                                \
957       Mask = 0x1f;                                                            \
958     }                                                                         \
959   else if ((Char & 0xf0) == 0xe0)                                             \
960     {                                                                         \
961       Len = 3;                                                                \
962       Mask = 0x0f;                                                            \
963     }                                                                         \
964   else if ((Char & 0xf8) == 0xf0)                                             \
965     {                                                                         \
966       Len = 4;                                                                \
967       Mask = 0x07;                                                            \
968     }                                                                         \
969   else if ((Char & 0xfc) == 0xf8)                                             \
970     {                                                                         \
971       Len = 5;                                                                \
972       Mask = 0x03;                                                            \
973     }                                                                         \
974   else if ((Char & 0xfe) == 0xfc)                                             \
975     {                                                                         \
976       Len = 6;                                                                \
977       Mask = 0x01;                                                            \
978     }                                                                         \
979   else                                                                        \
980     Len = -1;
981
982 /**
983  * computes length of a unicode character in UTF-8
984  * @param Char the char
985  */
986 #define UTF8_LENGTH(Char)              \
987   ((Char) < 0x80 ? 1 :                 \
988    ((Char) < 0x800 ? 2 :               \
989     ((Char) < 0x10000 ? 3 :            \
990      ((Char) < 0x200000 ? 4 :          \
991       ((Char) < 0x4000000 ? 5 : 6)))))
992    
993 /**
994  * Gets a UTF-8 value.
995  *
996  * @param Result variable for extracted unicode char.
997  * @param Chars the bytes to decode
998  * @param Count counter variable
999  * @param Mask mask for this char
1000  * @param Len length for this char in bytes
1001  */
1002 #define UTF8_GET(Result, Chars, Count, Mask, Len)                             \
1003   (Result) = (Chars)[0] & (Mask);                                             \
1004   for ((Count) = 1; (Count) < (Len); ++(Count))                               \
1005     {                                                                         \
1006       if (((Chars)[(Count)] & 0xc0) != 0x80)                                  \
1007         {                                                                     \
1008           (Result) = -1;                                                      \
1009           break;                                                              \
1010         }                                                                     \
1011       (Result) <<= 6;                                                         \
1012       (Result) |= ((Chars)[(Count)] & 0x3f);                                  \
1013     }
1014
1015 /**
1016  * Check whether a unicode char is in a valid range.
1017  *
1018  * @param Char the character
1019  */
1020 #define UNICODE_VALID(Char)                   \
1021     ((Char) < 0x110000 &&                     \
1022      ((Char) < 0xD800 || (Char) >= 0xE000) && \
1023      (Char) != 0xFFFE && (Char) != 0xFFFF)   
1024
1025 /**
1026  * Gets a unicode character from a UTF-8 string. Does no validation;
1027  * you must verify that the string is valid UTF-8 in advance and must
1028  * pass in the start of a character.
1029  *
1030  * @param str the string
1031  * @param start the start of the UTF-8 character.
1032  * @param ch_return location to return the character
1033  * @param end_return location to return the byte index of next character
1034  * @returns #TRUE on success, #FALSE otherwise.
1035  */
1036 void
1037 _dbus_string_get_unichar (const DBusString *str,
1038                           int               start,
1039                           dbus_unichar_t   *ch_return,
1040                           int              *end_return)
1041 {
1042   int i, mask, len;
1043   dbus_unichar_t result;
1044   unsigned char c;
1045   unsigned char *p;
1046   DBUS_CONST_STRING_PREAMBLE (str);
1047
1048   if (ch_return)
1049     *ch_return = 0;
1050   if (end_return)
1051     *end_return = real->len;
1052   
1053   mask = 0;
1054   p = real->str + start;
1055   c = *p;
1056   
1057   UTF8_COMPUTE (c, mask, len);
1058   if (len == -1)
1059     return;
1060   UTF8_GET (result, p, i, mask, len);
1061
1062   if (result == (dbus_unichar_t)-1)
1063     return;
1064
1065   if (ch_return)
1066     *ch_return = result;
1067   if (end_return)
1068     *end_return = start + len;
1069 }
1070
1071 /**
1072  * Finds the given substring in the string,
1073  * returning #TRUE and filling in the byte index
1074  * where the substring was found, if it was found.
1075  * Returns #FALSE if the substring wasn't found.
1076  * Sets *start to the length of the string if the substring
1077  * is not found.
1078  *
1079  * @param str the string
1080  * @param start where to start looking
1081  * @param substr the substring
1082  * @param found return location for where it was found, or #NULL
1083  * @returns #TRUE if found
1084  */
1085 dbus_bool_t
1086 _dbus_string_find (const DBusString *str,
1087                    int               start,
1088                    const char       *substr,
1089                    int              *found)
1090 {
1091   int i;
1092   DBUS_CONST_STRING_PREAMBLE (str);
1093   _dbus_assert (substr != NULL);
1094   _dbus_assert (start <= real->len);
1095   
1096   /* we always "find" an empty string */
1097   if (*substr == '\0')
1098     {
1099       if (found)
1100         *found = 0;
1101       return TRUE;
1102     }
1103   
1104   i = start;
1105   while (i < real->len)
1106     {
1107       if (real->str[i] == substr[0])
1108         {
1109           int j = i + 1;
1110           
1111           while (j < real->len)
1112             {
1113               if (substr[j - i] == '\0')
1114                 break;
1115               else if (real->str[j] != substr[j - i])
1116                 break;
1117               
1118               ++j;
1119             }
1120
1121           if (substr[j - i] == '\0')
1122             {
1123               if (found)
1124                 *found = i;
1125               return TRUE;
1126             }
1127         }
1128       
1129       ++i;
1130     }
1131
1132   if (found)
1133     *found = real->len;
1134   
1135   return FALSE;
1136 }
1137
1138 /**
1139  * Finds a blank (space or tab) in the string. Returns #TRUE
1140  * if found, #FALSE otherwise. If a blank is not found sets
1141  * *found to the length of the string.
1142  *
1143  * @param str the string
1144  * @param start byte index to start looking
1145  * @param found place to store the location of the first blank
1146  * @returns #TRUE if a blank was found
1147  */
1148 dbus_bool_t
1149 _dbus_string_find_blank (const DBusString *str,
1150                          int               start,
1151                          int              *found)
1152 {
1153   int i;
1154   DBUS_CONST_STRING_PREAMBLE (str);
1155   _dbus_assert (start <= real->len);
1156   
1157   i = start;
1158   while (i < real->len)
1159     {
1160       if (real->str[i] == ' ' ||
1161           real->str[i] == '\t')
1162         {
1163           if (found)
1164             *found = i;
1165           return TRUE;
1166         }
1167       
1168       ++i;
1169     }
1170
1171   if (found)
1172     *found = real->len;
1173   
1174   return FALSE;
1175 }
1176
1177 /**
1178  * Skips blanks from start, storing the first non-blank in *end
1179  *
1180  * @param str the string
1181  * @param start where to start
1182  * @param end where to store the first non-blank byte index
1183  */
1184 void
1185 _dbus_string_skip_blank (const DBusString *str,
1186                          int               start,
1187                          int              *end)
1188 {
1189   int i;
1190   DBUS_CONST_STRING_PREAMBLE (str);
1191   _dbus_assert (start <= real->len);
1192   
1193   i = start;
1194   while (i < real->len)
1195     {
1196       if (!(real->str[i] == ' ' ||
1197             real->str[i] == '\t'))
1198         break;
1199       
1200       ++i;
1201     }
1202
1203   _dbus_assert (i == real->len || !(real->str[i] == ' ' ||
1204                                     real->str[i] == '\t'));
1205   
1206   if (end)
1207     *end = i;
1208 }
1209
1210 /**
1211  * Tests two DBusString for equality.
1212  *
1213  * @param a first string
1214  * @param b second string
1215  * @returns #TRUE if equal
1216  */
1217 dbus_bool_t
1218 _dbus_string_equal (const DBusString *a,
1219                     const DBusString *b)
1220 {
1221   const unsigned char *ap;
1222   const unsigned char *bp;
1223   const unsigned char *a_end;
1224   const DBusRealString *real_a = (const DBusRealString*) a;
1225   const DBusRealString *real_b = (const DBusRealString*) b;
1226   DBUS_GENERIC_STRING_PREAMBLE (real_a);
1227   DBUS_GENERIC_STRING_PREAMBLE (real_b);
1228
1229   if (real_a->len != real_b->len)
1230     return FALSE;
1231
1232   ap = real_a->str;
1233   bp = real_b->str;
1234   a_end = real_a->str + real_a->len;
1235   while (ap != a_end)
1236     {
1237       if (*ap != *bp)
1238         return FALSE;
1239       
1240       ++ap;
1241       ++bp;
1242     }
1243
1244   return TRUE;
1245 }
1246
1247 /**
1248  * Checks whether a string is equal to a C string.
1249  *
1250  * @param a the string
1251  * @param c_str the C string
1252  * @returns #TRUE if equal
1253  */
1254 dbus_bool_t
1255 _dbus_string_equal_c_str (const DBusString *a,
1256                           const char       *c_str)
1257 {
1258   const unsigned char *ap;
1259   const unsigned char *bp;
1260   const unsigned char *a_end;
1261   const DBusRealString *real_a = (const DBusRealString*) a;
1262   DBUS_GENERIC_STRING_PREAMBLE (real_a);
1263
1264   ap = real_a->str;
1265   bp = (const unsigned char*) c_str;
1266   a_end = real_a->str + real_a->len;
1267   while (ap != a_end && *bp)
1268     {
1269       if (*ap != *bp)
1270         return FALSE;
1271       
1272       ++ap;
1273       ++bp;
1274     }
1275
1276   if (*ap && *bp == '\0')
1277     return FALSE;
1278   else if (ap == a_end && *bp)
1279     return FALSE;
1280   
1281   return TRUE;
1282 }
1283
1284 static const signed char base64_table[] = {
1285   /* 0 */ 'A',
1286   /* 1 */ 'B',
1287   /* 2 */ 'C',
1288   /* 3 */ 'D',
1289   /* 4 */ 'E',
1290   /* 5 */ 'F',
1291   /* 6 */ 'G',
1292   /* 7 */ 'H',
1293   /* 8 */ 'I',
1294   /* 9 */ 'J',
1295   /* 10 */ 'K',
1296   /* 11 */ 'L',
1297   /* 12 */ 'M',
1298   /* 13 */ 'N',
1299   /* 14 */ 'O',
1300   /* 15 */ 'P',
1301   /* 16 */ 'Q',
1302   /* 17 */ 'R',
1303   /* 18 */ 'S',
1304   /* 19 */ 'T',
1305   /* 20 */ 'U',
1306   /* 21 */ 'V',
1307   /* 22 */ 'W',
1308   /* 23 */ 'X',
1309   /* 24 */ 'Y',
1310   /* 25 */ 'Z',
1311   /* 26 */ 'a',
1312   /* 27 */ 'b',
1313   /* 28 */ 'c',
1314   /* 29 */ 'd',
1315   /* 30 */ 'e',
1316   /* 31 */ 'f',
1317   /* 32 */ 'g',
1318   /* 33 */ 'h',
1319   /* 34 */ 'i',
1320   /* 35 */ 'j',
1321   /* 36 */ 'k',
1322   /* 37 */ 'l',
1323   /* 38 */ 'm',
1324   /* 39 */ 'n',
1325   /* 40 */ 'o',
1326   /* 41 */ 'p',
1327   /* 42 */ 'q',
1328   /* 43 */ 'r',
1329   /* 44 */ 's',
1330   /* 45 */ 't',
1331   /* 46 */ 'u',
1332   /* 47 */ 'v',
1333   /* 48 */ 'w',
1334   /* 49 */ 'x',
1335   /* 50 */ 'y',
1336   /* 51 */ 'z',
1337   /* 52 */ '0',
1338   /* 53 */ '1',
1339   /* 54 */ '2',
1340   /* 55 */ '3',
1341   /* 56 */ '4',
1342   /* 57 */ '5',
1343   /* 58 */ '6',
1344   /* 59 */ '7',
1345   /* 60 */ '8',
1346   /* 61 */ '9',
1347   /* 62 */ '+',
1348   /* 63 */ '/'
1349 };
1350
1351 /** The minimum char that's a valid char in Base64-encoded text */
1352 #define UNBASE64_MIN_CHAR (43)
1353 /** The maximum char that's a valid char in Base64-encoded text */
1354 #define UNBASE64_MAX_CHAR (122)
1355 /** Must subtract this from a char's integer value before offsetting
1356  * into unbase64_table
1357  */
1358 #define UNBASE64_TABLE_OFFSET UNBASE64_MIN_CHAR
1359 static const signed char unbase64_table[] = {
1360   /* 43 + */ 62,
1361   /* 44 , */ -1,
1362   /* 45 - */ -1,
1363   /* 46 . */ -1,
1364   /* 47 / */ 63,
1365   /* 48 0 */ 52,
1366   /* 49 1 */ 53,
1367   /* 50 2 */ 54,
1368   /* 51 3 */ 55,
1369   /* 52 4 */ 56,
1370   /* 53 5 */ 57,
1371   /* 54 6 */ 58,
1372   /* 55 7 */ 59,
1373   /* 56 8 */ 60,
1374   /* 57 9 */ 61,
1375   /* 58 : */ -1,
1376   /* 59 ; */ -1,
1377   /* 60 < */ -1,
1378   /* 61 = */ -1,
1379   /* 62 > */ -1,
1380   /* 63 ? */ -1,
1381   /* 64 @ */ -1,
1382   /* 65 A */ 0,
1383   /* 66 B */ 1,
1384   /* 67 C */ 2,
1385   /* 68 D */ 3,
1386   /* 69 E */ 4,
1387   /* 70 F */ 5,
1388   /* 71 G */ 6,
1389   /* 72 H */ 7,
1390   /* 73 I */ 8,
1391   /* 74 J */ 9,
1392   /* 75 K */ 10,
1393   /* 76 L */ 11,
1394   /* 77 M */ 12,
1395   /* 78 N */ 13,
1396   /* 79 O */ 14,
1397   /* 80 P */ 15,
1398   /* 81 Q */ 16,
1399   /* 82 R */ 17,
1400   /* 83 S */ 18,
1401   /* 84 T */ 19,
1402   /* 85 U */ 20,
1403   /* 86 V */ 21,
1404   /* 87 W */ 22,
1405   /* 88 X */ 23,
1406   /* 89 Y */ 24,
1407   /* 90 Z */ 25,
1408   /* 91 [ */ -1,
1409   /* 92 \ */ -1,
1410   /* 93 ] */ -1,
1411   /* 94 ^ */ -1,
1412   /* 95 _ */ -1,
1413   /* 96 ` */ -1,
1414   /* 97 a */ 26,
1415   /* 98 b */ 27,
1416   /* 99 c */ 28,
1417   /* 100 d */ 29,
1418   /* 101 e */ 30,
1419   /* 102 f */ 31,
1420   /* 103 g */ 32,
1421   /* 104 h */ 33,
1422   /* 105 i */ 34,
1423   /* 106 j */ 35,
1424   /* 107 k */ 36,
1425   /* 108 l */ 37,
1426   /* 109 m */ 38,
1427   /* 110 n */ 39,
1428   /* 111 o */ 40,
1429   /* 112 p */ 41,
1430   /* 113 q */ 42,
1431   /* 114 r */ 43,
1432   /* 115 s */ 44,
1433   /* 116 t */ 45,
1434   /* 117 u */ 46,
1435   /* 118 v */ 47,
1436   /* 119 w */ 48,
1437   /* 120 x */ 49,
1438   /* 121 y */ 50,
1439   /* 122 z */ 51
1440 };
1441
1442 /**
1443  * Encodes a string using Base64, as documented in RFC 2045.
1444  *
1445  * @param source the string to encode
1446  * @param start byte index to start encoding
1447  * @param dest string where encoded data should be placed
1448  * @param insert_at where to place encoded data
1449  * @returns #TRUE if encoding was successful, #FALSE if no memory etc.
1450  */
1451 dbus_bool_t
1452 _dbus_string_base64_encode (const DBusString *source,
1453                             int               start,
1454                             DBusString       *dest,
1455                             int               insert_at)
1456 {
1457   int source_len;
1458   int dest_len;
1459   const unsigned char *s;
1460   unsigned char *d;
1461   const unsigned char *triplet_end;
1462   const unsigned char *final_end;
1463   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);  
1464   _dbus_assert (source != dest);
1465   
1466   /* For each 24 bits (3 bytes) of input, we have 4 chars of
1467    * output.
1468    */
1469   source_len = real_source->len - start;
1470   dest_len = (source_len / 3) * 4;
1471   if (source_len % 3 != 0)
1472     dest_len += 4;
1473
1474   if (source_len == 0)
1475     return TRUE;
1476   
1477   if (!open_gap (dest_len, real_dest, insert_at))
1478     return FALSE;
1479
1480   d = real_dest->str + insert_at;
1481   s = real_source->str + start;
1482   final_end = real_source->str + (start + source_len);
1483   triplet_end = final_end - (source_len % 3);
1484   _dbus_assert (triplet_end <= final_end);
1485   _dbus_assert ((final_end - triplet_end) < 3);
1486
1487 #define ENCODE_64(v) (base64_table[ (unsigned char) (v) ])
1488 #define SIX_BITS_MASK (0x3f)
1489   _dbus_assert (SIX_BITS_MASK < _DBUS_N_ELEMENTS (base64_table));
1490   
1491   while (s != triplet_end)
1492     {
1493       unsigned int triplet;
1494
1495       triplet = s[0] | (s[1] << 8) | (s[2] << 16);
1496
1497       /* Encode each 6 bits */
1498       
1499       *d++ = ENCODE_64 (triplet >> 18);
1500       *d++ = ENCODE_64 ((triplet >> 12) & SIX_BITS_MASK);
1501       *d++ = ENCODE_64 ((triplet >> 6) & SIX_BITS_MASK);
1502       *d++ = ENCODE_64 (triplet & SIX_BITS_MASK);
1503       
1504       s += 3;
1505     }
1506
1507   switch (final_end - triplet_end)
1508     {
1509     case 2:
1510       {
1511         unsigned int doublet;
1512         
1513         doublet = s[0] | (s[1] << 8);
1514         
1515         *d++ = ENCODE_64 (doublet >> 12);
1516         *d++ = ENCODE_64 ((doublet >> 6) & SIX_BITS_MASK);
1517         *d++ = ENCODE_64 (doublet & SIX_BITS_MASK);
1518         *d++ = '=';
1519       }
1520       break;
1521     case 1:
1522       {
1523         unsigned int singlet;
1524         
1525         singlet = s[0];
1526         
1527         *d++ = ENCODE_64 ((singlet >> 6) & SIX_BITS_MASK);
1528         *d++ = ENCODE_64 (singlet & SIX_BITS_MASK);
1529         *d++ = '=';
1530         *d++ = '=';
1531       }
1532       break;
1533     case 0:
1534       break;
1535     }
1536
1537   _dbus_assert (d == (real_dest->str + (insert_at + dest_len)));
1538
1539   return TRUE;
1540 }
1541
1542
1543 /**
1544  * Decodes a string from Base64, as documented in RFC 2045.
1545  *
1546  * @param source the string to decode
1547  * @param start byte index to start decode
1548  * @param dest string where decoded data should be placed
1549  * @param insert_at where to place decoded data
1550  * @returns #TRUE if decoding was successful, #FALSE if no memory etc.
1551  */
1552 dbus_bool_t
1553 _dbus_string_base64_decode (const DBusString *source,
1554                             int               start,
1555                             DBusString       *dest,
1556                             int               insert_at)
1557 {
1558   int source_len;
1559   const char *s;
1560   const char *end;
1561   DBusString result;
1562   unsigned int triplet = 0;
1563   int sextet_count;
1564   int pad_count;
1565   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1566   _dbus_assert (source != dest);
1567   
1568   source_len = real_source->len - start;
1569   s = real_source->str + start;
1570   end = real_source->str + source_len;
1571
1572   if (source_len == 0)
1573     return TRUE;
1574
1575   if (!_dbus_string_init (&result, _DBUS_INT_MAX))
1576     return FALSE;
1577
1578   pad_count = 0;
1579   sextet_count = 0;
1580   while (s != end)
1581     {
1582       /* The idea is to just skip anything that isn't
1583        * a base64 char - it's allowed to have whitespace,
1584        * newlines, etc. in here. We also ignore trailing
1585        * base64 chars, though that's suspicious.
1586        */
1587       
1588       if (*s >= UNBASE64_MIN_CHAR &&
1589           *s <= UNBASE64_MAX_CHAR)
1590         {
1591           if (*s == '=')
1592             {
1593               /* '=' is padding, doesn't represent additional data
1594                * but does increment our count.
1595                */
1596               pad_count += 1;
1597               sextet_count += 1;
1598             }
1599           else
1600             {
1601               int val;
1602
1603               val = unbase64_table[(*s) - UNBASE64_TABLE_OFFSET];
1604
1605               if (val >= 0)
1606                 {
1607                   triplet <<= 6;
1608                   triplet |= (unsigned int) val;
1609                   sextet_count += 1;
1610                 }
1611             }
1612
1613           if (sextet_count == 4)
1614             {
1615               /* no pad = 3 bytes, 1 pad = 2 bytes, 2 pad = 1 byte */
1616               
1617               _dbus_string_append_byte (&result,
1618                                         triplet & 0xff);
1619               
1620               if (pad_count < 2)
1621                 _dbus_string_append_byte (&result,
1622                                           (triplet >> 8) & 0xff);
1623
1624               if (pad_count < 1)
1625                 _dbus_string_append_byte (&result,
1626                                           triplet >> 16);
1627
1628               sextet_count = 0;
1629               pad_count = 0;
1630               triplet = 0;
1631             }
1632         }
1633       
1634       ++s;
1635     }
1636
1637   if (!_dbus_string_move (&result, 0, dest, insert_at))
1638     {
1639       _dbus_string_free (&result);
1640       return FALSE;
1641     }
1642
1643   _dbus_string_free (&result);
1644
1645   return TRUE;
1646 }
1647
1648 /**
1649  * Checks that the given range of the string
1650  * is valid ASCII. If the given range is not contained
1651  * in the string, returns #FALSE.
1652  *
1653  * @param str the string
1654  * @param start first byte index to check
1655  * @param len number of bytes to check
1656  * @returns #TRUE if the byte range exists and is all valid ASCII
1657  */
1658 dbus_bool_t
1659 _dbus_string_validate_ascii (const DBusString *str,
1660                              int               start,
1661                              int               len)
1662 {
1663   const unsigned char *s;
1664   const unsigned char *end;
1665   DBUS_CONST_STRING_PREAMBLE (str);
1666   _dbus_assert (start >= 0);
1667   _dbus_assert (len >= 0);
1668   
1669   if ((start + len) > real->len)
1670     return FALSE;
1671   
1672   s = real->str + start;
1673   end = s + len;
1674   while (s != end)
1675     {
1676       if (*s == '\0' ||
1677           ((*s & ~0x7f) != 0))
1678         return FALSE;
1679         
1680       ++s;
1681     }
1682   
1683   return TRUE;
1684 }
1685
1686 /** @} */
1687
1688 #ifdef DBUS_BUILD_TESTS
1689 #include "dbus-test.h"
1690 #include <stdio.h>
1691
1692 static void
1693 test_max_len (DBusString *str,
1694               int         max_len)
1695 {
1696   if (max_len > 0)
1697     {
1698       if (!_dbus_string_set_length (str, max_len - 1))
1699         _dbus_assert_not_reached ("setting len to one less than max should have worked");
1700     }
1701
1702   if (!_dbus_string_set_length (str, max_len))
1703     _dbus_assert_not_reached ("setting len to max len should have worked");
1704
1705   if (_dbus_string_set_length (str, max_len + 1))
1706     _dbus_assert_not_reached ("setting len to one more than max len should not have worked");
1707
1708   if (!_dbus_string_set_length (str, 0))
1709     _dbus_assert_not_reached ("setting len to zero should have worked");
1710 }
1711
1712 static void
1713 test_base64_roundtrip (const unsigned char *data,
1714                        int                  len)
1715 {
1716   DBusString orig;
1717   DBusString encoded;
1718   DBusString decoded;
1719
1720   if (len < 0)
1721     len = strlen (data);
1722   
1723   if (!_dbus_string_init (&orig, _DBUS_INT_MAX))
1724     _dbus_assert_not_reached ("could not init string");
1725
1726   if (!_dbus_string_init (&encoded, _DBUS_INT_MAX))
1727     _dbus_assert_not_reached ("could not init string");
1728   
1729   if (!_dbus_string_init (&decoded, _DBUS_INT_MAX))
1730     _dbus_assert_not_reached ("could not init string");
1731
1732   if (!_dbus_string_append_len (&orig, data, len))
1733     _dbus_assert_not_reached ("couldn't append orig data");
1734
1735   if (!_dbus_string_base64_encode (&orig, 0, &encoded, 0))
1736     _dbus_assert_not_reached ("could not encode");
1737
1738   if (!_dbus_string_base64_decode (&encoded, 0, &decoded, 0))
1739     _dbus_assert_not_reached ("could not decode");
1740
1741   if (!_dbus_string_equal (&orig, &decoded))
1742     {
1743       const char *s;
1744       
1745       printf ("Original string %d bytes encoded %d bytes decoded %d bytes\n",
1746               _dbus_string_get_length (&orig),
1747               _dbus_string_get_length (&encoded),
1748               _dbus_string_get_length (&decoded));
1749       printf ("Original: %s\n", data);
1750       _dbus_string_get_const_data (&decoded, &s);
1751       printf ("Decoded: %s\n", s);
1752       _dbus_assert_not_reached ("original string not the same as string decoded from base64");
1753     }
1754   
1755   _dbus_string_free (&orig);
1756   _dbus_string_free (&encoded);
1757   _dbus_string_free (&decoded);  
1758 }
1759
1760 /**
1761  * @ingroup DBusStringInternals
1762  * Unit test for DBusString.
1763  *
1764  * @todo Need to write tests for _dbus_string_copy() and
1765  * _dbus_string_move() moving to/from each of start/middle/end of a
1766  * string.
1767  * 
1768  * @returns #TRUE on success.
1769  */
1770 dbus_bool_t
1771 _dbus_string_test (void)
1772 {
1773   DBusString str;
1774   DBusString other;
1775   int i, end;
1776   long v;
1777   double d;
1778   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 };
1779   char *s;
1780   dbus_unichar_t ch;
1781   
1782   i = 0;
1783   while (i < _DBUS_N_ELEMENTS (lens))
1784     {
1785       if (!_dbus_string_init (&str, lens[i]))
1786         _dbus_assert_not_reached ("failed to init string");
1787       
1788       test_max_len (&str, lens[i]);
1789       _dbus_string_free (&str);
1790
1791       ++i;
1792     }
1793
1794   /* Test shortening and setting length */
1795   i = 0;
1796   while (i < _DBUS_N_ELEMENTS (lens))
1797     {
1798       int j;
1799       
1800       if (!_dbus_string_init (&str, lens[i]))
1801         _dbus_assert_not_reached ("failed to init string");
1802       
1803       if (!_dbus_string_set_length (&str, lens[i]))
1804         _dbus_assert_not_reached ("failed to set string length");
1805
1806       j = lens[i];
1807       while (j > 0)
1808         {
1809           _dbus_assert (_dbus_string_get_length (&str) == j);
1810           if (j > 0)
1811             {
1812               _dbus_string_shorten (&str, 1);
1813               _dbus_assert (_dbus_string_get_length (&str) == (j - 1));
1814             }
1815           --j;
1816         }
1817       
1818       _dbus_string_free (&str);
1819
1820       ++i;
1821     }
1822
1823   /* Test appending data */
1824   if (!_dbus_string_init (&str, _DBUS_INT_MAX))
1825     _dbus_assert_not_reached ("failed to init string");
1826
1827   i = 0;
1828   while (i < 10)
1829     {
1830       if (!_dbus_string_append (&str, "a"))
1831         _dbus_assert_not_reached ("failed to append string to string\n");
1832
1833       _dbus_assert (_dbus_string_get_length (&str) == i * 2 + 1);
1834
1835       if (!_dbus_string_append_byte (&str, 'b'))
1836         _dbus_assert_not_reached ("failed to append byte to string\n");
1837
1838       _dbus_assert (_dbus_string_get_length (&str) == i * 2 + 2);
1839                     
1840       ++i;
1841     }
1842
1843   _dbus_string_free (&str);
1844
1845   /* Check steal_data */
1846   
1847   if (!_dbus_string_init (&str, _DBUS_INT_MAX))
1848     _dbus_assert_not_reached ("failed to init string");
1849
1850   if (!_dbus_string_append (&str, "Hello World"))
1851     _dbus_assert_not_reached ("could not append to string");
1852
1853   i = _dbus_string_get_length (&str);
1854   
1855   if (!_dbus_string_steal_data (&str, &s))
1856     _dbus_assert_not_reached ("failed to steal data");
1857
1858   _dbus_assert (_dbus_string_get_length (&str) == 0);
1859   _dbus_assert (((int)strlen (s)) == i);
1860
1861   dbus_free (s);
1862
1863   /* Check move */
1864   
1865   if (!_dbus_string_append (&str, "Hello World"))
1866     _dbus_assert_not_reached ("could not append to string");
1867
1868   i = _dbus_string_get_length (&str);
1869
1870   if (!_dbus_string_init (&other, _DBUS_INT_MAX))
1871     _dbus_assert_not_reached ("could not init string");
1872   
1873   if (!_dbus_string_move (&str, 0, &other, 0))
1874     _dbus_assert_not_reached ("could not move");
1875
1876   _dbus_assert (_dbus_string_get_length (&str) == 0);
1877   _dbus_assert (_dbus_string_get_length (&other) == i);
1878
1879   if (!_dbus_string_append (&str, "Hello World"))
1880     _dbus_assert_not_reached ("could not append to string");
1881   
1882   if (!_dbus_string_move (&str, 0, &other, _dbus_string_get_length (&other)))
1883     _dbus_assert_not_reached ("could not move");
1884
1885   _dbus_assert (_dbus_string_get_length (&str) == 0);
1886   _dbus_assert (_dbus_string_get_length (&other) == i * 2);
1887
1888     if (!_dbus_string_append (&str, "Hello World"))
1889     _dbus_assert_not_reached ("could not append to string");
1890   
1891   if (!_dbus_string_move (&str, 0, &other, _dbus_string_get_length (&other) / 2))
1892     _dbus_assert_not_reached ("could not move");
1893
1894   _dbus_assert (_dbus_string_get_length (&str) == 0);
1895   _dbus_assert (_dbus_string_get_length (&other) == i * 3);
1896   
1897   _dbus_string_free (&other);
1898
1899   /* Check copy */
1900   
1901   if (!_dbus_string_append (&str, "Hello World"))
1902     _dbus_assert_not_reached ("could not append to string");
1903
1904   i = _dbus_string_get_length (&str);
1905   
1906   if (!_dbus_string_init (&other, _DBUS_INT_MAX))
1907     _dbus_assert_not_reached ("could not init string");
1908   
1909   if (!_dbus_string_copy (&str, 0, &other, 0))
1910     _dbus_assert_not_reached ("could not copy");
1911
1912   _dbus_assert (_dbus_string_get_length (&str) == i);
1913   _dbus_assert (_dbus_string_get_length (&other) == i);
1914
1915   if (!_dbus_string_copy (&str, 0, &other, _dbus_string_get_length (&other)))
1916     _dbus_assert_not_reached ("could not copy");
1917
1918   _dbus_assert (_dbus_string_get_length (&str) == i);
1919   _dbus_assert (_dbus_string_get_length (&other) == i * 2);
1920   _dbus_assert (_dbus_string_equal_c_str (&other,
1921                                           "Hello WorldHello World"));
1922
1923   if (!_dbus_string_copy (&str, 0, &other, _dbus_string_get_length (&other) / 2))
1924     _dbus_assert_not_reached ("could not copy");
1925
1926   _dbus_assert (_dbus_string_get_length (&str) == i);
1927   _dbus_assert (_dbus_string_get_length (&other) == i * 3);
1928   _dbus_assert (_dbus_string_equal_c_str (&other,
1929                                           "Hello WorldHello WorldHello World"));
1930   
1931   _dbus_string_free (&str);
1932   _dbus_string_free (&other);
1933
1934   /* Check append/get unichar */
1935   
1936   if (!_dbus_string_init (&str, _DBUS_INT_MAX))
1937     _dbus_assert_not_reached ("failed to init string");
1938
1939   ch = 0;
1940   if (!_dbus_string_append_unichar (&str, 0xfffc))
1941     _dbus_assert_not_reached ("failed to append unichar");
1942
1943   _dbus_string_get_unichar (&str, 0, &ch, &i);
1944
1945   _dbus_assert (ch == 0xfffc);
1946   _dbus_assert (i == _dbus_string_get_length (&str));
1947
1948   _dbus_string_free (&str);
1949   
1950   /* Check append/parse int/double */
1951   
1952   if (!_dbus_string_init (&str, _DBUS_INT_MAX))
1953     _dbus_assert_not_reached ("failed to init string");
1954
1955   if (!_dbus_string_append_int (&str, 27))
1956     _dbus_assert_not_reached ("failed to append int");
1957
1958   i = _dbus_string_get_length (&str);
1959
1960   if (!_dbus_string_parse_int (&str, 0, &v, &end))
1961     _dbus_assert_not_reached ("failed to parse int");
1962
1963   _dbus_assert (v == 27);
1964   _dbus_assert (end == i);
1965
1966   _dbus_string_free (&str);
1967   
1968   if (!_dbus_string_init (&str, _DBUS_INT_MAX))
1969     _dbus_assert_not_reached ("failed to init string");
1970   
1971   if (!_dbus_string_append_double (&str, 50.3))
1972     _dbus_assert_not_reached ("failed to append float");
1973
1974   i = _dbus_string_get_length (&str);
1975
1976   if (!_dbus_string_parse_double (&str, 0, &d, &end))
1977     _dbus_assert_not_reached ("failed to parse float");
1978
1979   _dbus_assert (d > (50.3 - 1e-6) && d < (50.3 + 1e-6));
1980   _dbus_assert (end == i);
1981
1982   _dbus_string_free (&str);
1983
1984   /* Test find */
1985   if (!_dbus_string_init (&str, _DBUS_INT_MAX))
1986     _dbus_assert_not_reached ("failed to init string");
1987
1988   if (!_dbus_string_append (&str, "Hello"))
1989     _dbus_assert_not_reached ("couldn't append to string");
1990   
1991   if (!_dbus_string_find (&str, 0, "He", &i))
1992     _dbus_assert_not_reached ("didn't find 'He'");
1993   _dbus_assert (i == 0);
1994
1995   if (!_dbus_string_find (&str, 0, "ello", &i))
1996     _dbus_assert_not_reached ("didn't find 'ello'");
1997   _dbus_assert (i == 1);
1998
1999   if (!_dbus_string_find (&str, 0, "lo", &i))
2000     _dbus_assert_not_reached ("didn't find 'lo'");
2001   _dbus_assert (i == 3);
2002
2003   if (!_dbus_string_find (&str, 2, "lo", &i))
2004     _dbus_assert_not_reached ("didn't find 'lo'");
2005   _dbus_assert (i == 3);
2006
2007   if (_dbus_string_find (&str, 4, "lo", &i))
2008     _dbus_assert_not_reached ("did find 'lo'");
2009   
2010   if (!_dbus_string_find (&str, 0, "l", &i))
2011     _dbus_assert_not_reached ("didn't find 'l'");
2012   _dbus_assert (i == 2);
2013
2014   if (!_dbus_string_find (&str, 0, "H", &i))
2015     _dbus_assert_not_reached ("didn't find 'H'");
2016   _dbus_assert (i == 0);
2017
2018   if (!_dbus_string_find (&str, 0, "", &i))
2019     _dbus_assert_not_reached ("didn't find ''");
2020   _dbus_assert (i == 0);
2021   
2022   if (_dbus_string_find (&str, 0, "Hello!", NULL))
2023     _dbus_assert_not_reached ("Did find 'Hello!'");
2024
2025   if (_dbus_string_find (&str, 0, "Oh, Hello", NULL))
2026     _dbus_assert_not_reached ("Did find 'Oh, Hello'");
2027   
2028   if (_dbus_string_find (&str, 0, "ill", NULL))
2029     _dbus_assert_not_reached ("Did find 'ill'");
2030
2031   if (_dbus_string_find (&str, 0, "q", NULL))
2032     _dbus_assert_not_reached ("Did find 'q'");
2033   
2034   _dbus_string_free (&str);
2035
2036   /* Base 64 */
2037   test_base64_roundtrip ("Hello this is a string\n", -1);
2038   test_base64_roundtrip ("Hello this is a string\n1", -1);
2039   test_base64_roundtrip ("Hello this is a string\n12", -1);
2040   test_base64_roundtrip ("Hello this is a string\n123", -1);
2041   test_base64_roundtrip ("Hello this is a string\n1234", -1);
2042   test_base64_roundtrip ("Hello this is a string\n12345", -1);
2043   test_base64_roundtrip ("", 0);
2044   test_base64_roundtrip ("1", 1);
2045   test_base64_roundtrip ("12", 2);
2046   test_base64_roundtrip ("123", 3);
2047   test_base64_roundtrip ("1234", 4);
2048   test_base64_roundtrip ("12345", 5);
2049   test_base64_roundtrip ("", 1);
2050   test_base64_roundtrip ("1", 2);
2051   test_base64_roundtrip ("12", 3);
2052   test_base64_roundtrip ("123", 4);
2053   test_base64_roundtrip ("1234", 5);
2054   test_base64_roundtrip ("12345", 6);
2055   {
2056     unsigned char buf[512];
2057     i = 0;
2058     while (i < _DBUS_N_ELEMENTS (buf))
2059       {
2060         buf[i] = i;
2061         ++i;
2062       }
2063     i = 0;
2064     while (i < _DBUS_N_ELEMENTS (buf))
2065       {
2066         test_base64_roundtrip (buf, i);
2067         ++i;
2068       }
2069   }
2070   
2071   return TRUE;
2072 }
2073
2074 #endif /* DBUS_BUILD_TESTS */