1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-string.c String utility class (internal to D-BUS implementation)
4 * Copyright (C) 2002, 2003 Red Hat, Inc.
6 * Licensed under the Academic Free License version 1.2
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.
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.
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
24 #include "dbus-internals.h"
25 #include "dbus-string.h"
26 /* we allow a system header here, for speed/convenience */
28 #include "dbus-marshal.h"
29 #define DBUS_CAN_USE_DBUS_STRING_PRIVATE 1
30 #include "dbus-string-private.h"
33 * @defgroup DBusString string class
34 * @ingroup DBusInternals
35 * @brief DBusString data structure
37 * Types and functions related to DBusString. DBusString is intended
38 * to be a string class that makes it hard to mess up security issues
39 * (and just in general harder to write buggy code). It should be
40 * used (or extended and then used) rather than the libc stuff in
41 * string.h. The string class is a bit inconvenient at spots because
42 * it handles out-of-memory failures and tries to be extra-robust.
44 * A DBusString has a maximum length set at initialization time; this
45 * can be used to ensure that a buffer doesn't get too big. The
46 * _dbus_string_lengthen() method checks for overflow, and for max
47 * length being exceeded.
49 * Try to avoid conversion to a plain C string, i.e. add methods on
50 * the string object instead, only convert to C string when passing
51 * things out to the public API. In particular, no sprintf, strcpy,
52 * strcat, any of that should be used. The GString feature of
53 * accepting negative numbers for "length of string" is also absent,
54 * because it could keep us from detecting bogus huge lengths. i.e. if
55 * we passed in some bogus huge length it would be taken to mean
56 * "current length of string" instead of "broken crack"
60 * @defgroup DBusStringInternals DBusString implementation details
61 * @ingroup DBusInternals
62 * @brief DBusString implementation details
64 * The guts of DBusString.
70 * We allocate 1 byte for nul termination, plus 7 bytes for possible
71 * align_offset, so we always need 8 bytes on top of the string's
72 * length to be in the allocated block.
74 #define ALLOCATION_PADDING 8
77 * This is the maximum max length (and thus also the maximum length)
80 #define MAX_MAX_LENGTH (_DBUS_INT_MAX - ALLOCATION_PADDING)
83 * Checks a bunch of assertions about a string object
85 * @param real the DBusRealString
87 #define DBUS_GENERIC_STRING_PREAMBLE(real) _dbus_assert ((real) != NULL); _dbus_assert (!(real)->invalid); _dbus_assert ((real)->len >= 0); _dbus_assert ((real)->allocated >= 0); _dbus_assert ((real)->max_length >= 0); _dbus_assert ((real)->len <= ((real)->allocated - ALLOCATION_PADDING)); _dbus_assert ((real)->len <= (real)->max_length)
90 * Checks assertions about a string object that needs to be
91 * modifiable - may not be locked or const. Also declares
92 * the "real" variable pointing to DBusRealString.
93 * @param str the string
95 #define DBUS_STRING_PREAMBLE(str) DBusRealString *real = (DBusRealString*) str; \
96 DBUS_GENERIC_STRING_PREAMBLE (real); \
97 _dbus_assert (!(real)->constant); \
98 _dbus_assert (!(real)->locked)
101 * Checks assertions about a string object that may be locked but
102 * can't be const. i.e. a string object that we can free. Also
103 * declares the "real" variable pointing to DBusRealString.
105 * @param str the string
107 #define DBUS_LOCKED_STRING_PREAMBLE(str) DBusRealString *real = (DBusRealString*) str; \
108 DBUS_GENERIC_STRING_PREAMBLE (real); \
109 _dbus_assert (!(real)->constant)
112 * Checks assertions about a string that may be const or locked. Also
113 * declares the "real" variable pointing to DBusRealString.
114 * @param str the string.
116 #define DBUS_CONST_STRING_PREAMBLE(str) const DBusRealString *real = (DBusRealString*) str; \
117 DBUS_GENERIC_STRING_PREAMBLE (real)
122 * @addtogroup DBusString
127 fixup_alignment (DBusRealString *real)
131 unsigned int old_align_offset;
133 /* we have to have extra space in real->allocated for the align offset and nul byte */
134 _dbus_assert (real->len <= real->allocated - ALLOCATION_PADDING);
136 old_align_offset = real->align_offset;
137 real_block = real->str - old_align_offset;
139 aligned = _DBUS_ALIGN_ADDRESS (real_block, 8);
141 real->align_offset = aligned - real_block;
144 if (old_align_offset != real->align_offset)
146 /* Here comes the suck */
147 memmove (real_block + real->align_offset,
148 real_block + old_align_offset,
152 _dbus_assert (real->align_offset < 8);
153 _dbus_assert (_DBUS_ALIGN_ADDRESS (real->str, 8) == real->str);
157 undo_alignment (DBusRealString *real)
159 if (real->align_offset != 0)
161 memmove (real->str - real->align_offset,
165 real->str = real->str - real->align_offset;
166 real->align_offset = 0;
171 * Initializes a string. The string starts life with zero length. The
172 * string must eventually be freed with _dbus_string_free().
174 * @param str memory to hold the string
175 * @returns #TRUE on success, #FALSE if no memory
178 _dbus_string_init (DBusString *str)
180 DBusRealString *real;
182 _dbus_assert (str != NULL);
184 _dbus_assert (sizeof (DBusString) == sizeof (DBusRealString));
186 real = (DBusRealString*) str;
188 /* It's very important not to touch anything
189 * other than real->str if we're going to fail,
190 * since we also use this function to reset
191 * an existing string, e.g. in _dbus_string_steal_data()
194 real->str = dbus_malloc (ALLOCATION_PADDING);
195 if (real->str == NULL)
198 real->allocated = ALLOCATION_PADDING;
200 real->str[real->len] = '\0';
202 real->max_length = MAX_MAX_LENGTH;
203 real->constant = FALSE;
204 real->locked = FALSE;
205 real->invalid = FALSE;
206 real->align_offset = 0;
208 fixup_alignment (real);
213 /* The max length thing is sort of a historical artifact
214 * from a feature that turned out to be dumb; perhaps
215 * we should purge it entirely. The problem with
216 * the feature is that it looks like memory allocation
217 * failure, but is not a transient or resolvable failure.
220 set_max_length (DBusString *str,
223 DBusRealString *real;
225 real = (DBusRealString*) str;
227 real->max_length = max_length;
231 * Initializes a constant string. The value parameter is not copied
232 * (should be static), and the string may never be modified.
233 * It is safe but not necessary to call _dbus_string_free()
234 * on a const string. The string has a length limit of MAXINT - 8.
236 * @param str memory to use for the string
237 * @param value a string to be stored in str (not copied!!!)
240 _dbus_string_init_const (DBusString *str,
243 _dbus_assert (value != NULL);
245 _dbus_string_init_const_len (str, value,
250 * Initializes a constant string with a length. The value parameter is
251 * not copied (should be static), and the string may never be
252 * modified. It is safe but not necessary to call _dbus_string_free()
255 * @param str memory to use for the string
256 * @param value a string to be stored in str (not copied!!!)
257 * @param len the length to use
260 _dbus_string_init_const_len (DBusString *str,
264 DBusRealString *real;
266 _dbus_assert (str != NULL);
267 _dbus_assert (value != NULL);
268 _dbus_assert (len <= MAX_MAX_LENGTH);
269 _dbus_assert (len >= 0);
271 real = (DBusRealString*) str;
273 real->str = (char*) value;
275 real->allocated = real->len + ALLOCATION_PADDING; /* a lie, just to avoid special-case assertions... */
276 real->max_length = real->len + 1;
277 real->constant = TRUE;
278 real->invalid = FALSE;
280 /* We don't require const strings to be 8-byte aligned as the
281 * memory is coming from elsewhere.
286 * Frees a string created by _dbus_string_init().
288 * @param str memory where the string is stored.
291 _dbus_string_free (DBusString *str)
293 DBusRealString *real = (DBusRealString*) str;
294 DBUS_GENERIC_STRING_PREAMBLE (real);
298 dbus_free (real->str - real->align_offset);
300 real->invalid = TRUE;
304 * Locks a string such that any attempts to change the string will
305 * result in aborting the program. Also, if the string is wasting a
306 * lot of memory (allocation is sufficiently larger than what the
307 * string is really using), _dbus_string_lock() will realloc the
308 * string's data to "compact" it.
310 * @param str the string to lock.
313 _dbus_string_lock (DBusString *str)
315 DBUS_LOCKED_STRING_PREAMBLE (str); /* can lock multiple times */
319 /* Try to realloc to avoid excess memory usage, since
320 * we know we won't change the string further
323 if (real->allocated - MAX_WASTE > real->len)
328 new_allocated = real->len + ALLOCATION_PADDING;
330 new_str = dbus_realloc (real->str - real->align_offset,
334 real->str = new_str + real->align_offset;
335 real->allocated = new_allocated;
336 fixup_alignment (real);
342 set_length (DBusRealString *real,
345 /* Note, we are setting the length without nul termination */
347 /* exceeding max length is the same as failure to allocate memory */
348 if (new_length > real->max_length)
351 if (new_length > (real->allocated - ALLOCATION_PADDING))
356 /* at least double our old allocation to avoid O(n), avoiding
359 if (real->allocated > (MAX_MAX_LENGTH + ALLOCATION_PADDING) / 2)
360 new_allocated = MAX_MAX_LENGTH + ALLOCATION_PADDING;
362 new_allocated = real->allocated * 2;
364 /* if you change the code just above here, run the tests without
365 * the following before you commit
367 #ifdef DBUS_BUILD_TESTS
368 new_allocated = 0; /* ensure a realloc every time so that we go
369 * through all malloc failure codepaths
373 /* But be sure we always alloc at least space for the new length */
374 new_allocated = MAX (new_allocated, new_length + ALLOCATION_PADDING);
376 new_str = dbus_realloc (real->str - real->align_offset, new_allocated);
380 real->str = new_str + real->align_offset;
381 real->allocated = new_allocated;
382 fixup_alignment (real);
385 real->len = new_length;
386 real->str[real->len] = '\0';
393 DBusRealString *dest,
399 if (len > dest->max_length - dest->len)
400 return FALSE; /* detected overflow of dest->len + len below */
402 if (!set_length (dest, dest->len + len))
405 memmove (dest->str + insert_at + len,
406 dest->str + insert_at,
407 dest->len - len - insert_at);
413 * Gets the raw character buffer from the string. The returned buffer
414 * will be nul-terminated, but note that strings may contain binary
415 * data so there may be extra nul characters prior to the termination.
416 * This function should be little-used, extend DBusString or add
417 * stuff to dbus-sysdeps.c instead. It's an error to use this
418 * function on a const string.
420 * @param str the string
424 _dbus_string_get_data (DBusString *str)
426 DBUS_STRING_PREAMBLE (str);
432 * Gets the raw character buffer from a const string.
434 * @param str the string
435 * @returns the string data
438 _dbus_string_get_const_data (const DBusString *str)
440 DBUS_CONST_STRING_PREAMBLE (str);
446 * Gets a sub-portion of the raw character buffer from the
447 * string. The "len" field is required simply for error
448 * checking, to be sure you don't try to use more
449 * string than exists. The nul termination of the
450 * returned buffer remains at the end of the entire
451 * string, not at start + len.
453 * @param str the string
454 * @param start byte offset to return
455 * @param len length of segment to return
456 * @returns the string data
459 _dbus_string_get_data_len (DBusString *str,
463 DBUS_STRING_PREAMBLE (str);
464 _dbus_assert (start >= 0);
465 _dbus_assert (len >= 0);
466 _dbus_assert (start <= real->len);
467 _dbus_assert (len <= real->len - start);
469 return real->str + start;
473 * const version of _dbus_string_get_data_len().
475 * @param str the string
476 * @param start byte offset to return
477 * @param len length of segment to return
478 * @returns the string data
481 _dbus_string_get_const_data_len (const DBusString *str,
485 DBUS_CONST_STRING_PREAMBLE (str);
486 _dbus_assert (start >= 0);
487 _dbus_assert (len >= 0);
488 _dbus_assert (start <= real->len);
489 _dbus_assert (len <= real->len - start);
491 return real->str + start;
495 * Sets the value of the byte at the given position.
497 * @param str the string
498 * @param i the position
499 * @param byte the new value
502 _dbus_string_set_byte (DBusString *str,
506 DBUS_STRING_PREAMBLE (str);
507 _dbus_assert (i < real->len);
508 _dbus_assert (i >= 0);
514 * Gets the byte at the given position.
516 * @param str the string
517 * @param start the position
518 * @returns the byte at that position
521 _dbus_string_get_byte (const DBusString *str,
524 DBUS_CONST_STRING_PREAMBLE (str);
525 _dbus_assert (start < real->len);
526 _dbus_assert (start >= 0);
528 return real->str[start];
532 * Inserts the given byte at the given position.
534 * @param str the string
535 * @param i the position
536 * @param byte the value to insert
537 * @returns #TRUE on success
540 _dbus_string_insert_byte (DBusString *str,
544 DBUS_STRING_PREAMBLE (str);
545 _dbus_assert (i <= real->len);
546 _dbus_assert (i >= 0);
548 if (!open_gap (1, real, i))
557 * Like _dbus_string_get_data(), but removes the
558 * gotten data from the original string. The caller
559 * must free the data returned. This function may
560 * fail due to lack of memory, and return #FALSE.
562 * @param str the string
563 * @param data_return location to return the buffer
564 * @returns #TRUE on success
567 _dbus_string_steal_data (DBusString *str,
571 DBUS_STRING_PREAMBLE (str);
572 _dbus_assert (data_return != NULL);
574 undo_alignment (real);
576 *data_return = real->str;
578 old_max_length = real->max_length;
580 /* reset the string */
581 if (!_dbus_string_init (str))
583 /* hrm, put it back then */
584 real->str = *data_return;
586 fixup_alignment (real);
590 real->max_length = old_max_length;
596 * Like _dbus_string_get_data_len(), but removes the gotten data from
597 * the original string. The caller must free the data returned. This
598 * function may fail due to lack of memory, and return #FALSE.
599 * The returned string is nul-terminated and has length len.
601 * @todo this function is broken because on failure it
602 * may corrupt the source string.
604 * @param str the string
605 * @param data_return location to return the buffer
606 * @param start the start of segment to steal
607 * @param len the length of segment to steal
608 * @returns #TRUE on success
611 _dbus_string_steal_data_len (DBusString *str,
617 DBUS_STRING_PREAMBLE (str);
618 _dbus_assert (data_return != NULL);
619 _dbus_assert (start >= 0);
620 _dbus_assert (len >= 0);
621 _dbus_assert (start <= real->len);
622 _dbus_assert (len <= real->len - start);
624 if (!_dbus_string_init (&dest))
627 set_max_length (&dest, real->max_length);
629 if (!_dbus_string_move_len (str, start, len, &dest, 0))
631 _dbus_string_free (&dest);
635 _dbus_warn ("Broken code in _dbus_string_steal_data_len(), see @todo, FIXME\n");
636 if (!_dbus_string_steal_data (&dest, data_return))
638 _dbus_string_free (&dest);
642 _dbus_string_free (&dest);
648 * Copies the data from the string into a char*
650 * @param str the string
651 * @param data_return place to return the data
652 * @returns #TRUE on success, #FALSE on no memory
655 _dbus_string_copy_data (const DBusString *str,
658 DBUS_CONST_STRING_PREAMBLE (str);
659 _dbus_assert (data_return != NULL);
661 *data_return = dbus_malloc (real->len + 1);
662 if (*data_return == NULL)
665 memcpy (*data_return, real->str, real->len + 1);
671 * Copies a segment of the string into a char*
673 * @param str the string
674 * @param data_return place to return the data
675 * @param start start index
676 * @param len length to copy
677 * @returns #FALSE if no memory
680 _dbus_string_copy_data_len (const DBusString *str,
687 DBUS_CONST_STRING_PREAMBLE (str);
688 _dbus_assert (data_return != NULL);
689 _dbus_assert (start >= 0);
690 _dbus_assert (len >= 0);
691 _dbus_assert (start <= real->len);
692 _dbus_assert (len <= real->len - start);
694 if (!_dbus_string_init (&dest))
697 set_max_length (&dest, real->max_length);
699 if (!_dbus_string_copy_len (str, start, len, &dest, 0))
701 _dbus_string_free (&dest);
705 if (!_dbus_string_steal_data (&dest, data_return))
707 _dbus_string_free (&dest);
711 _dbus_string_free (&dest);
716 * Gets the length of a string (not including nul termination).
718 * @returns the length.
721 _dbus_string_get_length (const DBusString *str)
723 DBUS_CONST_STRING_PREAMBLE (str);
729 * Makes a string longer by the given number of bytes. Checks whether
730 * adding additional_length to the current length would overflow an
731 * integer, and checks for exceeding a string's max length.
732 * The new bytes are not initialized, other than nul-terminating
733 * the end of the string. The uninitialized bytes may contain
734 * nul bytes or other junk.
736 * @param str a string
737 * @param additional_length length to add to the string.
738 * @returns #TRUE on success.
741 _dbus_string_lengthen (DBusString *str,
742 int additional_length)
744 DBUS_STRING_PREAMBLE (str);
745 _dbus_assert (additional_length >= 0);
747 if (additional_length > real->max_length - real->len)
748 return FALSE; /* would overflow */
750 return set_length (real,
751 real->len + additional_length);
755 * Makes a string shorter by the given number of bytes.
757 * @param str a string
758 * @param length_to_remove length to remove from the string.
761 _dbus_string_shorten (DBusString *str,
762 int length_to_remove)
764 DBUS_STRING_PREAMBLE (str);
765 _dbus_assert (length_to_remove >= 0);
766 _dbus_assert (length_to_remove <= real->len);
769 real->len - length_to_remove);
773 * Sets the length of a string. Can be used to truncate or lengthen
774 * the string. If the string is lengthened, the function may fail and
775 * return #FALSE. Newly-added bytes are not initialized, as with
776 * _dbus_string_lengthen().
778 * @param str a string
779 * @param length new length of the string.
780 * @returns #FALSE on failure.
783 _dbus_string_set_length (DBusString *str,
786 DBUS_STRING_PREAMBLE (str);
787 _dbus_assert (length >= 0);
789 return set_length (real, length);
793 * Align the length of a string to a specific alignment (typically 4 or 8)
794 * by appending nul bytes to the string.
796 * @param str a string
797 * @param alignment the alignment
798 * @returns #FALSE if no memory
801 _dbus_string_align_length (DBusString *str,
804 unsigned long new_len; /* ulong to avoid _DBUS_ALIGN_VALUE overflow */
806 DBUS_STRING_PREAMBLE (str);
807 _dbus_assert (alignment >= 1);
808 _dbus_assert (alignment <= 8); /* it has to be a bug if > 8 */
810 new_len = _DBUS_ALIGN_VALUE (real->len, alignment);
811 if (new_len > (unsigned long) real->max_length)
814 delta = new_len - real->len;
815 _dbus_assert (delta >= 0);
820 if (!set_length (real, new_len))
823 memset (real->str + (new_len - delta),
830 append (DBusRealString *real,
837 if (!_dbus_string_lengthen ((DBusString*)real, buffer_len))
840 memcpy (real->str + (real->len - buffer_len),
848 * Appends a nul-terminated C-style string to a DBusString.
850 * @param str the DBusString
851 * @param buffer the nul-terminated characters to append
852 * @returns #FALSE if not enough memory.
855 _dbus_string_append (DBusString *str,
858 unsigned long buffer_len;
860 DBUS_STRING_PREAMBLE (str);
861 _dbus_assert (buffer != NULL);
863 buffer_len = strlen (buffer);
864 if (buffer_len > (unsigned long) real->max_length)
867 return append (real, buffer, buffer_len);
871 * Appends block of bytes with the given length to a DBusString.
873 * @param str the DBusString
874 * @param buffer the bytes to append
875 * @param len the number of bytes to append
876 * @returns #FALSE if not enough memory.
879 _dbus_string_append_len (DBusString *str,
883 DBUS_STRING_PREAMBLE (str);
884 _dbus_assert (buffer != NULL);
885 _dbus_assert (len >= 0);
887 return append (real, buffer, len);
891 * Appends a single byte to the string, returning #FALSE
892 * if not enough memory.
894 * @param str the string
895 * @param byte the byte to append
896 * @returns #TRUE on success
899 _dbus_string_append_byte (DBusString *str,
902 DBUS_STRING_PREAMBLE (str);
904 if (!set_length (real, real->len + 1))
907 real->str[real->len-1] = byte;
913 * Appends a single Unicode character, encoding the character
916 * @param str the string
917 * @param ch the Unicode character
920 _dbus_string_append_unichar (DBusString *str,
928 DBUS_STRING_PREAMBLE (str);
930 /* this code is from GLib but is pretty standard I think */
944 else if (ch < 0x10000)
949 else if (ch < 0x200000)
954 else if (ch < 0x4000000)
965 if (len > (real->max_length - real->len))
966 return FALSE; /* real->len + len would overflow */
968 if (!set_length (real, real->len + len))
971 out = real->str + (real->len - len);
973 for (i = len - 1; i > 0; --i)
975 out[i] = (ch & 0x3f) | 0x80;
984 delete (DBusRealString *real,
991 memmove (real->str + start, real->str + start + len, real->len - (start + len));
993 real->str[real->len] = '\0';
997 * Deletes a segment of a DBusString with length len starting at
998 * start. (Hint: to clear an entire string, setting length to 0
999 * with _dbus_string_set_length() is easier.)
1001 * @param str the DBusString
1002 * @param start where to start deleting
1003 * @param len the number of bytes to delete
1006 _dbus_string_delete (DBusString *str,
1010 DBUS_STRING_PREAMBLE (str);
1011 _dbus_assert (start >= 0);
1012 _dbus_assert (len >= 0);
1013 _dbus_assert (start <= real->len);
1014 _dbus_assert (len <= real->len - start);
1016 delete (real, start, len);
1020 copy (DBusRealString *source,
1023 DBusRealString *dest,
1029 if (!open_gap (len, dest, insert_at))
1032 memcpy (dest->str + insert_at,
1033 source->str + start,
1040 * Checks assertions for two strings we're copying a segment between,
1041 * and declares real_source/real_dest variables.
1043 * @param source the source string
1044 * @param start the starting offset
1045 * @param dest the dest string
1046 * @param insert_at where the copied segment is inserted
1048 #define DBUS_STRING_COPY_PREAMBLE(source, start, dest, insert_at) \
1049 DBusRealString *real_source = (DBusRealString*) source; \
1050 DBusRealString *real_dest = (DBusRealString*) dest; \
1051 _dbus_assert ((source) != (dest)); \
1052 DBUS_GENERIC_STRING_PREAMBLE (real_source); \
1053 DBUS_GENERIC_STRING_PREAMBLE (real_dest); \
1054 _dbus_assert (!real_dest->constant); \
1055 _dbus_assert (!real_dest->locked); \
1056 _dbus_assert ((start) >= 0); \
1057 _dbus_assert ((start) <= real_source->len); \
1058 _dbus_assert ((insert_at) >= 0); \
1059 _dbus_assert ((insert_at) <= real_dest->len)
1062 * Moves the end of one string into another string. Both strings
1063 * must be initialized, valid strings.
1065 * @param source the source string
1066 * @param start where to chop off the source string
1067 * @param dest the destination string
1068 * @param insert_at where to move the chopped-off part of source string
1069 * @returns #FALSE if not enough memory
1072 _dbus_string_move (DBusString *source,
1077 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1079 if (!copy (real_source, start,
1080 real_source->len - start,
1085 delete (real_source, start,
1086 real_source->len - start);
1092 * Like _dbus_string_move(), but does not delete the section
1093 * of the source string that's copied to the dest string.
1095 * @param source the source string
1096 * @param start where to start copying the source string
1097 * @param dest the destination string
1098 * @param insert_at where to place the copied part of source string
1099 * @returns #FALSE if not enough memory
1102 _dbus_string_copy (const DBusString *source,
1107 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1109 return copy (real_source, start,
1110 real_source->len - start,
1116 * Like _dbus_string_move(), but can move a segment from
1117 * the middle of the source string.
1119 * @param source the source string
1120 * @param start first byte of source string to move
1121 * @param len length of segment to move
1122 * @param dest the destination string
1123 * @param insert_at where to move the bytes from the source string
1124 * @returns #FALSE if not enough memory
1127 _dbus_string_move_len (DBusString *source,
1134 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1135 _dbus_assert (len >= 0);
1136 _dbus_assert ((start + len) <= real_source->len);
1138 if (!copy (real_source, start, len,
1143 delete (real_source, start,
1150 * Like _dbus_string_copy(), but can copy a segment from the middle of
1151 * the source string.
1153 * @param source the source string
1154 * @param start where to start copying the source string
1155 * @param len length of segment to copy
1156 * @param dest the destination string
1157 * @param insert_at where to place the copied segment of source string
1158 * @returns #FALSE if not enough memory
1161 _dbus_string_copy_len (const DBusString *source,
1167 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1168 _dbus_assert (len >= 0);
1169 _dbus_assert (start <= real_source->len);
1170 _dbus_assert (len <= real_source->len - start);
1172 return copy (real_source, start, len,
1178 * Replaces a segment of dest string with a segment of source string.
1180 * @todo optimize the case where the two lengths are the same, and
1181 * avoid memmoving the data in the trailing part of the string twice.
1183 * @todo avoid inserting the source into dest, then deleting
1184 * the replaced chunk of dest (which creates a potentially large
1185 * intermediate string). Instead, extend the replaced chunk
1186 * of dest with padding to the same size as the source chunk,
1187 * then copy in the source bytes.
1189 * @param source the source string
1190 * @param start where to start copying the source string
1191 * @param len length of segment to copy
1192 * @param dest the destination string
1193 * @param replace_at start of segment of dest string to replace
1194 * @param replace_len length of segment of dest string to replace
1195 * @returns #FALSE if not enough memory
1199 _dbus_string_replace_len (const DBusString *source,
1206 DBUS_STRING_COPY_PREAMBLE (source, start, dest, replace_at);
1207 _dbus_assert (len >= 0);
1208 _dbus_assert (start <= real_source->len);
1209 _dbus_assert (len <= real_source->len - start);
1210 _dbus_assert (replace_at >= 0);
1211 _dbus_assert (replace_at <= real_dest->len);
1212 _dbus_assert (replace_len <= real_dest->len - replace_at);
1214 if (!copy (real_source, start, len,
1215 real_dest, replace_at))
1218 delete (real_dest, replace_at + len, replace_len);
1223 /* Unicode macros and utf8_validate() from GLib Owen Taylor, Havoc
1224 * Pennington, and Tom Tromey are the authors and authorized relicense.
1227 /** computes length and mask of a unicode character
1228 * @param Char the char
1229 * @param Mask the mask variable to assign to
1230 * @param Len the length variable to assign to
1232 #define UTF8_COMPUTE(Char, Mask, Len) \
1238 else if ((Char & 0xe0) == 0xc0) \
1243 else if ((Char & 0xf0) == 0xe0) \
1248 else if ((Char & 0xf8) == 0xf0) \
1253 else if ((Char & 0xfc) == 0xf8) \
1258 else if ((Char & 0xfe) == 0xfc) \
1267 * computes length of a unicode character in UTF-8
1268 * @param Char the char
1270 #define UTF8_LENGTH(Char) \
1271 ((Char) < 0x80 ? 1 : \
1272 ((Char) < 0x800 ? 2 : \
1273 ((Char) < 0x10000 ? 3 : \
1274 ((Char) < 0x200000 ? 4 : \
1275 ((Char) < 0x4000000 ? 5 : 6)))))
1278 * Gets a UTF-8 value.
1280 * @param Result variable for extracted unicode char.
1281 * @param Chars the bytes to decode
1282 * @param Count counter variable
1283 * @param Mask mask for this char
1284 * @param Len length for this char in bytes
1286 #define UTF8_GET(Result, Chars, Count, Mask, Len) \
1287 (Result) = (Chars)[0] & (Mask); \
1288 for ((Count) = 1; (Count) < (Len); ++(Count)) \
1290 if (((Chars)[(Count)] & 0xc0) != 0x80) \
1296 (Result) |= ((Chars)[(Count)] & 0x3f); \
1300 * Check whether a unicode char is in a valid range.
1302 * @param Char the character
1304 #define UNICODE_VALID(Char) \
1305 ((Char) < 0x110000 && \
1306 (((Char) & 0xFFFFF800) != 0xD800) && \
1307 ((Char) < 0xFDD0 || (Char) > 0xFDEF) && \
1308 ((Char) & 0xFFFF) != 0xFFFF)
1311 * Gets a unicode character from a UTF-8 string. Does no validation;
1312 * you must verify that the string is valid UTF-8 in advance and must
1313 * pass in the start of a character.
1315 * @param str the string
1316 * @param start the start of the UTF-8 character.
1317 * @param ch_return location to return the character
1318 * @param end_return location to return the byte index of next character
1321 _dbus_string_get_unichar (const DBusString *str,
1323 dbus_unichar_t *ch_return,
1327 dbus_unichar_t result;
1330 DBUS_CONST_STRING_PREAMBLE (str);
1331 _dbus_assert (start >= 0);
1332 _dbus_assert (start <= real->len);
1337 *end_return = real->len;
1340 p = real->str + start;
1343 UTF8_COMPUTE (c, mask, len);
1346 UTF8_GET (result, p, i, mask, len);
1348 if (result == (dbus_unichar_t)-1)
1352 *ch_return = result;
1354 *end_return = start + len;
1358 * Finds the given substring in the string,
1359 * returning #TRUE and filling in the byte index
1360 * where the substring was found, if it was found.
1361 * Returns #FALSE if the substring wasn't found.
1362 * Sets *start to the length of the string if the substring
1365 * @param str the string
1366 * @param start where to start looking
1367 * @param substr the substring
1368 * @param found return location for where it was found, or #NULL
1369 * @returns #TRUE if found
1372 _dbus_string_find (const DBusString *str,
1377 return _dbus_string_find_to (str, start,
1378 ((const DBusRealString*)str)->len,
1383 * Finds the given substring in the string,
1384 * up to a certain position,
1385 * returning #TRUE and filling in the byte index
1386 * where the substring was found, if it was found.
1387 * Returns #FALSE if the substring wasn't found.
1388 * Sets *start to the length of the string if the substring
1391 * @param str the string
1392 * @param start where to start looking
1393 * @param end where to stop looking
1394 * @param substr the substring
1395 * @param found return location for where it was found, or #NULL
1396 * @returns #TRUE if found
1399 _dbus_string_find_to (const DBusString *str,
1406 DBUS_CONST_STRING_PREAMBLE (str);
1407 _dbus_assert (substr != NULL);
1408 _dbus_assert (start <= real->len);
1409 _dbus_assert (start >= 0);
1410 _dbus_assert (substr != NULL);
1411 _dbus_assert (end <= real->len);
1412 _dbus_assert (start <= end);
1414 /* we always "find" an empty string */
1415 if (*substr == '\0')
1425 if (real->str[i] == substr[0])
1431 if (substr[j - i] == '\0')
1433 else if (real->str[j] != substr[j - i])
1439 if (substr[j - i] == '\0')
1457 * Find the given byte scanning backward from the given start.
1458 * Sets *found to -1 if the byte is not found.
1460 * @param str the string
1461 * @param start the place to start scanning (will not find the byte at this point)
1462 * @param byte the byte to find
1463 * @param found return location for where it was found
1464 * @returns #TRUE if found
1467 _dbus_string_find_byte_backward (const DBusString *str,
1473 DBUS_CONST_STRING_PREAMBLE (str);
1474 _dbus_assert (start <= real->len);
1475 _dbus_assert (start >= 0);
1476 _dbus_assert (found != NULL);
1481 if (real->str[i] == byte)
1494 * Finds a blank (space or tab) in the string. Returns #TRUE
1495 * if found, #FALSE otherwise. If a blank is not found sets
1496 * *found to the length of the string.
1498 * @param str the string
1499 * @param start byte index to start looking
1500 * @param found place to store the location of the first blank
1501 * @returns #TRUE if a blank was found
1504 _dbus_string_find_blank (const DBusString *str,
1509 DBUS_CONST_STRING_PREAMBLE (str);
1510 _dbus_assert (start <= real->len);
1511 _dbus_assert (start >= 0);
1514 while (i < real->len)
1516 if (real->str[i] == ' ' ||
1517 real->str[i] == '\t')
1534 * Skips blanks from start, storing the first non-blank in *end
1535 * (blank is space or tab).
1537 * @param str the string
1538 * @param start where to start
1539 * @param end where to store the first non-blank byte index
1542 _dbus_string_skip_blank (const DBusString *str,
1547 DBUS_CONST_STRING_PREAMBLE (str);
1548 _dbus_assert (start <= real->len);
1549 _dbus_assert (start >= 0);
1552 while (i < real->len)
1554 if (!(real->str[i] == ' ' ||
1555 real->str[i] == '\t'))
1561 _dbus_assert (i == real->len || !(real->str[i] == ' ' ||
1562 real->str[i] == '\t'));
1569 * Skips whitespace from start, storing the first non-whitespace in *end.
1570 * (whitespace is space, tab, newline, CR).
1572 * @param str the string
1573 * @param start where to start
1574 * @param end where to store the first non-whitespace byte index
1577 _dbus_string_skip_white (const DBusString *str,
1582 DBUS_CONST_STRING_PREAMBLE (str);
1583 _dbus_assert (start <= real->len);
1584 _dbus_assert (start >= 0);
1587 while (i < real->len)
1589 if (!(real->str[i] == ' ' ||
1590 real->str[i] == '\n' ||
1591 real->str[i] == '\r' ||
1592 real->str[i] == '\t'))
1598 _dbus_assert (i == real->len || !(real->str[i] == ' ' ||
1599 real->str[i] == '\t'));
1606 * Assigns a newline-terminated or \r\n-terminated line from the front
1607 * of the string to the given dest string. The dest string's previous
1608 * contents are deleted. If the source string contains no newline,
1609 * moves the entire source string to the dest string.
1611 * @todo owen correctly notes that this is a stupid function (it was
1612 * written purely for test code,
1613 * e.g. dbus-message-builder.c). Probably should be enforced as test
1614 * code only with #ifdef DBUS_BUILD_TESTS
1616 * @param source the source string
1617 * @param dest the destination string (contents are replaced)
1618 * @returns #FALSE if no memory, or source has length 0
1621 _dbus_string_pop_line (DBusString *source,
1625 dbus_bool_t have_newline;
1627 _dbus_string_set_length (dest, 0);
1630 if (_dbus_string_find (source, 0, "\n", &eol))
1632 have_newline = TRUE;
1633 eol += 1; /* include newline */
1637 eol = _dbus_string_get_length (source);
1638 have_newline = FALSE;
1642 return FALSE; /* eof */
1644 if (!_dbus_string_move_len (source, 0, eol,
1650 /* dump the newline and the \r if we have one */
1653 dbus_bool_t have_cr;
1655 _dbus_assert (_dbus_string_get_length (dest) > 0);
1657 if (_dbus_string_get_length (dest) > 1 &&
1658 _dbus_string_get_byte (dest,
1659 _dbus_string_get_length (dest) - 2) == '\r')
1664 _dbus_string_set_length (dest,
1665 _dbus_string_get_length (dest) -
1673 * Deletes up to and including the first blank space
1676 * @param str the string
1679 _dbus_string_delete_first_word (DBusString *str)
1683 if (_dbus_string_find_blank (str, 0, &i))
1684 _dbus_string_skip_blank (str, i, &i);
1686 _dbus_string_delete (str, 0, i);
1690 * Deletes any leading blanks in the string
1692 * @param str the string
1695 _dbus_string_delete_leading_blanks (DBusString *str)
1699 _dbus_string_skip_blank (str, 0, &i);
1702 _dbus_string_delete (str, 0, i);
1706 * Tests two DBusString for equality.
1708 * @todo memcmp is probably faster
1710 * @param a first string
1711 * @param b second string
1712 * @returns #TRUE if equal
1715 _dbus_string_equal (const DBusString *a,
1716 const DBusString *b)
1718 const unsigned char *ap;
1719 const unsigned char *bp;
1720 const unsigned char *a_end;
1721 const DBusRealString *real_a = (const DBusRealString*) a;
1722 const DBusRealString *real_b = (const DBusRealString*) b;
1723 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1724 DBUS_GENERIC_STRING_PREAMBLE (real_b);
1726 if (real_a->len != real_b->len)
1731 a_end = real_a->str + real_a->len;
1745 * Tests two DBusString for equality up to the given length.
1747 * @todo write a unit test
1749 * @todo memcmp is probably faster
1751 * @param a first string
1752 * @param b second string
1753 * @param len the lengh
1754 * @returns #TRUE if equal for the given number of bytes
1757 _dbus_string_equal_len (const DBusString *a,
1758 const DBusString *b,
1761 const unsigned char *ap;
1762 const unsigned char *bp;
1763 const unsigned char *a_end;
1764 const DBusRealString *real_a = (const DBusRealString*) a;
1765 const DBusRealString *real_b = (const DBusRealString*) b;
1766 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1767 DBUS_GENERIC_STRING_PREAMBLE (real_b);
1769 if (real_a->len != real_b->len &&
1770 (real_a->len < len || real_b->len < len))
1775 a_end = real_a->str + MIN (real_a->len, len);
1789 * Checks whether a string is equal to a C string.
1791 * @param a the string
1792 * @param c_str the C string
1793 * @returns #TRUE if equal
1796 _dbus_string_equal_c_str (const DBusString *a,
1799 const unsigned char *ap;
1800 const unsigned char *bp;
1801 const unsigned char *a_end;
1802 const DBusRealString *real_a = (const DBusRealString*) a;
1803 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1804 _dbus_assert (c_str != NULL);
1807 bp = (const unsigned char*) c_str;
1808 a_end = real_a->str + real_a->len;
1809 while (ap != a_end && *bp)
1818 if (ap != a_end || *bp)
1825 * Checks whether a string starts with the given C string.
1827 * @param a the string
1828 * @param c_str the C string
1829 * @returns #TRUE if string starts with it
1832 _dbus_string_starts_with_c_str (const DBusString *a,
1835 const unsigned char *ap;
1836 const unsigned char *bp;
1837 const unsigned char *a_end;
1838 const DBusRealString *real_a = (const DBusRealString*) a;
1839 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1840 _dbus_assert (c_str != NULL);
1843 bp = (const unsigned char*) c_str;
1844 a_end = real_a->str + real_a->len;
1845 while (ap != a_end && *bp)
1861 * Returns whether a string ends with the given suffix
1863 * @todo memcmp might make this faster.
1865 * @param a the string
1866 * @param c_str the C-style string
1867 * @returns #TRUE if the string ends with the suffix
1870 _dbus_string_ends_with_c_str (const DBusString *a,
1873 const unsigned char *ap;
1874 const unsigned char *bp;
1875 const unsigned char *a_end;
1876 unsigned long c_str_len;
1877 const DBusRealString *real_a = (const DBusRealString*) a;
1878 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1879 _dbus_assert (c_str != NULL);
1881 c_str_len = strlen (c_str);
1882 if (((unsigned long)real_a->len) < c_str_len)
1885 ap = real_a->str + (real_a->len - c_str_len);
1886 bp = (const unsigned char*) c_str;
1887 a_end = real_a->str + real_a->len;
1897 _dbus_assert (*ap == '\0');
1898 _dbus_assert (*bp == '\0');
1903 static const signed char base64_table[] = {
1970 /** The minimum char that's a valid char in Base64-encoded text */
1971 #define UNBASE64_MIN_CHAR (43)
1972 /** The maximum char that's a valid char in Base64-encoded text */
1973 #define UNBASE64_MAX_CHAR (122)
1974 /** Must subtract this from a char's integer value before offsetting
1975 * into unbase64_table
1977 #define UNBASE64_TABLE_OFFSET UNBASE64_MIN_CHAR
1978 static const signed char unbase64_table[] = {
2062 * Encodes a string using Base64, as documented in RFC 2045.
2064 * @param source the string to encode
2065 * @param start byte index to start encoding
2066 * @param dest string where encoded data should be placed
2067 * @param insert_at where to place encoded data
2068 * @returns #TRUE if encoding was successful, #FALSE if no memory etc.
2071 _dbus_string_base64_encode (const DBusString *source,
2077 unsigned int dest_len; /* unsigned for overflow checks below */
2078 const unsigned char *s;
2080 const unsigned char *triplet_end;
2081 const unsigned char *final_end;
2082 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
2083 _dbus_assert (source != dest);
2085 /* For each 24 bits (3 bytes) of input, we have 4 bytes of
2088 source_len = real_source->len - start;
2089 dest_len = (source_len / 3) * 4;
2090 if (source_len % 3 != 0)
2093 if (dest_len > (unsigned int) real_dest->max_length)
2096 if (source_len == 0)
2099 if (!open_gap (dest_len, real_dest, insert_at))
2102 d = real_dest->str + insert_at;
2103 s = real_source->str + start;
2104 final_end = real_source->str + (start + source_len);
2105 triplet_end = final_end - (source_len % 3);
2106 _dbus_assert (triplet_end <= final_end);
2107 _dbus_assert ((final_end - triplet_end) < 3);
2109 #define ENCODE_64(v) (base64_table[ (unsigned char) (v) ])
2110 #define SIX_BITS_MASK (0x3f)
2111 _dbus_assert (SIX_BITS_MASK < _DBUS_N_ELEMENTS (base64_table));
2113 while (s != triplet_end)
2115 unsigned int triplet;
2117 triplet = s[2] | (s[1] << 8) | (s[0] << 16);
2119 /* Encode each 6 bits. */
2121 *d++ = ENCODE_64 (triplet >> 18);
2122 *d++ = ENCODE_64 ((triplet >> 12) & SIX_BITS_MASK);
2123 *d++ = ENCODE_64 ((triplet >> 6) & SIX_BITS_MASK);
2124 *d++ = ENCODE_64 (triplet & SIX_BITS_MASK);
2129 switch (final_end - triplet_end)
2133 unsigned int doublet;
2135 doublet = s[1] | (s[0] << 8);
2137 *d++ = ENCODE_64 (doublet >> 12);
2138 *d++ = ENCODE_64 ((doublet >> 6) & SIX_BITS_MASK);
2139 *d++ = ENCODE_64 (doublet & SIX_BITS_MASK);
2145 unsigned int singlet;
2149 *d++ = ENCODE_64 ((singlet >> 6) & SIX_BITS_MASK);
2150 *d++ = ENCODE_64 (singlet & SIX_BITS_MASK);
2159 _dbus_assert (d == (real_dest->str + (insert_at + dest_len)));
2165 * Decodes a string from Base64, as documented in RFC 2045.
2167 * @todo sort out the AUDIT comment in here. The case it mentions
2168 * ("====" or "x===") is not allowed in correct base64, so need to
2169 * decide what to do with that kind of input. Probably ignore it
2170 * since we ignore any other junk seen.
2172 * @param source the string to decode
2173 * @param start byte index to start decode
2174 * @param dest string where decoded data should be placed
2175 * @param insert_at where to place decoded data
2176 * @returns #TRUE if decoding was successful, #FALSE if no memory etc.
2179 _dbus_string_base64_decode (const DBusString *source,
2188 unsigned int triplet = 0;
2191 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
2192 _dbus_assert (source != dest);
2194 source_len = real_source->len - start;
2195 s = real_source->str + start;
2196 end = real_source->str + source_len;
2198 if (source_len == 0)
2201 if (!_dbus_string_init (&result))
2208 /* The idea is to just skip anything that isn't
2209 * a base64 char - it's allowed to have whitespace,
2210 * newlines, etc. in here. We also ignore trailing
2211 * base64 chars, though that's suspicious.
2214 if (*s >= UNBASE64_MIN_CHAR &&
2215 *s <= UNBASE64_MAX_CHAR)
2219 /* '=' is padding, doesn't represent additional data
2220 * but does increment our count.
2229 val = unbase64_table[(*s) - UNBASE64_TABLE_OFFSET];
2234 triplet |= (unsigned int) val;
2239 if (sextet_count == 4)
2241 /* no pad = 3 bytes, 1 pad = 2 bytes, 2 pad = 1 byte */
2244 /* AUDIT: Comment doesn't mention 4 pad => 0,
2245 * 3 pad => 1 byte, though the code should
2246 * work fine if those are the required outputs.
2248 * I assume that the spec requires dropping
2249 * the top two bits of, say, ///= which is > 2
2250 * bytes worth of bits. (Or otherwise, you couldn't
2251 * actually represent 2 byte sequences.
2256 if (!_dbus_string_append_byte (&result,
2263 if (!_dbus_string_append_byte (&result,
2264 (triplet >> 8) & 0xff))
2268 if (!_dbus_string_append_byte (&result,
2281 if (!_dbus_string_move (&result, 0, dest, insert_at))
2283 _dbus_string_free (&result);
2287 _dbus_string_free (&result);
2292 _dbus_string_free (&result);
2298 * Encodes a string in hex, the way MD5 and SHA-1 are usually
2299 * encoded. (Each byte is two hex digits.)
2301 * @param source the string to encode
2302 * @param start byte index to start encoding
2303 * @param dest string where encoded data should be placed
2304 * @param insert_at where to place encoded data
2305 * @returns #TRUE if encoding was successful, #FALSE if no memory etc.
2308 _dbus_string_hex_encode (const DBusString *source,
2314 const char hexdigits[16] = {
2315 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
2316 'a', 'b', 'c', 'd', 'e', 'f'
2318 const unsigned char *p;
2319 const unsigned char *end;
2322 _dbus_assert (start <= _dbus_string_get_length (source));
2324 if (!_dbus_string_init (&result))
2329 p = (const unsigned char*) _dbus_string_get_const_data (source);
2330 end = p + _dbus_string_get_length (source);
2335 if (!_dbus_string_append_byte (&result,
2336 hexdigits[(*p >> 4)]))
2339 if (!_dbus_string_append_byte (&result,
2340 hexdigits[(*p & 0x0f)]))
2346 if (!_dbus_string_move (&result, 0, dest, insert_at))
2352 _dbus_string_free (&result);
2357 * Decodes a string from hex encoding.
2359 * @param source the string to decode
2360 * @param start byte index to start decode
2361 * @param dest string where decoded data should be placed
2362 * @param insert_at where to place decoded data
2363 * @returns #TRUE if decoding was successful, #FALSE if no memory etc.
2366 _dbus_string_hex_decode (const DBusString *source,
2372 const unsigned char *p;
2373 const unsigned char *end;
2375 dbus_bool_t high_bits;
2377 _dbus_assert (start <= _dbus_string_get_length (source));
2379 if (!_dbus_string_init (&result))
2385 p = (const unsigned char*) _dbus_string_get_const_data (source);
2386 end = p + _dbus_string_get_length (source);
2451 _dbus_verbose ("invalid character '%c' in hex encoded text\n",
2458 if (!_dbus_string_append_byte (&result,
2467 len = _dbus_string_get_length (&result);
2469 b = _dbus_string_get_byte (&result, len - 1);
2473 _dbus_string_set_byte (&result, len - 1, b);
2476 high_bits = !high_bits;
2481 if (!_dbus_string_move (&result, 0, dest, insert_at))
2487 _dbus_string_free (&result);
2492 * Checks that the given range of the string is valid ASCII with no
2493 * nul bytes. If the given range is not entirely contained in the
2494 * string, returns #FALSE.
2496 * @todo this is inconsistent with most of DBusString in that
2497 * it allows a start,len range that isn't in the string.
2499 * @param str the string
2500 * @param start first byte index to check
2501 * @param len number of bytes to check
2502 * @returns #TRUE if the byte range exists and is all valid ASCII
2505 _dbus_string_validate_ascii (const DBusString *str,
2509 const unsigned char *s;
2510 const unsigned char *end;
2511 DBUS_CONST_STRING_PREAMBLE (str);
2512 _dbus_assert (start >= 0);
2513 _dbus_assert (start <= real->len);
2514 _dbus_assert (len >= 0);
2516 if (len > real->len - start)
2519 s = real->str + start;
2524 ((*s & ~0x7f) != 0))
2534 * Checks that the given range of the string is valid UTF-8. If the
2535 * given range is not entirely contained in the string, returns
2536 * #FALSE. If the string contains any nul bytes in the given range,
2537 * returns #FALSE. If the start and start+len are not on character
2538 * boundaries, returns #FALSE.
2540 * @todo this is inconsistent with most of DBusString in that
2541 * it allows a start,len range that isn't in the string.
2543 * @param str the string
2544 * @param start first byte index to check
2545 * @param len number of bytes to check
2546 * @returns #TRUE if the byte range exists and is all valid UTF-8
2549 _dbus_string_validate_utf8 (const DBusString *str,
2553 const unsigned char *p;
2554 const unsigned char *end;
2555 DBUS_CONST_STRING_PREAMBLE (str);
2556 _dbus_assert (start >= 0);
2557 _dbus_assert (start <= real->len);
2558 _dbus_assert (len >= 0);
2560 if (len > real->len - start)
2563 p = real->str + start;
2568 int i, mask = 0, char_len;
2569 dbus_unichar_t result;
2570 unsigned char c = (unsigned char) *p;
2572 UTF8_COMPUTE (c, mask, char_len);
2577 /* check that the expected number of bytes exists in the remaining length */
2578 if ((end - p) < char_len)
2581 UTF8_GET (result, p, i, mask, char_len);
2583 if (UTF8_LENGTH (result) != char_len) /* Check for overlong UTF-8 */
2586 if (result == (dbus_unichar_t)-1)
2589 if (!UNICODE_VALID (result))
2595 /* See that we covered the entire length if a length was
2605 * Checks that the given range of the string is all nul bytes. If the
2606 * given range is not entirely contained in the string, returns
2609 * @todo this is inconsistent with most of DBusString in that
2610 * it allows a start,len range that isn't in the string.
2612 * @param str the string
2613 * @param start first byte index to check
2614 * @param len number of bytes to check
2615 * @returns #TRUE if the byte range exists and is all nul bytes
2618 _dbus_string_validate_nul (const DBusString *str,
2622 const unsigned char *s;
2623 const unsigned char *end;
2624 DBUS_CONST_STRING_PREAMBLE (str);
2625 _dbus_assert (start >= 0);
2626 _dbus_assert (len >= 0);
2627 _dbus_assert (start <= real->len);
2629 if (len > real->len - start)
2632 s = real->str + start;
2645 * Clears all allocated bytes in the string to zero.
2647 * @param str the string
2650 _dbus_string_zero (DBusString *str)
2652 DBUS_STRING_PREAMBLE (str);
2654 memset (real->str, '\0', real->allocated);
2658 #ifdef DBUS_BUILD_TESTS
2659 #include "dbus-test.h"
2663 test_max_len (DBusString *str,
2668 if (!_dbus_string_set_length (str, max_len - 1))
2669 _dbus_assert_not_reached ("setting len to one less than max should have worked");
2672 if (!_dbus_string_set_length (str, max_len))
2673 _dbus_assert_not_reached ("setting len to max len should have worked");
2675 if (_dbus_string_set_length (str, max_len + 1))
2676 _dbus_assert_not_reached ("setting len to one more than max len should not have worked");
2678 if (!_dbus_string_set_length (str, 0))
2679 _dbus_assert_not_reached ("setting len to zero should have worked");
2683 test_base64_roundtrip (const unsigned char *data,
2691 len = strlen (data);
2693 if (!_dbus_string_init (&orig))
2694 _dbus_assert_not_reached ("could not init string");
2696 if (!_dbus_string_init (&encoded))
2697 _dbus_assert_not_reached ("could not init string");
2699 if (!_dbus_string_init (&decoded))
2700 _dbus_assert_not_reached ("could not init string");
2702 if (!_dbus_string_append_len (&orig, data, len))
2703 _dbus_assert_not_reached ("couldn't append orig data");
2705 if (!_dbus_string_base64_encode (&orig, 0, &encoded, 0))
2706 _dbus_assert_not_reached ("could not encode");
2708 if (!_dbus_string_base64_decode (&encoded, 0, &decoded, 0))
2709 _dbus_assert_not_reached ("could not decode");
2711 if (!_dbus_string_equal (&orig, &decoded))
2715 printf ("Original string %d bytes encoded %d bytes decoded %d bytes\n",
2716 _dbus_string_get_length (&orig),
2717 _dbus_string_get_length (&encoded),
2718 _dbus_string_get_length (&decoded));
2719 printf ("Original: %s\n", data);
2720 s = _dbus_string_get_const_data (&decoded);
2721 printf ("Decoded: %s\n", s);
2722 _dbus_assert_not_reached ("original string not the same as string decoded from base64");
2725 _dbus_string_free (&orig);
2726 _dbus_string_free (&encoded);
2727 _dbus_string_free (&decoded);
2731 test_hex_roundtrip (const unsigned char *data,
2739 len = strlen (data);
2741 if (!_dbus_string_init (&orig))
2742 _dbus_assert_not_reached ("could not init string");
2744 if (!_dbus_string_init (&encoded))
2745 _dbus_assert_not_reached ("could not init string");
2747 if (!_dbus_string_init (&decoded))
2748 _dbus_assert_not_reached ("could not init string");
2750 if (!_dbus_string_append_len (&orig, data, len))
2751 _dbus_assert_not_reached ("couldn't append orig data");
2753 if (!_dbus_string_hex_encode (&orig, 0, &encoded, 0))
2754 _dbus_assert_not_reached ("could not encode");
2756 if (!_dbus_string_hex_decode (&encoded, 0, &decoded, 0))
2757 _dbus_assert_not_reached ("could not decode");
2759 if (!_dbus_string_equal (&orig, &decoded))
2763 printf ("Original string %d bytes encoded %d bytes decoded %d bytes\n",
2764 _dbus_string_get_length (&orig),
2765 _dbus_string_get_length (&encoded),
2766 _dbus_string_get_length (&decoded));
2767 printf ("Original: %s\n", data);
2768 s = _dbus_string_get_const_data (&decoded);
2769 printf ("Decoded: %s\n", s);
2770 _dbus_assert_not_reached ("original string not the same as string decoded from base64");
2773 _dbus_string_free (&orig);
2774 _dbus_string_free (&encoded);
2775 _dbus_string_free (&decoded);
2778 typedef void (* TestRoundtripFunc) (const unsigned char *data,
2781 test_roundtrips (TestRoundtripFunc func)
2783 (* func) ("Hello this is a string\n", -1);
2784 (* func) ("Hello this is a string\n1", -1);
2785 (* func) ("Hello this is a string\n12", -1);
2786 (* func) ("Hello this is a string\n123", -1);
2787 (* func) ("Hello this is a string\n1234", -1);
2788 (* func) ("Hello this is a string\n12345", -1);
2792 (* func) ("123", 3);
2793 (* func) ("1234", 4);
2794 (* func) ("12345", 5);
2798 (* func) ("123", 4);
2799 (* func) ("1234", 5);
2800 (* func) ("12345", 6);
2802 unsigned char buf[512];
2806 while (i < _DBUS_N_ELEMENTS (buf))
2812 while (i < _DBUS_N_ELEMENTS (buf))
2822 * @ingroup DBusStringInternals
2823 * Unit test for DBusString.
2825 * @todo Need to write tests for _dbus_string_copy() and
2826 * _dbus_string_move() moving to/from each of start/middle/end of a
2827 * string. Also need tests for _dbus_string_move_len ()
2829 * @returns #TRUE on success.
2832 _dbus_string_test (void)
2839 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 };
2844 while (i < _DBUS_N_ELEMENTS (lens))
2846 if (!_dbus_string_init (&str))
2847 _dbus_assert_not_reached ("failed to init string");
2849 set_max_length (&str, lens[i]);
2851 test_max_len (&str, lens[i]);
2852 _dbus_string_free (&str);
2857 /* Test shortening and setting length */
2859 while (i < _DBUS_N_ELEMENTS (lens))
2863 if (!_dbus_string_init (&str))
2864 _dbus_assert_not_reached ("failed to init string");
2866 set_max_length (&str, lens[i]);
2868 if (!_dbus_string_set_length (&str, lens[i]))
2869 _dbus_assert_not_reached ("failed to set string length");
2874 _dbus_assert (_dbus_string_get_length (&str) == j);
2877 _dbus_string_shorten (&str, 1);
2878 _dbus_assert (_dbus_string_get_length (&str) == (j - 1));
2883 _dbus_string_free (&str);
2888 /* Test appending data */
2889 if (!_dbus_string_init (&str))
2890 _dbus_assert_not_reached ("failed to init string");
2895 if (!_dbus_string_append (&str, "a"))
2896 _dbus_assert_not_reached ("failed to append string to string\n");
2898 _dbus_assert (_dbus_string_get_length (&str) == i * 2 + 1);
2900 if (!_dbus_string_append_byte (&str, 'b'))
2901 _dbus_assert_not_reached ("failed to append byte to string\n");
2903 _dbus_assert (_dbus_string_get_length (&str) == i * 2 + 2);
2908 _dbus_string_free (&str);
2910 /* Check steal_data */
2912 if (!_dbus_string_init (&str))
2913 _dbus_assert_not_reached ("failed to init string");
2915 if (!_dbus_string_append (&str, "Hello World"))
2916 _dbus_assert_not_reached ("could not append to string");
2918 i = _dbus_string_get_length (&str);
2920 if (!_dbus_string_steal_data (&str, &s))
2921 _dbus_assert_not_reached ("failed to steal data");
2923 _dbus_assert (_dbus_string_get_length (&str) == 0);
2924 _dbus_assert (((int)strlen (s)) == i);
2930 if (!_dbus_string_append (&str, "Hello World"))
2931 _dbus_assert_not_reached ("could not append to string");
2933 i = _dbus_string_get_length (&str);
2935 if (!_dbus_string_init (&other))
2936 _dbus_assert_not_reached ("could not init string");
2938 if (!_dbus_string_move (&str, 0, &other, 0))
2939 _dbus_assert_not_reached ("could not move");
2941 _dbus_assert (_dbus_string_get_length (&str) == 0);
2942 _dbus_assert (_dbus_string_get_length (&other) == i);
2944 if (!_dbus_string_append (&str, "Hello World"))
2945 _dbus_assert_not_reached ("could not append to string");
2947 if (!_dbus_string_move (&str, 0, &other, _dbus_string_get_length (&other)))
2948 _dbus_assert_not_reached ("could not move");
2950 _dbus_assert (_dbus_string_get_length (&str) == 0);
2951 _dbus_assert (_dbus_string_get_length (&other) == i * 2);
2953 if (!_dbus_string_append (&str, "Hello World"))
2954 _dbus_assert_not_reached ("could not append to string");
2956 if (!_dbus_string_move (&str, 0, &other, _dbus_string_get_length (&other) / 2))
2957 _dbus_assert_not_reached ("could not move");
2959 _dbus_assert (_dbus_string_get_length (&str) == 0);
2960 _dbus_assert (_dbus_string_get_length (&other) == i * 3);
2962 _dbus_string_free (&other);
2966 if (!_dbus_string_append (&str, "Hello World"))
2967 _dbus_assert_not_reached ("could not append to string");
2969 i = _dbus_string_get_length (&str);
2971 if (!_dbus_string_init (&other))
2972 _dbus_assert_not_reached ("could not init string");
2974 if (!_dbus_string_copy (&str, 0, &other, 0))
2975 _dbus_assert_not_reached ("could not copy");
2977 _dbus_assert (_dbus_string_get_length (&str) == i);
2978 _dbus_assert (_dbus_string_get_length (&other) == i);
2980 if (!_dbus_string_copy (&str, 0, &other, _dbus_string_get_length (&other)))
2981 _dbus_assert_not_reached ("could not copy");
2983 _dbus_assert (_dbus_string_get_length (&str) == i);
2984 _dbus_assert (_dbus_string_get_length (&other) == i * 2);
2985 _dbus_assert (_dbus_string_equal_c_str (&other,
2986 "Hello WorldHello World"));
2988 if (!_dbus_string_copy (&str, 0, &other, _dbus_string_get_length (&other) / 2))
2989 _dbus_assert_not_reached ("could not copy");
2991 _dbus_assert (_dbus_string_get_length (&str) == i);
2992 _dbus_assert (_dbus_string_get_length (&other) == i * 3);
2993 _dbus_assert (_dbus_string_equal_c_str (&other,
2994 "Hello WorldHello WorldHello World"));
2996 _dbus_string_free (&str);
2997 _dbus_string_free (&other);
3001 if (!_dbus_string_init (&str))
3002 _dbus_assert_not_reached ("failed to init string");
3004 if (!_dbus_string_append (&str, "Hello World"))
3005 _dbus_assert_not_reached ("could not append to string");
3007 i = _dbus_string_get_length (&str);
3009 if (!_dbus_string_init (&other))
3010 _dbus_assert_not_reached ("could not init string");
3012 if (!_dbus_string_replace_len (&str, 0, _dbus_string_get_length (&str),
3013 &other, 0, _dbus_string_get_length (&other)))
3014 _dbus_assert_not_reached ("could not replace");
3016 _dbus_assert (_dbus_string_get_length (&str) == i);
3017 _dbus_assert (_dbus_string_get_length (&other) == i);
3018 _dbus_assert (_dbus_string_equal_c_str (&other, "Hello World"));
3020 if (!_dbus_string_replace_len (&str, 0, _dbus_string_get_length (&str),
3022 _dbus_assert_not_reached ("could not replace center space");
3024 _dbus_assert (_dbus_string_get_length (&str) == i);
3025 _dbus_assert (_dbus_string_get_length (&other) == i * 2 - 1);
3026 _dbus_assert (_dbus_string_equal_c_str (&other,
3027 "HelloHello WorldWorld"));
3030 if (!_dbus_string_replace_len (&str, 1, 1,
3032 _dbus_string_get_length (&other) - 1,
3034 _dbus_assert_not_reached ("could not replace end character");
3036 _dbus_assert (_dbus_string_get_length (&str) == i);
3037 _dbus_assert (_dbus_string_get_length (&other) == i * 2 - 1);
3038 _dbus_assert (_dbus_string_equal_c_str (&other,
3039 "HelloHello WorldWorle"));
3041 _dbus_string_free (&str);
3042 _dbus_string_free (&other);
3044 /* Check append/get unichar */
3046 if (!_dbus_string_init (&str))
3047 _dbus_assert_not_reached ("failed to init string");
3050 if (!_dbus_string_append_unichar (&str, 0xfffc))
3051 _dbus_assert_not_reached ("failed to append unichar");
3053 _dbus_string_get_unichar (&str, 0, &ch, &i);
3055 _dbus_assert (ch == 0xfffc);
3056 _dbus_assert (i == _dbus_string_get_length (&str));
3058 _dbus_string_free (&str);
3060 /* Check insert/set/get byte */
3062 if (!_dbus_string_init (&str))
3063 _dbus_assert_not_reached ("failed to init string");
3065 if (!_dbus_string_append (&str, "Hello"))
3066 _dbus_assert_not_reached ("failed to append Hello");
3068 _dbus_assert (_dbus_string_get_byte (&str, 0) == 'H');
3069 _dbus_assert (_dbus_string_get_byte (&str, 1) == 'e');
3070 _dbus_assert (_dbus_string_get_byte (&str, 2) == 'l');
3071 _dbus_assert (_dbus_string_get_byte (&str, 3) == 'l');
3072 _dbus_assert (_dbus_string_get_byte (&str, 4) == 'o');
3074 _dbus_string_set_byte (&str, 1, 'q');
3075 _dbus_assert (_dbus_string_get_byte (&str, 1) == 'q');
3077 if (!_dbus_string_insert_byte (&str, 0, 255))
3078 _dbus_assert_not_reached ("can't insert byte");
3080 if (!_dbus_string_insert_byte (&str, 2, 'Z'))
3081 _dbus_assert_not_reached ("can't insert byte");
3083 if (!_dbus_string_insert_byte (&str, _dbus_string_get_length (&str), 'W'))
3084 _dbus_assert_not_reached ("can't insert byte");
3086 _dbus_assert (_dbus_string_get_byte (&str, 0) == 255);
3087 _dbus_assert (_dbus_string_get_byte (&str, 1) == 'H');
3088 _dbus_assert (_dbus_string_get_byte (&str, 2) == 'Z');
3089 _dbus_assert (_dbus_string_get_byte (&str, 3) == 'q');
3090 _dbus_assert (_dbus_string_get_byte (&str, 4) == 'l');
3091 _dbus_assert (_dbus_string_get_byte (&str, 5) == 'l');
3092 _dbus_assert (_dbus_string_get_byte (&str, 6) == 'o');
3093 _dbus_assert (_dbus_string_get_byte (&str, 7) == 'W');
3095 _dbus_string_free (&str);
3097 /* Check append/parse int/double */
3099 if (!_dbus_string_init (&str))
3100 _dbus_assert_not_reached ("failed to init string");
3102 if (!_dbus_string_append_int (&str, 27))
3103 _dbus_assert_not_reached ("failed to append int");
3105 i = _dbus_string_get_length (&str);
3107 if (!_dbus_string_parse_int (&str, 0, &v, &end))
3108 _dbus_assert_not_reached ("failed to parse int");
3110 _dbus_assert (v == 27);
3111 _dbus_assert (end == i);
3113 _dbus_string_free (&str);
3115 if (!_dbus_string_init (&str))
3116 _dbus_assert_not_reached ("failed to init string");
3118 if (!_dbus_string_append_double (&str, 50.3))
3119 _dbus_assert_not_reached ("failed to append float");
3121 i = _dbus_string_get_length (&str);
3123 if (!_dbus_string_parse_double (&str, 0, &d, &end))
3124 _dbus_assert_not_reached ("failed to parse float");
3126 _dbus_assert (d > (50.3 - 1e-6) && d < (50.3 + 1e-6));
3127 _dbus_assert (end == i);
3129 _dbus_string_free (&str);
3132 if (!_dbus_string_init (&str))
3133 _dbus_assert_not_reached ("failed to init string");
3135 if (!_dbus_string_append (&str, "Hello"))
3136 _dbus_assert_not_reached ("couldn't append to string");
3138 if (!_dbus_string_find (&str, 0, "He", &i))
3139 _dbus_assert_not_reached ("didn't find 'He'");
3140 _dbus_assert (i == 0);
3142 if (!_dbus_string_find (&str, 0, "Hello", &i))
3143 _dbus_assert_not_reached ("didn't find 'Hello'");
3144 _dbus_assert (i == 0);
3146 if (!_dbus_string_find (&str, 0, "ello", &i))
3147 _dbus_assert_not_reached ("didn't find 'ello'");
3148 _dbus_assert (i == 1);
3150 if (!_dbus_string_find (&str, 0, "lo", &i))
3151 _dbus_assert_not_reached ("didn't find 'lo'");
3152 _dbus_assert (i == 3);
3154 if (!_dbus_string_find (&str, 2, "lo", &i))
3155 _dbus_assert_not_reached ("didn't find 'lo'");
3156 _dbus_assert (i == 3);
3158 if (_dbus_string_find (&str, 4, "lo", &i))
3159 _dbus_assert_not_reached ("did find 'lo'");
3161 if (!_dbus_string_find (&str, 0, "l", &i))
3162 _dbus_assert_not_reached ("didn't find 'l'");
3163 _dbus_assert (i == 2);
3165 if (!_dbus_string_find (&str, 0, "H", &i))
3166 _dbus_assert_not_reached ("didn't find 'H'");
3167 _dbus_assert (i == 0);
3169 if (!_dbus_string_find (&str, 0, "", &i))
3170 _dbus_assert_not_reached ("didn't find ''");
3171 _dbus_assert (i == 0);
3173 if (_dbus_string_find (&str, 0, "Hello!", NULL))
3174 _dbus_assert_not_reached ("Did find 'Hello!'");
3176 if (_dbus_string_find (&str, 0, "Oh, Hello", NULL))
3177 _dbus_assert_not_reached ("Did find 'Oh, Hello'");
3179 if (_dbus_string_find (&str, 0, "ill", NULL))
3180 _dbus_assert_not_reached ("Did find 'ill'");
3182 if (_dbus_string_find (&str, 0, "q", NULL))
3183 _dbus_assert_not_reached ("Did find 'q'");
3185 if (!_dbus_string_find_to (&str, 0, 2, "He", NULL))
3186 _dbus_assert_not_reached ("Didn't find 'He'");
3188 if (_dbus_string_find_to (&str, 0, 2, "Hello", NULL))
3189 _dbus_assert_not_reached ("Did find 'Hello'");
3191 if (!_dbus_string_find_byte_backward (&str, _dbus_string_get_length (&str), 'H', &i))
3192 _dbus_assert_not_reached ("Did not find 'H'");
3193 _dbus_assert (i == 0);
3195 if (!_dbus_string_find_byte_backward (&str, _dbus_string_get_length (&str), 'o', &i))
3196 _dbus_assert_not_reached ("Did not find 'o'");
3197 _dbus_assert (i == _dbus_string_get_length (&str) - 1);
3199 if (_dbus_string_find_byte_backward (&str, _dbus_string_get_length (&str) - 1, 'o', &i))
3200 _dbus_assert_not_reached ("Did find 'o'");
3201 _dbus_assert (i == -1);
3203 if (_dbus_string_find_byte_backward (&str, 1, 'e', &i))
3204 _dbus_assert_not_reached ("Did find 'e'");
3205 _dbus_assert (i == -1);
3207 if (!_dbus_string_find_byte_backward (&str, 2, 'e', &i))
3208 _dbus_assert_not_reached ("Didn't find 'e'");
3209 _dbus_assert (i == 1);
3211 _dbus_string_free (&str);
3213 /* Base 64 and Hex encoding */
3214 test_roundtrips (test_base64_roundtrip);
3215 test_roundtrips (test_hex_roundtrip);
3220 #endif /* DBUS_BUILD_TESTS */