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 * @todo should return the const char* instead of using an out param;
476 * the temporary variable encourages a bug where you use const data
477 * after modifying the string and possibly causing a realloc.
479 * @param str the string
480 * @param start byte offset to return
481 * @param len length of segment to return
482 * @returns the string data
485 _dbus_string_get_const_data_len (const DBusString *str,
489 DBUS_CONST_STRING_PREAMBLE (str);
490 _dbus_assert (start >= 0);
491 _dbus_assert (len >= 0);
492 _dbus_assert (start <= real->len);
493 _dbus_assert (len <= real->len - start);
495 return real->str + start;
499 * Sets the value of the byte at the given position.
501 * @param str the string
502 * @param i the position
503 * @param byte the new value
506 _dbus_string_set_byte (DBusString *str,
510 DBUS_STRING_PREAMBLE (str);
511 _dbus_assert (i < real->len);
512 _dbus_assert (i >= 0);
518 * Gets the byte at the given position.
520 * @param str the string
521 * @param start the position
522 * @returns the byte at that position
525 _dbus_string_get_byte (const DBusString *str,
528 DBUS_CONST_STRING_PREAMBLE (str);
529 _dbus_assert (start < real->len);
530 _dbus_assert (start >= 0);
532 return real->str[start];
536 * Inserts the given byte at the given position.
538 * @param str the string
539 * @param i the position
540 * @param byte the value to insert
541 * @returns #TRUE on success
544 _dbus_string_insert_byte (DBusString *str,
548 DBUS_STRING_PREAMBLE (str);
549 _dbus_assert (i <= real->len);
550 _dbus_assert (i >= 0);
552 if (!open_gap (1, real, i))
561 * Like _dbus_string_get_data(), but removes the
562 * gotten data from the original string. The caller
563 * must free the data returned. This function may
564 * fail due to lack of memory, and return #FALSE.
566 * @param str the string
567 * @param data_return location to return the buffer
568 * @returns #TRUE on success
571 _dbus_string_steal_data (DBusString *str,
575 DBUS_STRING_PREAMBLE (str);
576 _dbus_assert (data_return != NULL);
578 undo_alignment (real);
580 *data_return = real->str;
582 old_max_length = real->max_length;
584 /* reset the string */
585 if (!_dbus_string_init (str))
587 /* hrm, put it back then */
588 real->str = *data_return;
590 fixup_alignment (real);
594 real->max_length = old_max_length;
600 * Like _dbus_string_get_data_len(), but removes the gotten data from
601 * the original string. The caller must free the data returned. This
602 * function may fail due to lack of memory, and return #FALSE.
603 * The returned string is nul-terminated and has length len.
605 * @todo this function is broken because on failure it
606 * may corrupt the source string.
608 * @param str the string
609 * @param data_return location to return the buffer
610 * @param start the start of segment to steal
611 * @param len the length of segment to steal
612 * @returns #TRUE on success
615 _dbus_string_steal_data_len (DBusString *str,
621 DBUS_STRING_PREAMBLE (str);
622 _dbus_assert (data_return != NULL);
623 _dbus_assert (start >= 0);
624 _dbus_assert (len >= 0);
625 _dbus_assert (start <= real->len);
626 _dbus_assert (len <= real->len - start);
628 if (!_dbus_string_init (&dest))
631 set_max_length (&dest, real->max_length);
633 if (!_dbus_string_move_len (str, start, len, &dest, 0))
635 _dbus_string_free (&dest);
639 _dbus_warn ("Broken code in _dbus_string_steal_data_len(), see @todo, FIXME\n");
640 if (!_dbus_string_steal_data (&dest, data_return))
642 _dbus_string_free (&dest);
646 _dbus_string_free (&dest);
652 * Copies the data from the string into a char*
654 * @param str the string
655 * @param data_return place to return the data
656 * @returns #TRUE on success, #FALSE on no memory
659 _dbus_string_copy_data (const DBusString *str,
662 DBUS_CONST_STRING_PREAMBLE (str);
663 _dbus_assert (data_return != NULL);
665 *data_return = dbus_malloc (real->len + 1);
666 if (*data_return == NULL)
669 memcpy (*data_return, real->str, real->len + 1);
675 * Copies a segment of the string into a char*
677 * @param str the string
678 * @param data_return place to return the data
679 * @param start start index
680 * @param len length to copy
681 * @returns #FALSE if no memory
684 _dbus_string_copy_data_len (const DBusString *str,
691 DBUS_CONST_STRING_PREAMBLE (str);
692 _dbus_assert (data_return != NULL);
693 _dbus_assert (start >= 0);
694 _dbus_assert (len >= 0);
695 _dbus_assert (start <= real->len);
696 _dbus_assert (len <= real->len - start);
698 if (!_dbus_string_init (&dest))
701 set_max_length (&dest, real->max_length);
703 if (!_dbus_string_copy_len (str, start, len, &dest, 0))
705 _dbus_string_free (&dest);
709 if (!_dbus_string_steal_data (&dest, data_return))
711 _dbus_string_free (&dest);
715 _dbus_string_free (&dest);
720 * Gets the length of a string (not including nul termination).
722 * @returns the length.
725 _dbus_string_get_length (const DBusString *str)
727 DBUS_CONST_STRING_PREAMBLE (str);
733 * Makes a string longer by the given number of bytes. Checks whether
734 * adding additional_length to the current length would overflow an
735 * integer, and checks for exceeding a string's max length.
736 * The new bytes are not initialized, other than nul-terminating
737 * the end of the string. The uninitialized bytes may contain
738 * nul bytes or other junk.
740 * @param str a string
741 * @param additional_length length to add to the string.
742 * @returns #TRUE on success.
745 _dbus_string_lengthen (DBusString *str,
746 int additional_length)
748 DBUS_STRING_PREAMBLE (str);
749 _dbus_assert (additional_length >= 0);
751 if (additional_length > real->max_length - real->len)
752 return FALSE; /* would overflow */
754 return set_length (real,
755 real->len + additional_length);
759 * Makes a string shorter by the given number of bytes.
761 * @param str a string
762 * @param length_to_remove length to remove from the string.
765 _dbus_string_shorten (DBusString *str,
766 int length_to_remove)
768 DBUS_STRING_PREAMBLE (str);
769 _dbus_assert (length_to_remove >= 0);
770 _dbus_assert (length_to_remove <= real->len);
773 real->len - length_to_remove);
777 * Sets the length of a string. Can be used to truncate or lengthen
778 * the string. If the string is lengthened, the function may fail and
779 * return #FALSE. Newly-added bytes are not initialized, as with
780 * _dbus_string_lengthen().
782 * @param str a string
783 * @param length new length of the string.
784 * @returns #FALSE on failure.
787 _dbus_string_set_length (DBusString *str,
790 DBUS_STRING_PREAMBLE (str);
791 _dbus_assert (length >= 0);
793 return set_length (real, length);
797 * Align the length of a string to a specific alignment (typically 4 or 8)
798 * by appending nul bytes to the string.
800 * @param str a string
801 * @param alignment the alignment
802 * @returns #FALSE if no memory
805 _dbus_string_align_length (DBusString *str,
808 unsigned long new_len; /* ulong to avoid _DBUS_ALIGN_VALUE overflow */
810 DBUS_STRING_PREAMBLE (str);
811 _dbus_assert (alignment >= 1);
812 _dbus_assert (alignment <= 8); /* it has to be a bug if > 8 */
814 new_len = _DBUS_ALIGN_VALUE (real->len, alignment);
815 if (new_len > (unsigned long) real->max_length)
818 delta = new_len - real->len;
819 _dbus_assert (delta >= 0);
824 if (!set_length (real, new_len))
827 memset (real->str + (new_len - delta),
834 append (DBusRealString *real,
841 if (!_dbus_string_lengthen ((DBusString*)real, buffer_len))
844 memcpy (real->str + (real->len - buffer_len),
852 * Appends a nul-terminated C-style string to a DBusString.
854 * @param str the DBusString
855 * @param buffer the nul-terminated characters to append
856 * @returns #FALSE if not enough memory.
859 _dbus_string_append (DBusString *str,
862 unsigned long buffer_len;
864 DBUS_STRING_PREAMBLE (str);
865 _dbus_assert (buffer != NULL);
867 buffer_len = strlen (buffer);
868 if (buffer_len > (unsigned long) real->max_length)
871 return append (real, buffer, buffer_len);
875 * Appends block of bytes with the given length to a DBusString.
877 * @param str the DBusString
878 * @param buffer the bytes to append
879 * @param len the number of bytes to append
880 * @returns #FALSE if not enough memory.
883 _dbus_string_append_len (DBusString *str,
887 DBUS_STRING_PREAMBLE (str);
888 _dbus_assert (buffer != NULL);
889 _dbus_assert (len >= 0);
891 return append (real, buffer, len);
895 * Appends a single byte to the string, returning #FALSE
896 * if not enough memory.
898 * @param str the string
899 * @param byte the byte to append
900 * @returns #TRUE on success
903 _dbus_string_append_byte (DBusString *str,
906 DBUS_STRING_PREAMBLE (str);
908 if (!set_length (real, real->len + 1))
911 real->str[real->len-1] = byte;
917 * Appends a single Unicode character, encoding the character
920 * @param str the string
921 * @param ch the Unicode character
924 _dbus_string_append_unichar (DBusString *str,
932 DBUS_STRING_PREAMBLE (str);
934 /* this code is from GLib but is pretty standard I think */
948 else if (ch < 0x10000)
953 else if (ch < 0x200000)
958 else if (ch < 0x4000000)
969 if (len > (real->max_length - real->len))
970 return FALSE; /* real->len + len would overflow */
972 if (!set_length (real, real->len + len))
975 out = real->str + (real->len - len);
977 for (i = len - 1; i > 0; --i)
979 out[i] = (ch & 0x3f) | 0x80;
988 delete (DBusRealString *real,
995 memmove (real->str + start, real->str + start + len, real->len - (start + len));
997 real->str[real->len] = '\0';
1001 * Deletes a segment of a DBusString with length len starting at
1002 * start. (Hint: to clear an entire string, setting length to 0
1003 * with _dbus_string_set_length() is easier.)
1005 * @param str the DBusString
1006 * @param start where to start deleting
1007 * @param len the number of bytes to delete
1010 _dbus_string_delete (DBusString *str,
1014 DBUS_STRING_PREAMBLE (str);
1015 _dbus_assert (start >= 0);
1016 _dbus_assert (len >= 0);
1017 _dbus_assert (start <= real->len);
1018 _dbus_assert (len <= real->len - start);
1020 delete (real, start, len);
1024 copy (DBusRealString *source,
1027 DBusRealString *dest,
1033 if (!open_gap (len, dest, insert_at))
1036 memcpy (dest->str + insert_at,
1037 source->str + start,
1044 * Checks assertions for two strings we're copying a segment between,
1045 * and declares real_source/real_dest variables.
1047 * @param source the source string
1048 * @param start the starting offset
1049 * @param dest the dest string
1050 * @param insert_at where the copied segment is inserted
1052 #define DBUS_STRING_COPY_PREAMBLE(source, start, dest, insert_at) \
1053 DBusRealString *real_source = (DBusRealString*) source; \
1054 DBusRealString *real_dest = (DBusRealString*) dest; \
1055 _dbus_assert ((source) != (dest)); \
1056 DBUS_GENERIC_STRING_PREAMBLE (real_source); \
1057 DBUS_GENERIC_STRING_PREAMBLE (real_dest); \
1058 _dbus_assert (!real_dest->constant); \
1059 _dbus_assert (!real_dest->locked); \
1060 _dbus_assert ((start) >= 0); \
1061 _dbus_assert ((start) <= real_source->len); \
1062 _dbus_assert ((insert_at) >= 0); \
1063 _dbus_assert ((insert_at) <= real_dest->len)
1066 * Moves the end of one string into another string. Both strings
1067 * must be initialized, valid strings.
1069 * @param source the source string
1070 * @param start where to chop off the source string
1071 * @param dest the destination string
1072 * @param insert_at where to move the chopped-off part of source string
1073 * @returns #FALSE if not enough memory
1076 _dbus_string_move (DBusString *source,
1081 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1083 if (!copy (real_source, start,
1084 real_source->len - start,
1089 delete (real_source, start,
1090 real_source->len - start);
1096 * Like _dbus_string_move(), but does not delete the section
1097 * of the source string that's copied to the dest string.
1099 * @param source the source string
1100 * @param start where to start copying the source string
1101 * @param dest the destination string
1102 * @param insert_at where to place the copied part of source string
1103 * @returns #FALSE if not enough memory
1106 _dbus_string_copy (const DBusString *source,
1111 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1113 return copy (real_source, start,
1114 real_source->len - start,
1120 * Like _dbus_string_move(), but can move a segment from
1121 * the middle of the source string.
1123 * @param source the source string
1124 * @param start first byte of source string to move
1125 * @param len length of segment to move
1126 * @param dest the destination string
1127 * @param insert_at where to move the bytes from the source string
1128 * @returns #FALSE if not enough memory
1131 _dbus_string_move_len (DBusString *source,
1138 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1139 _dbus_assert (len >= 0);
1140 _dbus_assert ((start + len) <= real_source->len);
1142 if (!copy (real_source, start, len,
1147 delete (real_source, start,
1154 * Like _dbus_string_copy(), but can copy a segment from the middle of
1155 * the source string.
1157 * @param source the source string
1158 * @param start where to start copying the source string
1159 * @param len length of segment to copy
1160 * @param dest the destination string
1161 * @param insert_at where to place the copied segment of source string
1162 * @returns #FALSE if not enough memory
1165 _dbus_string_copy_len (const DBusString *source,
1171 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1172 _dbus_assert (len >= 0);
1173 _dbus_assert (start <= real_source->len);
1174 _dbus_assert (len <= real_source->len - start);
1176 return copy (real_source, start, len,
1182 * Replaces a segment of dest string with a segment of source string.
1184 * @todo optimize the case where the two lengths are the same, and
1185 * avoid memmoving the data in the trailing part of the string twice.
1187 * @todo avoid inserting the source into dest, then deleting
1188 * the replaced chunk of dest (which creates a potentially large
1189 * intermediate string). Instead, extend the replaced chunk
1190 * of dest with padding to the same size as the source chunk,
1191 * then copy in the source bytes.
1193 * @param source the source string
1194 * @param start where to start copying the source string
1195 * @param len length of segment to copy
1196 * @param dest the destination string
1197 * @param replace_at start of segment of dest string to replace
1198 * @param replace_len length of segment of dest string to replace
1199 * @returns #FALSE if not enough memory
1203 _dbus_string_replace_len (const DBusString *source,
1210 DBUS_STRING_COPY_PREAMBLE (source, start, dest, replace_at);
1211 _dbus_assert (len >= 0);
1212 _dbus_assert (start <= real_source->len);
1213 _dbus_assert (len <= real_source->len - start);
1214 _dbus_assert (replace_at >= 0);
1215 _dbus_assert (replace_at <= real_dest->len);
1216 _dbus_assert (replace_len <= real_dest->len - replace_at);
1218 if (!copy (real_source, start, len,
1219 real_dest, replace_at))
1222 delete (real_dest, replace_at + len, replace_len);
1227 /* Unicode macros and utf8_validate() from GLib Owen Taylor, Havoc
1228 * Pennington, and Tom Tromey are the authors and authorized relicense.
1231 /** computes length and mask of a unicode character
1232 * @param Char the char
1233 * @param Mask the mask variable to assign to
1234 * @param Len the length variable to assign to
1236 #define UTF8_COMPUTE(Char, Mask, Len) \
1242 else if ((Char & 0xe0) == 0xc0) \
1247 else if ((Char & 0xf0) == 0xe0) \
1252 else if ((Char & 0xf8) == 0xf0) \
1257 else if ((Char & 0xfc) == 0xf8) \
1262 else if ((Char & 0xfe) == 0xfc) \
1271 * computes length of a unicode character in UTF-8
1272 * @param Char the char
1274 #define UTF8_LENGTH(Char) \
1275 ((Char) < 0x80 ? 1 : \
1276 ((Char) < 0x800 ? 2 : \
1277 ((Char) < 0x10000 ? 3 : \
1278 ((Char) < 0x200000 ? 4 : \
1279 ((Char) < 0x4000000 ? 5 : 6)))))
1282 * Gets a UTF-8 value.
1284 * @param Result variable for extracted unicode char.
1285 * @param Chars the bytes to decode
1286 * @param Count counter variable
1287 * @param Mask mask for this char
1288 * @param Len length for this char in bytes
1290 #define UTF8_GET(Result, Chars, Count, Mask, Len) \
1291 (Result) = (Chars)[0] & (Mask); \
1292 for ((Count) = 1; (Count) < (Len); ++(Count)) \
1294 if (((Chars)[(Count)] & 0xc0) != 0x80) \
1300 (Result) |= ((Chars)[(Count)] & 0x3f); \
1304 * Check whether a unicode char is in a valid range.
1306 * @param Char the character
1308 #define UNICODE_VALID(Char) \
1309 ((Char) < 0x110000 && \
1310 (((Char) & 0xFFFFF800) != 0xD800) && \
1311 ((Char) < 0xFDD0 || (Char) > 0xFDEF) && \
1312 ((Char) & 0xFFFF) != 0xFFFF)
1315 * Gets a unicode character from a UTF-8 string. Does no validation;
1316 * you must verify that the string is valid UTF-8 in advance and must
1317 * pass in the start of a character.
1319 * @param str the string
1320 * @param start the start of the UTF-8 character.
1321 * @param ch_return location to return the character
1322 * @param end_return location to return the byte index of next character
1325 _dbus_string_get_unichar (const DBusString *str,
1327 dbus_unichar_t *ch_return,
1331 dbus_unichar_t result;
1334 DBUS_CONST_STRING_PREAMBLE (str);
1335 _dbus_assert (start >= 0);
1336 _dbus_assert (start <= real->len);
1341 *end_return = real->len;
1344 p = real->str + start;
1347 UTF8_COMPUTE (c, mask, len);
1350 UTF8_GET (result, p, i, mask, len);
1352 if (result == (dbus_unichar_t)-1)
1356 *ch_return = result;
1358 *end_return = start + len;
1362 * Finds the given substring in the string,
1363 * returning #TRUE and filling in the byte index
1364 * where the substring was found, if it was found.
1365 * Returns #FALSE if the substring wasn't found.
1366 * Sets *start to the length of the string if the substring
1369 * @param str the string
1370 * @param start where to start looking
1371 * @param substr the substring
1372 * @param found return location for where it was found, or #NULL
1373 * @returns #TRUE if found
1376 _dbus_string_find (const DBusString *str,
1381 return _dbus_string_find_to (str, start,
1382 ((const DBusRealString*)str)->len,
1387 * Finds the given substring in the string,
1388 * up to a certain position,
1389 * returning #TRUE and filling in the byte index
1390 * where the substring was found, if it was found.
1391 * Returns #FALSE if the substring wasn't found.
1392 * Sets *start to the length of the string if the substring
1395 * @param str the string
1396 * @param start where to start looking
1397 * @param end where to stop looking
1398 * @param substr the substring
1399 * @param found return location for where it was found, or #NULL
1400 * @returns #TRUE if found
1403 _dbus_string_find_to (const DBusString *str,
1410 DBUS_CONST_STRING_PREAMBLE (str);
1411 _dbus_assert (substr != NULL);
1412 _dbus_assert (start <= real->len);
1413 _dbus_assert (start >= 0);
1414 _dbus_assert (substr != NULL);
1415 _dbus_assert (end <= real->len);
1416 _dbus_assert (start <= end);
1418 /* we always "find" an empty string */
1419 if (*substr == '\0')
1429 if (real->str[i] == substr[0])
1435 if (substr[j - i] == '\0')
1437 else if (real->str[j] != substr[j - i])
1443 if (substr[j - i] == '\0')
1461 * Find the given byte scanning backward from the given start.
1462 * Sets *found to -1 if the byte is not found.
1464 * @param str the string
1465 * @param start the place to start scanning (will not find the byte at this point)
1466 * @param byte the byte to find
1467 * @param found return location for where it was found
1468 * @returns #TRUE if found
1471 _dbus_string_find_byte_backward (const DBusString *str,
1477 DBUS_CONST_STRING_PREAMBLE (str);
1478 _dbus_assert (start <= real->len);
1479 _dbus_assert (start >= 0);
1480 _dbus_assert (found != NULL);
1485 if (real->str[i] == byte)
1498 * Finds a blank (space or tab) in the string. Returns #TRUE
1499 * if found, #FALSE otherwise. If a blank is not found sets
1500 * *found to the length of the string.
1502 * @param str the string
1503 * @param start byte index to start looking
1504 * @param found place to store the location of the first blank
1505 * @returns #TRUE if a blank was found
1508 _dbus_string_find_blank (const DBusString *str,
1513 DBUS_CONST_STRING_PREAMBLE (str);
1514 _dbus_assert (start <= real->len);
1515 _dbus_assert (start >= 0);
1518 while (i < real->len)
1520 if (real->str[i] == ' ' ||
1521 real->str[i] == '\t')
1538 * Skips blanks from start, storing the first non-blank in *end
1539 * (blank is space or tab).
1541 * @param str the string
1542 * @param start where to start
1543 * @param end where to store the first non-blank byte index
1546 _dbus_string_skip_blank (const DBusString *str,
1551 DBUS_CONST_STRING_PREAMBLE (str);
1552 _dbus_assert (start <= real->len);
1553 _dbus_assert (start >= 0);
1556 while (i < real->len)
1558 if (!(real->str[i] == ' ' ||
1559 real->str[i] == '\t'))
1565 _dbus_assert (i == real->len || !(real->str[i] == ' ' ||
1566 real->str[i] == '\t'));
1573 * Skips whitespace from start, storing the first non-whitespace in *end.
1574 * (whitespace is space, tab, newline, CR).
1576 * @param str the string
1577 * @param start where to start
1578 * @param end where to store the first non-whitespace byte index
1581 _dbus_string_skip_white (const DBusString *str,
1586 DBUS_CONST_STRING_PREAMBLE (str);
1587 _dbus_assert (start <= real->len);
1588 _dbus_assert (start >= 0);
1591 while (i < real->len)
1593 if (!(real->str[i] == ' ' ||
1594 real->str[i] == '\n' ||
1595 real->str[i] == '\r' ||
1596 real->str[i] == '\t'))
1602 _dbus_assert (i == real->len || !(real->str[i] == ' ' ||
1603 real->str[i] == '\t'));
1610 * Assigns a newline-terminated or \r\n-terminated line from the front
1611 * of the string to the given dest string. The dest string's previous
1612 * contents are deleted. If the source string contains no newline,
1613 * moves the entire source string to the dest string.
1615 * @todo owen correctly notes that this is a stupid function (it was
1616 * written purely for test code,
1617 * e.g. dbus-message-builder.c). Probably should be enforced as test
1618 * code only with #ifdef DBUS_BUILD_TESTS
1620 * @param source the source string
1621 * @param dest the destination string (contents are replaced)
1622 * @returns #FALSE if no memory, or source has length 0
1625 _dbus_string_pop_line (DBusString *source,
1629 dbus_bool_t have_newline;
1631 _dbus_string_set_length (dest, 0);
1634 if (_dbus_string_find (source, 0, "\n", &eol))
1636 have_newline = TRUE;
1637 eol += 1; /* include newline */
1641 eol = _dbus_string_get_length (source);
1642 have_newline = FALSE;
1646 return FALSE; /* eof */
1648 if (!_dbus_string_move_len (source, 0, eol,
1654 /* dump the newline and the \r if we have one */
1657 dbus_bool_t have_cr;
1659 _dbus_assert (_dbus_string_get_length (dest) > 0);
1661 if (_dbus_string_get_length (dest) > 1 &&
1662 _dbus_string_get_byte (dest,
1663 _dbus_string_get_length (dest) - 2) == '\r')
1668 _dbus_string_set_length (dest,
1669 _dbus_string_get_length (dest) -
1677 * Deletes up to and including the first blank space
1680 * @param str the string
1683 _dbus_string_delete_first_word (DBusString *str)
1687 if (_dbus_string_find_blank (str, 0, &i))
1688 _dbus_string_skip_blank (str, i, &i);
1690 _dbus_string_delete (str, 0, i);
1694 * Deletes any leading blanks in the string
1696 * @param str the string
1699 _dbus_string_delete_leading_blanks (DBusString *str)
1703 _dbus_string_skip_blank (str, 0, &i);
1706 _dbus_string_delete (str, 0, i);
1710 * Tests two DBusString for equality.
1712 * @todo memcmp is probably faster
1714 * @param a first string
1715 * @param b second string
1716 * @returns #TRUE if equal
1719 _dbus_string_equal (const DBusString *a,
1720 const DBusString *b)
1722 const unsigned char *ap;
1723 const unsigned char *bp;
1724 const unsigned char *a_end;
1725 const DBusRealString *real_a = (const DBusRealString*) a;
1726 const DBusRealString *real_b = (const DBusRealString*) b;
1727 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1728 DBUS_GENERIC_STRING_PREAMBLE (real_b);
1730 if (real_a->len != real_b->len)
1735 a_end = real_a->str + real_a->len;
1749 * Tests two DBusString for equality up to the given length.
1751 * @todo write a unit test
1753 * @todo memcmp is probably faster
1755 * @param a first string
1756 * @param b second string
1757 * @param len the lengh
1758 * @returns #TRUE if equal for the given number of bytes
1761 _dbus_string_equal_len (const DBusString *a,
1762 const DBusString *b,
1765 const unsigned char *ap;
1766 const unsigned char *bp;
1767 const unsigned char *a_end;
1768 const DBusRealString *real_a = (const DBusRealString*) a;
1769 const DBusRealString *real_b = (const DBusRealString*) b;
1770 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1771 DBUS_GENERIC_STRING_PREAMBLE (real_b);
1773 if (real_a->len != real_b->len &&
1774 (real_a->len < len || real_b->len < len))
1779 a_end = real_a->str + MIN (real_a->len, len);
1793 * Checks whether a string is equal to a C string.
1795 * @param a the string
1796 * @param c_str the C string
1797 * @returns #TRUE if equal
1800 _dbus_string_equal_c_str (const DBusString *a,
1803 const unsigned char *ap;
1804 const unsigned char *bp;
1805 const unsigned char *a_end;
1806 const DBusRealString *real_a = (const DBusRealString*) a;
1807 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1808 _dbus_assert (c_str != NULL);
1811 bp = (const unsigned char*) c_str;
1812 a_end = real_a->str + real_a->len;
1813 while (ap != a_end && *bp)
1822 if (ap != a_end || *bp)
1829 * Checks whether a string starts with the given C string.
1831 * @param a the string
1832 * @param c_str the C string
1833 * @returns #TRUE if string starts with it
1836 _dbus_string_starts_with_c_str (const DBusString *a,
1839 const unsigned char *ap;
1840 const unsigned char *bp;
1841 const unsigned char *a_end;
1842 const DBusRealString *real_a = (const DBusRealString*) a;
1843 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1844 _dbus_assert (c_str != NULL);
1847 bp = (const unsigned char*) c_str;
1848 a_end = real_a->str + real_a->len;
1849 while (ap != a_end && *bp)
1865 * Returns whether a string ends with the given suffix
1867 * @todo memcmp might make this faster.
1869 * @param a the string
1870 * @param c_str the C-style string
1871 * @returns #TRUE if the string ends with the suffix
1874 _dbus_string_ends_with_c_str (const DBusString *a,
1877 const unsigned char *ap;
1878 const unsigned char *bp;
1879 const unsigned char *a_end;
1880 unsigned long c_str_len;
1881 const DBusRealString *real_a = (const DBusRealString*) a;
1882 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1883 _dbus_assert (c_str != NULL);
1885 c_str_len = strlen (c_str);
1886 if (((unsigned long)real_a->len) < c_str_len)
1889 ap = real_a->str + (real_a->len - c_str_len);
1890 bp = (const unsigned char*) c_str;
1891 a_end = real_a->str + real_a->len;
1901 _dbus_assert (*ap == '\0');
1902 _dbus_assert (*bp == '\0');
1907 static const signed char base64_table[] = {
1974 /** The minimum char that's a valid char in Base64-encoded text */
1975 #define UNBASE64_MIN_CHAR (43)
1976 /** The maximum char that's a valid char in Base64-encoded text */
1977 #define UNBASE64_MAX_CHAR (122)
1978 /** Must subtract this from a char's integer value before offsetting
1979 * into unbase64_table
1981 #define UNBASE64_TABLE_OFFSET UNBASE64_MIN_CHAR
1982 static const signed char unbase64_table[] = {
2066 * Encodes a string using Base64, as documented in RFC 2045.
2068 * @param source the string to encode
2069 * @param start byte index to start encoding
2070 * @param dest string where encoded data should be placed
2071 * @param insert_at where to place encoded data
2072 * @returns #TRUE if encoding was successful, #FALSE if no memory etc.
2075 _dbus_string_base64_encode (const DBusString *source,
2081 unsigned int dest_len; /* unsigned for overflow checks below */
2082 const unsigned char *s;
2084 const unsigned char *triplet_end;
2085 const unsigned char *final_end;
2086 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
2087 _dbus_assert (source != dest);
2089 /* For each 24 bits (3 bytes) of input, we have 4 bytes of
2092 source_len = real_source->len - start;
2093 dest_len = (source_len / 3) * 4;
2094 if (source_len % 3 != 0)
2097 if (dest_len > (unsigned int) real_dest->max_length)
2100 if (source_len == 0)
2103 if (!open_gap (dest_len, real_dest, insert_at))
2106 d = real_dest->str + insert_at;
2107 s = real_source->str + start;
2108 final_end = real_source->str + (start + source_len);
2109 triplet_end = final_end - (source_len % 3);
2110 _dbus_assert (triplet_end <= final_end);
2111 _dbus_assert ((final_end - triplet_end) < 3);
2113 #define ENCODE_64(v) (base64_table[ (unsigned char) (v) ])
2114 #define SIX_BITS_MASK (0x3f)
2115 _dbus_assert (SIX_BITS_MASK < _DBUS_N_ELEMENTS (base64_table));
2117 while (s != triplet_end)
2119 unsigned int triplet;
2121 triplet = s[2] | (s[1] << 8) | (s[0] << 16);
2123 /* Encode each 6 bits. */
2125 *d++ = ENCODE_64 (triplet >> 18);
2126 *d++ = ENCODE_64 ((triplet >> 12) & SIX_BITS_MASK);
2127 *d++ = ENCODE_64 ((triplet >> 6) & SIX_BITS_MASK);
2128 *d++ = ENCODE_64 (triplet & SIX_BITS_MASK);
2133 switch (final_end - triplet_end)
2137 unsigned int doublet;
2139 doublet = s[1] | (s[0] << 8);
2141 *d++ = ENCODE_64 (doublet >> 12);
2142 *d++ = ENCODE_64 ((doublet >> 6) & SIX_BITS_MASK);
2143 *d++ = ENCODE_64 (doublet & SIX_BITS_MASK);
2149 unsigned int singlet;
2153 *d++ = ENCODE_64 ((singlet >> 6) & SIX_BITS_MASK);
2154 *d++ = ENCODE_64 (singlet & SIX_BITS_MASK);
2163 _dbus_assert (d == (real_dest->str + (insert_at + dest_len)));
2169 * Decodes a string from Base64, as documented in RFC 2045.
2171 * @todo sort out the AUDIT comment in here. The case it mentions
2172 * ("====" or "x===") is not allowed in correct base64, so need to
2173 * decide what to do with that kind of input. Probably ignore it
2174 * since we ignore any other junk seen.
2176 * @param source the string to decode
2177 * @param start byte index to start decode
2178 * @param dest string where decoded data should be placed
2179 * @param insert_at where to place decoded data
2180 * @returns #TRUE if decoding was successful, #FALSE if no memory etc.
2183 _dbus_string_base64_decode (const DBusString *source,
2192 unsigned int triplet = 0;
2195 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
2196 _dbus_assert (source != dest);
2198 source_len = real_source->len - start;
2199 s = real_source->str + start;
2200 end = real_source->str + source_len;
2202 if (source_len == 0)
2205 if (!_dbus_string_init (&result))
2212 /* The idea is to just skip anything that isn't
2213 * a base64 char - it's allowed to have whitespace,
2214 * newlines, etc. in here. We also ignore trailing
2215 * base64 chars, though that's suspicious.
2218 if (*s >= UNBASE64_MIN_CHAR &&
2219 *s <= UNBASE64_MAX_CHAR)
2223 /* '=' is padding, doesn't represent additional data
2224 * but does increment our count.
2233 val = unbase64_table[(*s) - UNBASE64_TABLE_OFFSET];
2238 triplet |= (unsigned int) val;
2243 if (sextet_count == 4)
2245 /* no pad = 3 bytes, 1 pad = 2 bytes, 2 pad = 1 byte */
2248 /* AUDIT: Comment doesn't mention 4 pad => 0,
2249 * 3 pad => 1 byte, though the code should
2250 * work fine if those are the required outputs.
2252 * I assume that the spec requires dropping
2253 * the top two bits of, say, ///= which is > 2
2254 * bytes worth of bits. (Or otherwise, you couldn't
2255 * actually represent 2 byte sequences.
2260 if (!_dbus_string_append_byte (&result,
2267 if (!_dbus_string_append_byte (&result,
2268 (triplet >> 8) & 0xff))
2272 if (!_dbus_string_append_byte (&result,
2285 if (!_dbus_string_move (&result, 0, dest, insert_at))
2287 _dbus_string_free (&result);
2291 _dbus_string_free (&result);
2296 _dbus_string_free (&result);
2302 * Encodes a string in hex, the way MD5 and SHA-1 are usually
2303 * encoded. (Each byte is two hex digits.)
2305 * @param source the string to encode
2306 * @param start byte index to start encoding
2307 * @param dest string where encoded data should be placed
2308 * @param insert_at where to place encoded data
2309 * @returns #TRUE if encoding was successful, #FALSE if no memory etc.
2312 _dbus_string_hex_encode (const DBusString *source,
2318 const char hexdigits[16] = {
2319 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
2320 'a', 'b', 'c', 'd', 'e', 'f'
2322 const unsigned char *p;
2323 const unsigned char *end;
2326 _dbus_assert (start <= _dbus_string_get_length (source));
2328 if (!_dbus_string_init (&result))
2333 p = (const unsigned char*) _dbus_string_get_const_data (source);
2334 end = p + _dbus_string_get_length (source);
2339 if (!_dbus_string_append_byte (&result,
2340 hexdigits[(*p >> 4)]))
2343 if (!_dbus_string_append_byte (&result,
2344 hexdigits[(*p & 0x0f)]))
2350 if (!_dbus_string_move (&result, 0, dest, insert_at))
2356 _dbus_string_free (&result);
2361 * Decodes a string from hex encoding.
2363 * @param source the string to decode
2364 * @param start byte index to start decode
2365 * @param dest string where decoded data should be placed
2366 * @param insert_at where to place decoded data
2367 * @returns #TRUE if decoding was successful, #FALSE if no memory etc.
2370 _dbus_string_hex_decode (const DBusString *source,
2376 const unsigned char *p;
2377 const unsigned char *end;
2379 dbus_bool_t high_bits;
2381 _dbus_assert (start <= _dbus_string_get_length (source));
2383 if (!_dbus_string_init (&result))
2389 p = (const unsigned char*) _dbus_string_get_const_data (source);
2390 end = p + _dbus_string_get_length (source);
2455 _dbus_verbose ("invalid character '%c' in hex encoded text\n",
2462 if (!_dbus_string_append_byte (&result,
2471 len = _dbus_string_get_length (&result);
2473 b = _dbus_string_get_byte (&result, len - 1);
2477 _dbus_string_set_byte (&result, len - 1, b);
2480 high_bits = !high_bits;
2485 if (!_dbus_string_move (&result, 0, dest, insert_at))
2491 _dbus_string_free (&result);
2496 * Checks that the given range of the string is valid ASCII with no
2497 * nul bytes. If the given range is not entirely contained in the
2498 * string, returns #FALSE.
2500 * @todo this is inconsistent with most of DBusString in that
2501 * it allows a start,len range that isn't in the string.
2503 * @param str the string
2504 * @param start first byte index to check
2505 * @param len number of bytes to check
2506 * @returns #TRUE if the byte range exists and is all valid ASCII
2509 _dbus_string_validate_ascii (const DBusString *str,
2513 const unsigned char *s;
2514 const unsigned char *end;
2515 DBUS_CONST_STRING_PREAMBLE (str);
2516 _dbus_assert (start >= 0);
2517 _dbus_assert (start <= real->len);
2518 _dbus_assert (len >= 0);
2520 if (len > real->len - start)
2523 s = real->str + start;
2528 ((*s & ~0x7f) != 0))
2538 * Checks that the given range of the string is valid UTF-8. If the
2539 * given range is not entirely contained in the string, returns
2540 * #FALSE. If the string contains any nul bytes in the given range,
2541 * returns #FALSE. If the start and start+len are not on character
2542 * boundaries, returns #FALSE.
2544 * @todo this is inconsistent with most of DBusString in that
2545 * it allows a start,len range that isn't in the string.
2547 * @param str the string
2548 * @param start first byte index to check
2549 * @param len number of bytes to check
2550 * @returns #TRUE if the byte range exists and is all valid UTF-8
2553 _dbus_string_validate_utf8 (const DBusString *str,
2557 const unsigned char *p;
2558 const unsigned char *end;
2559 DBUS_CONST_STRING_PREAMBLE (str);
2560 _dbus_assert (start >= 0);
2561 _dbus_assert (start <= real->len);
2562 _dbus_assert (len >= 0);
2564 if (len > real->len - start)
2567 p = real->str + start;
2572 int i, mask = 0, char_len;
2573 dbus_unichar_t result;
2574 unsigned char c = (unsigned char) *p;
2576 UTF8_COMPUTE (c, mask, char_len);
2581 /* check that the expected number of bytes exists in the remaining length */
2582 if ((end - p) < char_len)
2585 UTF8_GET (result, p, i, mask, char_len);
2587 if (UTF8_LENGTH (result) != char_len) /* Check for overlong UTF-8 */
2590 if (result == (dbus_unichar_t)-1)
2593 if (!UNICODE_VALID (result))
2599 /* See that we covered the entire length if a length was
2609 * Checks that the given range of the string is all nul bytes. If the
2610 * given range is not entirely contained in the string, returns
2613 * @todo this is inconsistent with most of DBusString in that
2614 * it allows a start,len range that isn't in the string.
2616 * @param str the string
2617 * @param start first byte index to check
2618 * @param len number of bytes to check
2619 * @returns #TRUE if the byte range exists and is all nul bytes
2622 _dbus_string_validate_nul (const DBusString *str,
2626 const unsigned char *s;
2627 const unsigned char *end;
2628 DBUS_CONST_STRING_PREAMBLE (str);
2629 _dbus_assert (start >= 0);
2630 _dbus_assert (len >= 0);
2631 _dbus_assert (start <= real->len);
2633 if (len > real->len - start)
2636 s = real->str + start;
2649 * Clears all allocated bytes in the string to zero.
2651 * @param str the string
2654 _dbus_string_zero (DBusString *str)
2656 DBUS_STRING_PREAMBLE (str);
2658 memset (real->str, '\0', real->allocated);
2662 #ifdef DBUS_BUILD_TESTS
2663 #include "dbus-test.h"
2667 test_max_len (DBusString *str,
2672 if (!_dbus_string_set_length (str, max_len - 1))
2673 _dbus_assert_not_reached ("setting len to one less than max should have worked");
2676 if (!_dbus_string_set_length (str, max_len))
2677 _dbus_assert_not_reached ("setting len to max len should have worked");
2679 if (_dbus_string_set_length (str, max_len + 1))
2680 _dbus_assert_not_reached ("setting len to one more than max len should not have worked");
2682 if (!_dbus_string_set_length (str, 0))
2683 _dbus_assert_not_reached ("setting len to zero should have worked");
2687 test_base64_roundtrip (const unsigned char *data,
2695 len = strlen (data);
2697 if (!_dbus_string_init (&orig))
2698 _dbus_assert_not_reached ("could not init string");
2700 if (!_dbus_string_init (&encoded))
2701 _dbus_assert_not_reached ("could not init string");
2703 if (!_dbus_string_init (&decoded))
2704 _dbus_assert_not_reached ("could not init string");
2706 if (!_dbus_string_append_len (&orig, data, len))
2707 _dbus_assert_not_reached ("couldn't append orig data");
2709 if (!_dbus_string_base64_encode (&orig, 0, &encoded, 0))
2710 _dbus_assert_not_reached ("could not encode");
2712 if (!_dbus_string_base64_decode (&encoded, 0, &decoded, 0))
2713 _dbus_assert_not_reached ("could not decode");
2715 if (!_dbus_string_equal (&orig, &decoded))
2719 printf ("Original string %d bytes encoded %d bytes decoded %d bytes\n",
2720 _dbus_string_get_length (&orig),
2721 _dbus_string_get_length (&encoded),
2722 _dbus_string_get_length (&decoded));
2723 printf ("Original: %s\n", data);
2724 s = _dbus_string_get_const_data (&decoded);
2725 printf ("Decoded: %s\n", s);
2726 _dbus_assert_not_reached ("original string not the same as string decoded from base64");
2729 _dbus_string_free (&orig);
2730 _dbus_string_free (&encoded);
2731 _dbus_string_free (&decoded);
2735 test_hex_roundtrip (const unsigned char *data,
2743 len = strlen (data);
2745 if (!_dbus_string_init (&orig))
2746 _dbus_assert_not_reached ("could not init string");
2748 if (!_dbus_string_init (&encoded))
2749 _dbus_assert_not_reached ("could not init string");
2751 if (!_dbus_string_init (&decoded))
2752 _dbus_assert_not_reached ("could not init string");
2754 if (!_dbus_string_append_len (&orig, data, len))
2755 _dbus_assert_not_reached ("couldn't append orig data");
2757 if (!_dbus_string_hex_encode (&orig, 0, &encoded, 0))
2758 _dbus_assert_not_reached ("could not encode");
2760 if (!_dbus_string_hex_decode (&encoded, 0, &decoded, 0))
2761 _dbus_assert_not_reached ("could not decode");
2763 if (!_dbus_string_equal (&orig, &decoded))
2767 printf ("Original string %d bytes encoded %d bytes decoded %d bytes\n",
2768 _dbus_string_get_length (&orig),
2769 _dbus_string_get_length (&encoded),
2770 _dbus_string_get_length (&decoded));
2771 printf ("Original: %s\n", data);
2772 s = _dbus_string_get_const_data (&decoded);
2773 printf ("Decoded: %s\n", s);
2774 _dbus_assert_not_reached ("original string not the same as string decoded from base64");
2777 _dbus_string_free (&orig);
2778 _dbus_string_free (&encoded);
2779 _dbus_string_free (&decoded);
2782 typedef void (* TestRoundtripFunc) (const unsigned char *data,
2785 test_roundtrips (TestRoundtripFunc func)
2787 (* func) ("Hello this is a string\n", -1);
2788 (* func) ("Hello this is a string\n1", -1);
2789 (* func) ("Hello this is a string\n12", -1);
2790 (* func) ("Hello this is a string\n123", -1);
2791 (* func) ("Hello this is a string\n1234", -1);
2792 (* func) ("Hello this is a string\n12345", -1);
2796 (* func) ("123", 3);
2797 (* func) ("1234", 4);
2798 (* func) ("12345", 5);
2802 (* func) ("123", 4);
2803 (* func) ("1234", 5);
2804 (* func) ("12345", 6);
2806 unsigned char buf[512];
2810 while (i < _DBUS_N_ELEMENTS (buf))
2816 while (i < _DBUS_N_ELEMENTS (buf))
2826 * @ingroup DBusStringInternals
2827 * Unit test for DBusString.
2829 * @todo Need to write tests for _dbus_string_copy() and
2830 * _dbus_string_move() moving to/from each of start/middle/end of a
2831 * string. Also need tests for _dbus_string_move_len ()
2833 * @returns #TRUE on success.
2836 _dbus_string_test (void)
2843 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 };
2848 while (i < _DBUS_N_ELEMENTS (lens))
2850 if (!_dbus_string_init (&str))
2851 _dbus_assert_not_reached ("failed to init string");
2853 set_max_length (&str, lens[i]);
2855 test_max_len (&str, lens[i]);
2856 _dbus_string_free (&str);
2861 /* Test shortening and setting length */
2863 while (i < _DBUS_N_ELEMENTS (lens))
2867 if (!_dbus_string_init (&str))
2868 _dbus_assert_not_reached ("failed to init string");
2870 set_max_length (&str, lens[i]);
2872 if (!_dbus_string_set_length (&str, lens[i]))
2873 _dbus_assert_not_reached ("failed to set string length");
2878 _dbus_assert (_dbus_string_get_length (&str) == j);
2881 _dbus_string_shorten (&str, 1);
2882 _dbus_assert (_dbus_string_get_length (&str) == (j - 1));
2887 _dbus_string_free (&str);
2892 /* Test appending data */
2893 if (!_dbus_string_init (&str))
2894 _dbus_assert_not_reached ("failed to init string");
2899 if (!_dbus_string_append (&str, "a"))
2900 _dbus_assert_not_reached ("failed to append string to string\n");
2902 _dbus_assert (_dbus_string_get_length (&str) == i * 2 + 1);
2904 if (!_dbus_string_append_byte (&str, 'b'))
2905 _dbus_assert_not_reached ("failed to append byte to string\n");
2907 _dbus_assert (_dbus_string_get_length (&str) == i * 2 + 2);
2912 _dbus_string_free (&str);
2914 /* Check steal_data */
2916 if (!_dbus_string_init (&str))
2917 _dbus_assert_not_reached ("failed to init string");
2919 if (!_dbus_string_append (&str, "Hello World"))
2920 _dbus_assert_not_reached ("could not append to string");
2922 i = _dbus_string_get_length (&str);
2924 if (!_dbus_string_steal_data (&str, &s))
2925 _dbus_assert_not_reached ("failed to steal data");
2927 _dbus_assert (_dbus_string_get_length (&str) == 0);
2928 _dbus_assert (((int)strlen (s)) == i);
2934 if (!_dbus_string_append (&str, "Hello World"))
2935 _dbus_assert_not_reached ("could not append to string");
2937 i = _dbus_string_get_length (&str);
2939 if (!_dbus_string_init (&other))
2940 _dbus_assert_not_reached ("could not init string");
2942 if (!_dbus_string_move (&str, 0, &other, 0))
2943 _dbus_assert_not_reached ("could not move");
2945 _dbus_assert (_dbus_string_get_length (&str) == 0);
2946 _dbus_assert (_dbus_string_get_length (&other) == i);
2948 if (!_dbus_string_append (&str, "Hello World"))
2949 _dbus_assert_not_reached ("could not append to string");
2951 if (!_dbus_string_move (&str, 0, &other, _dbus_string_get_length (&other)))
2952 _dbus_assert_not_reached ("could not move");
2954 _dbus_assert (_dbus_string_get_length (&str) == 0);
2955 _dbus_assert (_dbus_string_get_length (&other) == i * 2);
2957 if (!_dbus_string_append (&str, "Hello World"))
2958 _dbus_assert_not_reached ("could not append to string");
2960 if (!_dbus_string_move (&str, 0, &other, _dbus_string_get_length (&other) / 2))
2961 _dbus_assert_not_reached ("could not move");
2963 _dbus_assert (_dbus_string_get_length (&str) == 0);
2964 _dbus_assert (_dbus_string_get_length (&other) == i * 3);
2966 _dbus_string_free (&other);
2970 if (!_dbus_string_append (&str, "Hello World"))
2971 _dbus_assert_not_reached ("could not append to string");
2973 i = _dbus_string_get_length (&str);
2975 if (!_dbus_string_init (&other))
2976 _dbus_assert_not_reached ("could not init string");
2978 if (!_dbus_string_copy (&str, 0, &other, 0))
2979 _dbus_assert_not_reached ("could not copy");
2981 _dbus_assert (_dbus_string_get_length (&str) == i);
2982 _dbus_assert (_dbus_string_get_length (&other) == i);
2984 if (!_dbus_string_copy (&str, 0, &other, _dbus_string_get_length (&other)))
2985 _dbus_assert_not_reached ("could not copy");
2987 _dbus_assert (_dbus_string_get_length (&str) == i);
2988 _dbus_assert (_dbus_string_get_length (&other) == i * 2);
2989 _dbus_assert (_dbus_string_equal_c_str (&other,
2990 "Hello WorldHello World"));
2992 if (!_dbus_string_copy (&str, 0, &other, _dbus_string_get_length (&other) / 2))
2993 _dbus_assert_not_reached ("could not copy");
2995 _dbus_assert (_dbus_string_get_length (&str) == i);
2996 _dbus_assert (_dbus_string_get_length (&other) == i * 3);
2997 _dbus_assert (_dbus_string_equal_c_str (&other,
2998 "Hello WorldHello WorldHello World"));
3000 _dbus_string_free (&str);
3001 _dbus_string_free (&other);
3005 if (!_dbus_string_init (&str))
3006 _dbus_assert_not_reached ("failed to init string");
3008 if (!_dbus_string_append (&str, "Hello World"))
3009 _dbus_assert_not_reached ("could not append to string");
3011 i = _dbus_string_get_length (&str);
3013 if (!_dbus_string_init (&other))
3014 _dbus_assert_not_reached ("could not init string");
3016 if (!_dbus_string_replace_len (&str, 0, _dbus_string_get_length (&str),
3017 &other, 0, _dbus_string_get_length (&other)))
3018 _dbus_assert_not_reached ("could not replace");
3020 _dbus_assert (_dbus_string_get_length (&str) == i);
3021 _dbus_assert (_dbus_string_get_length (&other) == i);
3022 _dbus_assert (_dbus_string_equal_c_str (&other, "Hello World"));
3024 if (!_dbus_string_replace_len (&str, 0, _dbus_string_get_length (&str),
3026 _dbus_assert_not_reached ("could not replace center space");
3028 _dbus_assert (_dbus_string_get_length (&str) == i);
3029 _dbus_assert (_dbus_string_get_length (&other) == i * 2 - 1);
3030 _dbus_assert (_dbus_string_equal_c_str (&other,
3031 "HelloHello WorldWorld"));
3034 if (!_dbus_string_replace_len (&str, 1, 1,
3036 _dbus_string_get_length (&other) - 1,
3038 _dbus_assert_not_reached ("could not replace end character");
3040 _dbus_assert (_dbus_string_get_length (&str) == i);
3041 _dbus_assert (_dbus_string_get_length (&other) == i * 2 - 1);
3042 _dbus_assert (_dbus_string_equal_c_str (&other,
3043 "HelloHello WorldWorle"));
3045 _dbus_string_free (&str);
3046 _dbus_string_free (&other);
3048 /* Check append/get unichar */
3050 if (!_dbus_string_init (&str))
3051 _dbus_assert_not_reached ("failed to init string");
3054 if (!_dbus_string_append_unichar (&str, 0xfffc))
3055 _dbus_assert_not_reached ("failed to append unichar");
3057 _dbus_string_get_unichar (&str, 0, &ch, &i);
3059 _dbus_assert (ch == 0xfffc);
3060 _dbus_assert (i == _dbus_string_get_length (&str));
3062 _dbus_string_free (&str);
3064 /* Check insert/set/get byte */
3066 if (!_dbus_string_init (&str))
3067 _dbus_assert_not_reached ("failed to init string");
3069 if (!_dbus_string_append (&str, "Hello"))
3070 _dbus_assert_not_reached ("failed to append Hello");
3072 _dbus_assert (_dbus_string_get_byte (&str, 0) == 'H');
3073 _dbus_assert (_dbus_string_get_byte (&str, 1) == 'e');
3074 _dbus_assert (_dbus_string_get_byte (&str, 2) == 'l');
3075 _dbus_assert (_dbus_string_get_byte (&str, 3) == 'l');
3076 _dbus_assert (_dbus_string_get_byte (&str, 4) == 'o');
3078 _dbus_string_set_byte (&str, 1, 'q');
3079 _dbus_assert (_dbus_string_get_byte (&str, 1) == 'q');
3081 if (!_dbus_string_insert_byte (&str, 0, 255))
3082 _dbus_assert_not_reached ("can't insert byte");
3084 if (!_dbus_string_insert_byte (&str, 2, 'Z'))
3085 _dbus_assert_not_reached ("can't insert byte");
3087 if (!_dbus_string_insert_byte (&str, _dbus_string_get_length (&str), 'W'))
3088 _dbus_assert_not_reached ("can't insert byte");
3090 _dbus_assert (_dbus_string_get_byte (&str, 0) == 255);
3091 _dbus_assert (_dbus_string_get_byte (&str, 1) == 'H');
3092 _dbus_assert (_dbus_string_get_byte (&str, 2) == 'Z');
3093 _dbus_assert (_dbus_string_get_byte (&str, 3) == 'q');
3094 _dbus_assert (_dbus_string_get_byte (&str, 4) == 'l');
3095 _dbus_assert (_dbus_string_get_byte (&str, 5) == 'l');
3096 _dbus_assert (_dbus_string_get_byte (&str, 6) == 'o');
3097 _dbus_assert (_dbus_string_get_byte (&str, 7) == 'W');
3099 _dbus_string_free (&str);
3101 /* Check append/parse int/double */
3103 if (!_dbus_string_init (&str))
3104 _dbus_assert_not_reached ("failed to init string");
3106 if (!_dbus_string_append_int (&str, 27))
3107 _dbus_assert_not_reached ("failed to append int");
3109 i = _dbus_string_get_length (&str);
3111 if (!_dbus_string_parse_int (&str, 0, &v, &end))
3112 _dbus_assert_not_reached ("failed to parse int");
3114 _dbus_assert (v == 27);
3115 _dbus_assert (end == i);
3117 _dbus_string_free (&str);
3119 if (!_dbus_string_init (&str))
3120 _dbus_assert_not_reached ("failed to init string");
3122 if (!_dbus_string_append_double (&str, 50.3))
3123 _dbus_assert_not_reached ("failed to append float");
3125 i = _dbus_string_get_length (&str);
3127 if (!_dbus_string_parse_double (&str, 0, &d, &end))
3128 _dbus_assert_not_reached ("failed to parse float");
3130 _dbus_assert (d > (50.3 - 1e-6) && d < (50.3 + 1e-6));
3131 _dbus_assert (end == i);
3133 _dbus_string_free (&str);
3136 if (!_dbus_string_init (&str))
3137 _dbus_assert_not_reached ("failed to init string");
3139 if (!_dbus_string_append (&str, "Hello"))
3140 _dbus_assert_not_reached ("couldn't append to string");
3142 if (!_dbus_string_find (&str, 0, "He", &i))
3143 _dbus_assert_not_reached ("didn't find 'He'");
3144 _dbus_assert (i == 0);
3146 if (!_dbus_string_find (&str, 0, "Hello", &i))
3147 _dbus_assert_not_reached ("didn't find 'Hello'");
3148 _dbus_assert (i == 0);
3150 if (!_dbus_string_find (&str, 0, "ello", &i))
3151 _dbus_assert_not_reached ("didn't find 'ello'");
3152 _dbus_assert (i == 1);
3154 if (!_dbus_string_find (&str, 0, "lo", &i))
3155 _dbus_assert_not_reached ("didn't find 'lo'");
3156 _dbus_assert (i == 3);
3158 if (!_dbus_string_find (&str, 2, "lo", &i))
3159 _dbus_assert_not_reached ("didn't find 'lo'");
3160 _dbus_assert (i == 3);
3162 if (_dbus_string_find (&str, 4, "lo", &i))
3163 _dbus_assert_not_reached ("did find 'lo'");
3165 if (!_dbus_string_find (&str, 0, "l", &i))
3166 _dbus_assert_not_reached ("didn't find 'l'");
3167 _dbus_assert (i == 2);
3169 if (!_dbus_string_find (&str, 0, "H", &i))
3170 _dbus_assert_not_reached ("didn't find 'H'");
3171 _dbus_assert (i == 0);
3173 if (!_dbus_string_find (&str, 0, "", &i))
3174 _dbus_assert_not_reached ("didn't find ''");
3175 _dbus_assert (i == 0);
3177 if (_dbus_string_find (&str, 0, "Hello!", NULL))
3178 _dbus_assert_not_reached ("Did find 'Hello!'");
3180 if (_dbus_string_find (&str, 0, "Oh, Hello", NULL))
3181 _dbus_assert_not_reached ("Did find 'Oh, Hello'");
3183 if (_dbus_string_find (&str, 0, "ill", NULL))
3184 _dbus_assert_not_reached ("Did find 'ill'");
3186 if (_dbus_string_find (&str, 0, "q", NULL))
3187 _dbus_assert_not_reached ("Did find 'q'");
3189 if (!_dbus_string_find_to (&str, 0, 2, "He", NULL))
3190 _dbus_assert_not_reached ("Didn't find 'He'");
3192 if (_dbus_string_find_to (&str, 0, 2, "Hello", NULL))
3193 _dbus_assert_not_reached ("Did find 'Hello'");
3195 if (!_dbus_string_find_byte_backward (&str, _dbus_string_get_length (&str), 'H', &i))
3196 _dbus_assert_not_reached ("Did not find 'H'");
3197 _dbus_assert (i == 0);
3199 if (!_dbus_string_find_byte_backward (&str, _dbus_string_get_length (&str), 'o', &i))
3200 _dbus_assert_not_reached ("Did not find 'o'");
3201 _dbus_assert (i == _dbus_string_get_length (&str) - 1);
3203 if (_dbus_string_find_byte_backward (&str, _dbus_string_get_length (&str) - 1, 'o', &i))
3204 _dbus_assert_not_reached ("Did find 'o'");
3205 _dbus_assert (i == -1);
3207 if (_dbus_string_find_byte_backward (&str, 1, 'e', &i))
3208 _dbus_assert_not_reached ("Did find 'e'");
3209 _dbus_assert (i == -1);
3211 if (!_dbus_string_find_byte_backward (&str, 2, 'e', &i))
3212 _dbus_assert_not_reached ("Didn't find 'e'");
3213 _dbus_assert (i == 1);
3215 _dbus_string_free (&str);
3217 /* Base 64 and Hex encoding */
3218 test_roundtrips (test_base64_roundtrip);
3219 test_roundtrips (test_hex_roundtrip);
3224 #endif /* DBUS_BUILD_TESTS */