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