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"
31 #include "dbus-protocol.h"
34 * @defgroup DBusString string class
35 * @ingroup DBusInternals
36 * @brief DBusString data structure
38 * Types and functions related to DBusString. DBusString is intended
39 * to be a string class that makes it hard to mess up security issues
40 * (and just in general harder to write buggy code). It should be
41 * used (or extended and then used) rather than the libc stuff in
42 * string.h. The string class is a bit inconvenient at spots because
43 * it handles out-of-memory failures and tries to be extra-robust.
45 * A DBusString has a maximum length set at initialization time; this
46 * can be used to ensure that a buffer doesn't get too big. The
47 * _dbus_string_lengthen() method checks for overflow, and for max
48 * length being exceeded.
50 * Try to avoid conversion to a plain C string, i.e. add methods on
51 * the string object instead, only convert to C string when passing
52 * things out to the public API. In particular, no sprintf, strcpy,
53 * strcat, any of that should be used. The GString feature of
54 * accepting negative numbers for "length of string" is also absent,
55 * because it could keep us from detecting bogus huge lengths. i.e. if
56 * we passed in some bogus huge length it would be taken to mean
57 * "current length of string" instead of "broken crack"
61 * @defgroup DBusStringInternals DBusString implementation details
62 * @ingroup DBusInternals
63 * @brief DBusString implementation details
65 * The guts of DBusString.
71 * We allocate 1 byte for nul termination, plus 7 bytes for possible
72 * align_offset, so we always need 8 bytes on top of the string's
73 * length to be in the allocated block.
75 #define ALLOCATION_PADDING 8
78 * This is the maximum max length (and thus also the maximum length)
81 #define MAX_MAX_LENGTH (_DBUS_INT_MAX - ALLOCATION_PADDING)
84 * Checks a bunch of assertions about a string object
86 * @param real the DBusRealString
88 #define DBUS_GENERIC_STRING_PREAMBLE(real) _dbus_assert ((real) != NULL); _dbus_assert (!(real)->invalid); _dbus_assert ((real)->len >= 0); _dbus_assert ((real)->allocated >= 0); _dbus_assert ((real)->max_length >= 0); _dbus_assert ((real)->len <= ((real)->allocated - ALLOCATION_PADDING)); _dbus_assert ((real)->len <= (real)->max_length)
91 * Checks assertions about a string object that needs to be
92 * modifiable - may not be locked or const. Also declares
93 * the "real" variable pointing to DBusRealString.
94 * @param str the string
96 #define DBUS_STRING_PREAMBLE(str) DBusRealString *real = (DBusRealString*) str; \
97 DBUS_GENERIC_STRING_PREAMBLE (real); \
98 _dbus_assert (!(real)->constant); \
99 _dbus_assert (!(real)->locked)
102 * Checks assertions about a string object that may be locked but
103 * can't be const. i.e. a string object that we can free. Also
104 * declares the "real" variable pointing to DBusRealString.
106 * @param str the string
108 #define DBUS_LOCKED_STRING_PREAMBLE(str) DBusRealString *real = (DBusRealString*) str; \
109 DBUS_GENERIC_STRING_PREAMBLE (real); \
110 _dbus_assert (!(real)->constant)
113 * Checks assertions about a string that may be const or locked. Also
114 * declares the "real" variable pointing to DBusRealString.
115 * @param str the string.
117 #define DBUS_CONST_STRING_PREAMBLE(str) const DBusRealString *real = (DBusRealString*) str; \
118 DBUS_GENERIC_STRING_PREAMBLE (real)
123 * @addtogroup DBusString
128 fixup_alignment (DBusRealString *real)
132 unsigned int old_align_offset;
134 /* we have to have extra space in real->allocated for the align offset and nul byte */
135 _dbus_assert (real->len <= real->allocated - ALLOCATION_PADDING);
137 old_align_offset = real->align_offset;
138 real_block = real->str - old_align_offset;
140 aligned = _DBUS_ALIGN_ADDRESS (real_block, 8);
142 real->align_offset = aligned - real_block;
145 if (old_align_offset != real->align_offset)
147 /* Here comes the suck */
148 memmove (real_block + real->align_offset,
149 real_block + old_align_offset,
153 _dbus_assert (real->align_offset < 8);
154 _dbus_assert (_DBUS_ALIGN_ADDRESS (real->str, 8) == real->str);
158 undo_alignment (DBusRealString *real)
160 if (real->align_offset != 0)
162 memmove (real->str - real->align_offset,
166 real->str = real->str - real->align_offset;
167 real->align_offset = 0;
172 * Initializes a string. The string starts life with zero length. The
173 * string must eventually be freed with _dbus_string_free().
175 * @param str memory to hold the string
176 * @returns #TRUE on success, #FALSE if no memory
179 _dbus_string_init (DBusString *str)
181 DBusRealString *real;
183 _dbus_assert (str != NULL);
185 _dbus_assert (sizeof (DBusString) == sizeof (DBusRealString));
187 real = (DBusRealString*) str;
189 /* It's very important not to touch anything
190 * other than real->str if we're going to fail,
191 * since we also use this function to reset
192 * an existing string, e.g. in _dbus_string_steal_data()
195 real->str = dbus_malloc (ALLOCATION_PADDING);
196 if (real->str == NULL)
199 real->allocated = ALLOCATION_PADDING;
201 real->str[real->len] = '\0';
203 real->max_length = MAX_MAX_LENGTH;
204 real->constant = FALSE;
205 real->locked = FALSE;
206 real->invalid = FALSE;
207 real->align_offset = 0;
209 fixup_alignment (real);
214 /* The max length thing is sort of a historical artifact
215 * from a feature that turned out to be dumb; perhaps
216 * we should purge it entirely. The problem with
217 * the feature is that it looks like memory allocation
218 * failure, but is not a transient or resolvable failure.
221 set_max_length (DBusString *str,
224 DBusRealString *real;
226 real = (DBusRealString*) str;
228 real->max_length = max_length;
232 * Initializes a constant string. The value parameter is not copied
233 * (should be static), and the string may never be modified.
234 * It is safe but not necessary to call _dbus_string_free()
235 * on a const string. The string has a length limit of MAXINT - 8.
237 * @param str memory to use for the string
238 * @param value a string to be stored in str (not copied!!!)
241 _dbus_string_init_const (DBusString *str,
244 _dbus_assert (value != NULL);
246 _dbus_string_init_const_len (str, value,
251 * Initializes a constant string with a length. The value parameter is
252 * not copied (should be static), and the string may never be
253 * modified. It is safe but not necessary to call _dbus_string_free()
256 * @param str memory to use for the string
257 * @param value a string to be stored in str (not copied!!!)
258 * @param len the length to use
261 _dbus_string_init_const_len (DBusString *str,
265 DBusRealString *real;
267 _dbus_assert (str != NULL);
268 _dbus_assert (value != NULL);
269 _dbus_assert (len <= MAX_MAX_LENGTH);
270 _dbus_assert (len >= 0);
272 real = (DBusRealString*) str;
274 real->str = (char*) value;
276 real->allocated = real->len + ALLOCATION_PADDING; /* a lie, just to avoid special-case assertions... */
277 real->max_length = real->len + 1;
278 real->constant = TRUE;
279 real->invalid = FALSE;
281 /* We don't require const strings to be 8-byte aligned as the
282 * memory is coming from elsewhere.
287 * Frees a string created by _dbus_string_init().
289 * @param str memory where the string is stored.
292 _dbus_string_free (DBusString *str)
294 DBusRealString *real = (DBusRealString*) str;
295 DBUS_GENERIC_STRING_PREAMBLE (real);
299 dbus_free (real->str - real->align_offset);
301 real->invalid = TRUE;
305 * Locks a string such that any attempts to change the string will
306 * result in aborting the program. Also, if the string is wasting a
307 * lot of memory (allocation is sufficiently larger than what the
308 * string is really using), _dbus_string_lock() will realloc the
309 * string's data to "compact" it.
311 * @param str the string to lock.
314 _dbus_string_lock (DBusString *str)
316 DBUS_LOCKED_STRING_PREAMBLE (str); /* can lock multiple times */
320 /* Try to realloc to avoid excess memory usage, since
321 * we know we won't change the string further
324 if (real->allocated - MAX_WASTE > real->len)
329 new_allocated = real->len + ALLOCATION_PADDING;
331 new_str = dbus_realloc (real->str - real->align_offset,
335 real->str = new_str + real->align_offset;
336 real->allocated = new_allocated;
337 fixup_alignment (real);
343 set_length (DBusRealString *real,
346 /* Note, we are setting the length without nul termination */
348 /* exceeding max length is the same as failure to allocate memory */
349 if (new_length > real->max_length)
352 if (new_length > (real->allocated - ALLOCATION_PADDING))
357 /* at least double our old allocation to avoid O(n), avoiding
360 if (real->allocated > (MAX_MAX_LENGTH + ALLOCATION_PADDING) / 2)
361 new_allocated = MAX_MAX_LENGTH + ALLOCATION_PADDING;
363 new_allocated = real->allocated * 2;
365 /* if you change the code just above here, run the tests without
366 * the following before you commit
368 #ifdef DBUS_BUILD_TESTS
369 new_allocated = 0; /* ensure a realloc every time so that we go
370 * through all malloc failure codepaths
374 /* But be sure we always alloc at least space for the new length */
375 new_allocated = MAX (new_allocated, new_length + ALLOCATION_PADDING);
377 new_str = dbus_realloc (real->str - real->align_offset, new_allocated);
381 real->str = new_str + real->align_offset;
382 real->allocated = new_allocated;
383 fixup_alignment (real);
386 real->len = new_length;
387 real->str[real->len] = '\0';
394 DBusRealString *dest,
400 if (len > dest->max_length - dest->len)
401 return FALSE; /* detected overflow of dest->len + len below */
403 if (!set_length (dest, dest->len + len))
406 memmove (dest->str + insert_at + len,
407 dest->str + insert_at,
408 dest->len - len - insert_at);
414 * Gets the raw character buffer from the string. The returned buffer
415 * will be nul-terminated, but note that strings may contain binary
416 * data so there may be extra nul characters prior to the termination.
417 * This function should be little-used, extend DBusString or add
418 * stuff to dbus-sysdeps.c instead. It's an error to use this
419 * function on a const string.
421 * @param str the string
425 _dbus_string_get_data (DBusString *str)
427 DBUS_STRING_PREAMBLE (str);
433 * Gets the raw character buffer from a const string.
435 * @param str the string
436 * @returns the string data
439 _dbus_string_get_const_data (const DBusString *str)
441 DBUS_CONST_STRING_PREAMBLE (str);
447 * Gets a sub-portion of the raw character buffer from the
448 * string. The "len" field is required simply for error
449 * checking, to be sure you don't try to use more
450 * string than exists. The nul termination of the
451 * returned buffer remains at the end of the entire
452 * string, not at start + len.
454 * @param str the string
455 * @param start byte offset to return
456 * @param len length of segment to return
457 * @returns the string data
460 _dbus_string_get_data_len (DBusString *str,
464 DBUS_STRING_PREAMBLE (str);
465 _dbus_assert (start >= 0);
466 _dbus_assert (len >= 0);
467 _dbus_assert (start <= real->len);
468 _dbus_assert (len <= real->len - start);
470 return real->str + start;
474 * const version of _dbus_string_get_data_len().
476 * @param str the string
477 * @param start byte offset to return
478 * @param len length of segment to return
479 * @returns the string data
482 _dbus_string_get_const_data_len (const DBusString *str,
486 DBUS_CONST_STRING_PREAMBLE (str);
487 _dbus_assert (start >= 0);
488 _dbus_assert (len >= 0);
489 _dbus_assert (start <= real->len);
490 _dbus_assert (len <= real->len - start);
492 return real->str + start;
496 * Sets the value of the byte at the given position.
498 * @param str the string
499 * @param i the position
500 * @param byte the new value
503 _dbus_string_set_byte (DBusString *str,
507 DBUS_STRING_PREAMBLE (str);
508 _dbus_assert (i < real->len);
509 _dbus_assert (i >= 0);
515 * Gets the byte at the given position.
517 * @param str the string
518 * @param start the position
519 * @returns the byte at that position
522 _dbus_string_get_byte (const DBusString *str,
525 DBUS_CONST_STRING_PREAMBLE (str);
526 _dbus_assert (start < real->len);
527 _dbus_assert (start >= 0);
529 return real->str[start];
533 * Inserts the given byte at the given position.
535 * @param str the string
536 * @param i the position
537 * @param byte the value to insert
538 * @returns #TRUE on success
541 _dbus_string_insert_byte (DBusString *str,
545 DBUS_STRING_PREAMBLE (str);
546 _dbus_assert (i <= real->len);
547 _dbus_assert (i >= 0);
549 if (!open_gap (1, real, i))
558 * Like _dbus_string_get_data(), but removes the
559 * gotten data from the original string. The caller
560 * must free the data returned. This function may
561 * fail due to lack of memory, and return #FALSE.
563 * @param str the string
564 * @param data_return location to return the buffer
565 * @returns #TRUE on success
568 _dbus_string_steal_data (DBusString *str,
572 DBUS_STRING_PREAMBLE (str);
573 _dbus_assert (data_return != NULL);
575 undo_alignment (real);
577 *data_return = real->str;
579 old_max_length = real->max_length;
581 /* reset the string */
582 if (!_dbus_string_init (str))
584 /* hrm, put it back then */
585 real->str = *data_return;
587 fixup_alignment (real);
591 real->max_length = old_max_length;
597 * Like _dbus_string_get_data_len(), but removes the gotten data from
598 * the original string. The caller must free the data returned. This
599 * function may fail due to lack of memory, and return #FALSE.
600 * The returned string is nul-terminated and has length len.
602 * @todo this function is broken because on failure it
603 * may corrupt the source string.
605 * @param str the string
606 * @param data_return location to return the buffer
607 * @param start the start of segment to steal
608 * @param len the length of segment to steal
609 * @returns #TRUE on success
612 _dbus_string_steal_data_len (DBusString *str,
618 DBUS_STRING_PREAMBLE (str);
619 _dbus_assert (data_return != NULL);
620 _dbus_assert (start >= 0);
621 _dbus_assert (len >= 0);
622 _dbus_assert (start <= real->len);
623 _dbus_assert (len <= real->len - start);
625 if (!_dbus_string_init (&dest))
628 set_max_length (&dest, real->max_length);
630 if (!_dbus_string_move_len (str, start, len, &dest, 0))
632 _dbus_string_free (&dest);
636 _dbus_warn ("Broken code in _dbus_string_steal_data_len(), see @todo, FIXME\n");
637 if (!_dbus_string_steal_data (&dest, data_return))
639 _dbus_string_free (&dest);
643 _dbus_string_free (&dest);
649 * Copies the data from the string into a char*
651 * @param str the string
652 * @param data_return place to return the data
653 * @returns #TRUE on success, #FALSE on no memory
656 _dbus_string_copy_data (const DBusString *str,
659 DBUS_CONST_STRING_PREAMBLE (str);
660 _dbus_assert (data_return != NULL);
662 *data_return = dbus_malloc (real->len + 1);
663 if (*data_return == NULL)
666 memcpy (*data_return, real->str, real->len + 1);
672 * Copies a segment of the string into a char*
674 * @param str the string
675 * @param data_return place to return the data
676 * @param start start index
677 * @param len length to copy
678 * @returns #FALSE if no memory
681 _dbus_string_copy_data_len (const DBusString *str,
688 DBUS_CONST_STRING_PREAMBLE (str);
689 _dbus_assert (data_return != NULL);
690 _dbus_assert (start >= 0);
691 _dbus_assert (len >= 0);
692 _dbus_assert (start <= real->len);
693 _dbus_assert (len <= real->len - start);
695 if (!_dbus_string_init (&dest))
698 set_max_length (&dest, real->max_length);
700 if (!_dbus_string_copy_len (str, start, len, &dest, 0))
702 _dbus_string_free (&dest);
706 if (!_dbus_string_steal_data (&dest, data_return))
708 _dbus_string_free (&dest);
712 _dbus_string_free (&dest);
717 * Gets the length of a string (not including nul termination).
719 * @returns the length.
722 _dbus_string_get_length (const DBusString *str)
724 DBUS_CONST_STRING_PREAMBLE (str);
730 * Makes a string longer by the given number of bytes. Checks whether
731 * adding additional_length to the current length would overflow an
732 * integer, and checks for exceeding a string's max length.
733 * The new bytes are not initialized, other than nul-terminating
734 * the end of the string. The uninitialized bytes may contain
735 * nul bytes or other junk.
737 * @param str a string
738 * @param additional_length length to add to the string.
739 * @returns #TRUE on success.
742 _dbus_string_lengthen (DBusString *str,
743 int additional_length)
745 DBUS_STRING_PREAMBLE (str);
746 _dbus_assert (additional_length >= 0);
748 if (additional_length > real->max_length - real->len)
749 return FALSE; /* would overflow */
751 return set_length (real,
752 real->len + additional_length);
756 * Makes a string shorter by the given number of bytes.
758 * @param str a string
759 * @param length_to_remove length to remove from the string.
762 _dbus_string_shorten (DBusString *str,
763 int length_to_remove)
765 DBUS_STRING_PREAMBLE (str);
766 _dbus_assert (length_to_remove >= 0);
767 _dbus_assert (length_to_remove <= real->len);
770 real->len - length_to_remove);
774 * Sets the length of a string. Can be used to truncate or lengthen
775 * the string. If the string is lengthened, the function may fail and
776 * return #FALSE. Newly-added bytes are not initialized, as with
777 * _dbus_string_lengthen().
779 * @param str a string
780 * @param length new length of the string.
781 * @returns #FALSE on failure.
784 _dbus_string_set_length (DBusString *str,
787 DBUS_STRING_PREAMBLE (str);
788 _dbus_assert (length >= 0);
790 return set_length (real, length);
794 * Align the length of a string to a specific alignment (typically 4 or 8)
795 * by appending nul bytes to the string.
797 * @param str a string
798 * @param alignment the alignment
799 * @returns #FALSE if no memory
802 _dbus_string_align_length (DBusString *str,
805 unsigned long new_len; /* ulong to avoid _DBUS_ALIGN_VALUE overflow */
807 DBUS_STRING_PREAMBLE (str);
808 _dbus_assert (alignment >= 1);
809 _dbus_assert (alignment <= 8); /* it has to be a bug if > 8 */
811 new_len = _DBUS_ALIGN_VALUE (real->len, alignment);
812 if (new_len > (unsigned long) real->max_length)
815 delta = new_len - real->len;
816 _dbus_assert (delta >= 0);
821 if (!set_length (real, new_len))
824 memset (real->str + (new_len - delta),
831 append (DBusRealString *real,
838 if (!_dbus_string_lengthen ((DBusString*)real, buffer_len))
841 memcpy (real->str + (real->len - buffer_len),
849 * Appends a nul-terminated C-style string to a DBusString.
851 * @param str the DBusString
852 * @param buffer the nul-terminated characters to append
853 * @returns #FALSE if not enough memory.
856 _dbus_string_append (DBusString *str,
859 unsigned long buffer_len;
861 DBUS_STRING_PREAMBLE (str);
862 _dbus_assert (buffer != NULL);
864 buffer_len = strlen (buffer);
865 if (buffer_len > (unsigned long) real->max_length)
868 return append (real, buffer, buffer_len);
872 * Appends block of bytes with the given length to a DBusString.
874 * @param str the DBusString
875 * @param buffer the bytes to append
876 * @param len the number of bytes to append
877 * @returns #FALSE if not enough memory.
880 _dbus_string_append_len (DBusString *str,
884 DBUS_STRING_PREAMBLE (str);
885 _dbus_assert (buffer != NULL);
886 _dbus_assert (len >= 0);
888 return append (real, buffer, len);
892 * Appends a single byte to the string, returning #FALSE
893 * if not enough memory.
895 * @param str the string
896 * @param byte the byte to append
897 * @returns #TRUE on success
900 _dbus_string_append_byte (DBusString *str,
903 DBUS_STRING_PREAMBLE (str);
905 if (!set_length (real, real->len + 1))
908 real->str[real->len-1] = byte;
914 * Appends a single Unicode character, encoding the character
917 * @param str the string
918 * @param ch the Unicode character
921 _dbus_string_append_unichar (DBusString *str,
929 DBUS_STRING_PREAMBLE (str);
931 /* this code is from GLib but is pretty standard I think */
945 else if (ch < 0x10000)
950 else if (ch < 0x200000)
955 else if (ch < 0x4000000)
966 if (len > (real->max_length - real->len))
967 return FALSE; /* real->len + len would overflow */
969 if (!set_length (real, real->len + len))
972 out = real->str + (real->len - len);
974 for (i = len - 1; i > 0; --i)
976 out[i] = (ch & 0x3f) | 0x80;
985 delete (DBusRealString *real,
992 memmove (real->str + start, real->str + start + len, real->len - (start + len));
994 real->str[real->len] = '\0';
998 * Deletes a segment of a DBusString with length len starting at
999 * start. (Hint: to clear an entire string, setting length to 0
1000 * with _dbus_string_set_length() is easier.)
1002 * @param str the DBusString
1003 * @param start where to start deleting
1004 * @param len the number of bytes to delete
1007 _dbus_string_delete (DBusString *str,
1011 DBUS_STRING_PREAMBLE (str);
1012 _dbus_assert (start >= 0);
1013 _dbus_assert (len >= 0);
1014 _dbus_assert (start <= real->len);
1015 _dbus_assert (len <= real->len - start);
1017 delete (real, start, len);
1021 copy (DBusRealString *source,
1024 DBusRealString *dest,
1030 if (!open_gap (len, dest, insert_at))
1033 memcpy (dest->str + insert_at,
1034 source->str + start,
1041 * Checks assertions for two strings we're copying a segment between,
1042 * and declares real_source/real_dest variables.
1044 * @param source the source string
1045 * @param start the starting offset
1046 * @param dest the dest string
1047 * @param insert_at where the copied segment is inserted
1049 #define DBUS_STRING_COPY_PREAMBLE(source, start, dest, insert_at) \
1050 DBusRealString *real_source = (DBusRealString*) source; \
1051 DBusRealString *real_dest = (DBusRealString*) dest; \
1052 _dbus_assert ((source) != (dest)); \
1053 DBUS_GENERIC_STRING_PREAMBLE (real_source); \
1054 DBUS_GENERIC_STRING_PREAMBLE (real_dest); \
1055 _dbus_assert (!real_dest->constant); \
1056 _dbus_assert (!real_dest->locked); \
1057 _dbus_assert ((start) >= 0); \
1058 _dbus_assert ((start) <= real_source->len); \
1059 _dbus_assert ((insert_at) >= 0); \
1060 _dbus_assert ((insert_at) <= real_dest->len)
1063 * Moves the end of one string into another string. Both strings
1064 * must be initialized, valid strings.
1066 * @param source the source string
1067 * @param start where to chop off the source string
1068 * @param dest the destination string
1069 * @param insert_at where to move the chopped-off part of source string
1070 * @returns #FALSE if not enough memory
1073 _dbus_string_move (DBusString *source,
1078 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1080 if (!copy (real_source, start,
1081 real_source->len - start,
1086 delete (real_source, start,
1087 real_source->len - start);
1093 * Like _dbus_string_move(), but does not delete the section
1094 * of the source string that's copied to the dest string.
1096 * @param source the source string
1097 * @param start where to start copying the source string
1098 * @param dest the destination string
1099 * @param insert_at where to place the copied part of source string
1100 * @returns #FALSE if not enough memory
1103 _dbus_string_copy (const DBusString *source,
1108 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1110 return copy (real_source, start,
1111 real_source->len - start,
1117 * Like _dbus_string_move(), but can move a segment from
1118 * the middle of the source string.
1120 * @param source the source string
1121 * @param start first byte of source string to move
1122 * @param len length of segment to move
1123 * @param dest the destination string
1124 * @param insert_at where to move the bytes from the source string
1125 * @returns #FALSE if not enough memory
1128 _dbus_string_move_len (DBusString *source,
1135 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1136 _dbus_assert (len >= 0);
1137 _dbus_assert ((start + len) <= real_source->len);
1139 if (!copy (real_source, start, len,
1144 delete (real_source, start,
1151 * Like _dbus_string_copy(), but can copy a segment from the middle of
1152 * the source string.
1154 * @param source the source string
1155 * @param start where to start copying the source string
1156 * @param len length of segment to copy
1157 * @param dest the destination string
1158 * @param insert_at where to place the copied segment of source string
1159 * @returns #FALSE if not enough memory
1162 _dbus_string_copy_len (const DBusString *source,
1168 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1169 _dbus_assert (len >= 0);
1170 _dbus_assert (start <= real_source->len);
1171 _dbus_assert (len <= real_source->len - start);
1173 return copy (real_source, start, len,
1179 * Replaces a segment of dest string with a segment of source string.
1181 * @todo optimize the case where the two lengths are the same, and
1182 * avoid memmoving the data in the trailing part of the string twice.
1184 * @todo avoid inserting the source into dest, then deleting
1185 * the replaced chunk of dest (which creates a potentially large
1186 * intermediate string). Instead, extend the replaced chunk
1187 * of dest with padding to the same size as the source chunk,
1188 * then copy in the source bytes.
1190 * @param source the source string
1191 * @param start where to start copying the source string
1192 * @param len length of segment to copy
1193 * @param dest the destination string
1194 * @param replace_at start of segment of dest string to replace
1195 * @param replace_len length of segment of dest string to replace
1196 * @returns #FALSE if not enough memory
1200 _dbus_string_replace_len (const DBusString *source,
1207 DBUS_STRING_COPY_PREAMBLE (source, start, dest, replace_at);
1208 _dbus_assert (len >= 0);
1209 _dbus_assert (start <= real_source->len);
1210 _dbus_assert (len <= real_source->len - start);
1211 _dbus_assert (replace_at >= 0);
1212 _dbus_assert (replace_at <= real_dest->len);
1213 _dbus_assert (replace_len <= real_dest->len - replace_at);
1215 if (!copy (real_source, start, len,
1216 real_dest, replace_at))
1219 delete (real_dest, replace_at + len, replace_len);
1224 /* Unicode macros and utf8_validate() from GLib Owen Taylor, Havoc
1225 * Pennington, and Tom Tromey are the authors and authorized relicense.
1228 /** computes length and mask of a unicode character
1229 * @param Char the char
1230 * @param Mask the mask variable to assign to
1231 * @param Len the length variable to assign to
1233 #define UTF8_COMPUTE(Char, Mask, Len) \
1239 else if ((Char & 0xe0) == 0xc0) \
1244 else if ((Char & 0xf0) == 0xe0) \
1249 else if ((Char & 0xf8) == 0xf0) \
1254 else if ((Char & 0xfc) == 0xf8) \
1259 else if ((Char & 0xfe) == 0xfc) \
1268 * computes length of a unicode character in UTF-8
1269 * @param Char the char
1271 #define UTF8_LENGTH(Char) \
1272 ((Char) < 0x80 ? 1 : \
1273 ((Char) < 0x800 ? 2 : \
1274 ((Char) < 0x10000 ? 3 : \
1275 ((Char) < 0x200000 ? 4 : \
1276 ((Char) < 0x4000000 ? 5 : 6)))))
1279 * Gets a UTF-8 value.
1281 * @param Result variable for extracted unicode char.
1282 * @param Chars the bytes to decode
1283 * @param Count counter variable
1284 * @param Mask mask for this char
1285 * @param Len length for this char in bytes
1287 #define UTF8_GET(Result, Chars, Count, Mask, Len) \
1288 (Result) = (Chars)[0] & (Mask); \
1289 for ((Count) = 1; (Count) < (Len); ++(Count)) \
1291 if (((Chars)[(Count)] & 0xc0) != 0x80) \
1297 (Result) |= ((Chars)[(Count)] & 0x3f); \
1301 * Check whether a unicode char is in a valid range.
1303 * @param Char the character
1305 #define UNICODE_VALID(Char) \
1306 ((Char) < 0x110000 && \
1307 (((Char) & 0xFFFFF800) != 0xD800) && \
1308 ((Char) < 0xFDD0 || (Char) > 0xFDEF) && \
1309 ((Char) & 0xFFFF) != 0xFFFF)
1312 * Gets a unicode character from a UTF-8 string. Does no validation;
1313 * you must verify that the string is valid UTF-8 in advance and must
1314 * pass in the start of a character.
1316 * @param str the string
1317 * @param start the start of the UTF-8 character.
1318 * @param ch_return location to return the character
1319 * @param end_return location to return the byte index of next character
1322 _dbus_string_get_unichar (const DBusString *str,
1324 dbus_unichar_t *ch_return,
1328 dbus_unichar_t result;
1331 DBUS_CONST_STRING_PREAMBLE (str);
1332 _dbus_assert (start >= 0);
1333 _dbus_assert (start <= real->len);
1338 *end_return = real->len;
1341 p = real->str + start;
1344 UTF8_COMPUTE (c, mask, len);
1347 UTF8_GET (result, p, i, mask, len);
1349 if (result == (dbus_unichar_t)-1)
1353 *ch_return = result;
1355 *end_return = start + len;
1359 * Finds the given substring in the string,
1360 * returning #TRUE and filling in the byte index
1361 * where the substring was found, if it was found.
1362 * Returns #FALSE if the substring wasn't found.
1363 * Sets *start to the length of the string if the substring
1366 * @param str the string
1367 * @param start where to start looking
1368 * @param substr the substring
1369 * @param found return location for where it was found, or #NULL
1370 * @returns #TRUE if found
1373 _dbus_string_find (const DBusString *str,
1378 return _dbus_string_find_to (str, start,
1379 ((const DBusRealString*)str)->len,
1384 * Finds the given substring in the string,
1385 * up to a certain position,
1386 * returning #TRUE and filling in the byte index
1387 * where the substring was found, if it was found.
1388 * Returns #FALSE if the substring wasn't found.
1389 * Sets *start to the length of the string if the substring
1392 * @param str the string
1393 * @param start where to start looking
1394 * @param end where to stop looking
1395 * @param substr the substring
1396 * @param found return location for where it was found, or #NULL
1397 * @returns #TRUE if found
1400 _dbus_string_find_to (const DBusString *str,
1407 DBUS_CONST_STRING_PREAMBLE (str);
1408 _dbus_assert (substr != NULL);
1409 _dbus_assert (start <= real->len);
1410 _dbus_assert (start >= 0);
1411 _dbus_assert (substr != NULL);
1412 _dbus_assert (end <= real->len);
1413 _dbus_assert (start <= end);
1415 /* we always "find" an empty string */
1416 if (*substr == '\0')
1426 if (real->str[i] == substr[0])
1432 if (substr[j - i] == '\0')
1434 else if (real->str[j] != substr[j - i])
1440 if (substr[j - i] == '\0')
1458 * Find the given byte scanning backward from the given start.
1459 * Sets *found to -1 if the byte is not found.
1461 * @param str the string
1462 * @param start the place to start scanning (will not find the byte at this point)
1463 * @param byte the byte to find
1464 * @param found return location for where it was found
1465 * @returns #TRUE if found
1468 _dbus_string_find_byte_backward (const DBusString *str,
1474 DBUS_CONST_STRING_PREAMBLE (str);
1475 _dbus_assert (start <= real->len);
1476 _dbus_assert (start >= 0);
1477 _dbus_assert (found != NULL);
1482 if (real->str[i] == byte)
1495 * Finds a blank (space or tab) in the string. Returns #TRUE
1496 * if found, #FALSE otherwise. If a blank is not found sets
1497 * *found to the length of the string.
1499 * @param str the string
1500 * @param start byte index to start looking
1501 * @param found place to store the location of the first blank
1502 * @returns #TRUE if a blank was found
1505 _dbus_string_find_blank (const DBusString *str,
1510 DBUS_CONST_STRING_PREAMBLE (str);
1511 _dbus_assert (start <= real->len);
1512 _dbus_assert (start >= 0);
1515 while (i < real->len)
1517 if (real->str[i] == ' ' ||
1518 real->str[i] == '\t')
1535 * Skips blanks from start, storing the first non-blank in *end
1536 * (blank is space or tab).
1538 * @param str the string
1539 * @param start where to start
1540 * @param end where to store the first non-blank byte index
1543 _dbus_string_skip_blank (const DBusString *str,
1548 DBUS_CONST_STRING_PREAMBLE (str);
1549 _dbus_assert (start <= real->len);
1550 _dbus_assert (start >= 0);
1553 while (i < real->len)
1555 if (!(real->str[i] == ' ' ||
1556 real->str[i] == '\t'))
1562 _dbus_assert (i == real->len || !(real->str[i] == ' ' ||
1563 real->str[i] == '\t'));
1570 * Skips whitespace from start, storing the first non-whitespace in *end.
1571 * (whitespace is space, tab, newline, CR).
1573 * @param str the string
1574 * @param start where to start
1575 * @param end where to store the first non-whitespace byte index
1578 _dbus_string_skip_white (const DBusString *str,
1583 DBUS_CONST_STRING_PREAMBLE (str);
1584 _dbus_assert (start <= real->len);
1585 _dbus_assert (start >= 0);
1588 while (i < real->len)
1590 if (!(real->str[i] == ' ' ||
1591 real->str[i] == '\n' ||
1592 real->str[i] == '\r' ||
1593 real->str[i] == '\t'))
1599 _dbus_assert (i == real->len || !(real->str[i] == ' ' ||
1600 real->str[i] == '\t'));
1607 * Assigns a newline-terminated or \r\n-terminated line from the front
1608 * of the string to the given dest string. The dest string's previous
1609 * contents are deleted. If the source string contains no newline,
1610 * moves the entire source string to the dest string.
1612 * @todo owen correctly notes that this is a stupid function (it was
1613 * written purely for test code,
1614 * e.g. dbus-message-builder.c). Probably should be enforced as test
1615 * code only with #ifdef DBUS_BUILD_TESTS
1617 * @param source the source string
1618 * @param dest the destination string (contents are replaced)
1619 * @returns #FALSE if no memory, or source has length 0
1622 _dbus_string_pop_line (DBusString *source,
1626 dbus_bool_t have_newline;
1628 _dbus_string_set_length (dest, 0);
1631 if (_dbus_string_find (source, 0, "\n", &eol))
1633 have_newline = TRUE;
1634 eol += 1; /* include newline */
1638 eol = _dbus_string_get_length (source);
1639 have_newline = FALSE;
1643 return FALSE; /* eof */
1645 if (!_dbus_string_move_len (source, 0, eol,
1651 /* dump the newline and the \r if we have one */
1654 dbus_bool_t have_cr;
1656 _dbus_assert (_dbus_string_get_length (dest) > 0);
1658 if (_dbus_string_get_length (dest) > 1 &&
1659 _dbus_string_get_byte (dest,
1660 _dbus_string_get_length (dest) - 2) == '\r')
1665 _dbus_string_set_length (dest,
1666 _dbus_string_get_length (dest) -
1674 * Deletes up to and including the first blank space
1677 * @param str the string
1680 _dbus_string_delete_first_word (DBusString *str)
1684 if (_dbus_string_find_blank (str, 0, &i))
1685 _dbus_string_skip_blank (str, i, &i);
1687 _dbus_string_delete (str, 0, i);
1691 * Deletes any leading blanks in the string
1693 * @param str the string
1696 _dbus_string_delete_leading_blanks (DBusString *str)
1700 _dbus_string_skip_blank (str, 0, &i);
1703 _dbus_string_delete (str, 0, i);
1707 * Tests two DBusString for equality.
1709 * @todo memcmp is probably faster
1711 * @param a first string
1712 * @param b second string
1713 * @returns #TRUE if equal
1716 _dbus_string_equal (const DBusString *a,
1717 const DBusString *b)
1719 const unsigned char *ap;
1720 const unsigned char *bp;
1721 const unsigned char *a_end;
1722 const DBusRealString *real_a = (const DBusRealString*) a;
1723 const DBusRealString *real_b = (const DBusRealString*) b;
1724 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1725 DBUS_GENERIC_STRING_PREAMBLE (real_b);
1727 if (real_a->len != real_b->len)
1732 a_end = real_a->str + real_a->len;
1746 * Tests two DBusString for equality up to the given length.
1748 * @todo write a unit test
1750 * @todo memcmp is probably faster
1752 * @param a first string
1753 * @param b second string
1754 * @param len the lengh
1755 * @returns #TRUE if equal for the given number of bytes
1758 _dbus_string_equal_len (const DBusString *a,
1759 const DBusString *b,
1762 const unsigned char *ap;
1763 const unsigned char *bp;
1764 const unsigned char *a_end;
1765 const DBusRealString *real_a = (const DBusRealString*) a;
1766 const DBusRealString *real_b = (const DBusRealString*) b;
1767 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1768 DBUS_GENERIC_STRING_PREAMBLE (real_b);
1770 if (real_a->len != real_b->len &&
1771 (real_a->len < len || real_b->len < len))
1776 a_end = real_a->str + MIN (real_a->len, len);
1790 * Checks whether a string is equal to a C string.
1792 * @param a the string
1793 * @param c_str the C string
1794 * @returns #TRUE if equal
1797 _dbus_string_equal_c_str (const DBusString *a,
1800 const unsigned char *ap;
1801 const unsigned char *bp;
1802 const unsigned char *a_end;
1803 const DBusRealString *real_a = (const DBusRealString*) a;
1804 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1805 _dbus_assert (c_str != NULL);
1808 bp = (const unsigned char*) c_str;
1809 a_end = real_a->str + real_a->len;
1810 while (ap != a_end && *bp)
1819 if (ap != a_end || *bp)
1826 * Checks whether a string starts with the given C string.
1828 * @param a the string
1829 * @param c_str the C string
1830 * @returns #TRUE if string starts with it
1833 _dbus_string_starts_with_c_str (const DBusString *a,
1836 const unsigned char *ap;
1837 const unsigned char *bp;
1838 const unsigned char *a_end;
1839 const DBusRealString *real_a = (const DBusRealString*) a;
1840 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1841 _dbus_assert (c_str != NULL);
1844 bp = (const unsigned char*) c_str;
1845 a_end = real_a->str + real_a->len;
1846 while (ap != a_end && *bp)
1862 * Returns whether a string ends with the given suffix
1864 * @todo memcmp might make this faster.
1866 * @param a the string
1867 * @param c_str the C-style string
1868 * @returns #TRUE if the string ends with the suffix
1871 _dbus_string_ends_with_c_str (const DBusString *a,
1874 const unsigned char *ap;
1875 const unsigned char *bp;
1876 const unsigned char *a_end;
1877 unsigned long c_str_len;
1878 const DBusRealString *real_a = (const DBusRealString*) a;
1879 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1880 _dbus_assert (c_str != NULL);
1882 c_str_len = strlen (c_str);
1883 if (((unsigned long)real_a->len) < c_str_len)
1886 ap = real_a->str + (real_a->len - c_str_len);
1887 bp = (const unsigned char*) c_str;
1888 a_end = real_a->str + real_a->len;
1898 _dbus_assert (*ap == '\0');
1899 _dbus_assert (*bp == '\0');
1904 static const signed char base64_table[] = {
1971 /** The minimum char that's a valid char in Base64-encoded text */
1972 #define UNBASE64_MIN_CHAR (43)
1973 /** The maximum char that's a valid char in Base64-encoded text */
1974 #define UNBASE64_MAX_CHAR (122)
1975 /** Must subtract this from a char's integer value before offsetting
1976 * into unbase64_table
1978 #define UNBASE64_TABLE_OFFSET UNBASE64_MIN_CHAR
1979 static const signed char unbase64_table[] = {
2063 * Encodes a string using Base64, as documented in RFC 2045.
2065 * @param source the string to encode
2066 * @param start byte index to start encoding
2067 * @param dest string where encoded data should be placed
2068 * @param insert_at where to place encoded data
2069 * @returns #TRUE if encoding was successful, #FALSE if no memory etc.
2072 _dbus_string_base64_encode (const DBusString *source,
2078 unsigned int dest_len; /* unsigned for overflow checks below */
2079 const unsigned char *s;
2081 const unsigned char *triplet_end;
2082 const unsigned char *final_end;
2083 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
2084 _dbus_assert (source != dest);
2086 /* For each 24 bits (3 bytes) of input, we have 4 bytes of
2089 source_len = real_source->len - start;
2090 dest_len = (source_len / 3) * 4;
2091 if (source_len % 3 != 0)
2094 if (dest_len > (unsigned int) real_dest->max_length)
2097 if (source_len == 0)
2100 if (!open_gap (dest_len, real_dest, insert_at))
2103 d = real_dest->str + insert_at;
2104 s = real_source->str + start;
2105 final_end = real_source->str + (start + source_len);
2106 triplet_end = final_end - (source_len % 3);
2107 _dbus_assert (triplet_end <= final_end);
2108 _dbus_assert ((final_end - triplet_end) < 3);
2110 #define ENCODE_64(v) (base64_table[ (unsigned char) (v) ])
2111 #define SIX_BITS_MASK (0x3f)
2112 _dbus_assert (SIX_BITS_MASK < _DBUS_N_ELEMENTS (base64_table));
2114 while (s != triplet_end)
2116 unsigned int triplet;
2118 triplet = s[2] | (s[1] << 8) | (s[0] << 16);
2120 /* Encode each 6 bits. */
2122 *d++ = ENCODE_64 (triplet >> 18);
2123 *d++ = ENCODE_64 ((triplet >> 12) & SIX_BITS_MASK);
2124 *d++ = ENCODE_64 ((triplet >> 6) & SIX_BITS_MASK);
2125 *d++ = ENCODE_64 (triplet & SIX_BITS_MASK);
2130 switch (final_end - triplet_end)
2134 unsigned int doublet;
2136 doublet = s[1] | (s[0] << 8);
2138 *d++ = ENCODE_64 (doublet >> 12);
2139 *d++ = ENCODE_64 ((doublet >> 6) & SIX_BITS_MASK);
2140 *d++ = ENCODE_64 (doublet & SIX_BITS_MASK);
2146 unsigned int singlet;
2150 *d++ = ENCODE_64 ((singlet >> 6) & SIX_BITS_MASK);
2151 *d++ = ENCODE_64 (singlet & SIX_BITS_MASK);
2160 _dbus_assert (d == (real_dest->str + (insert_at + dest_len)));
2166 * Decodes a string from Base64, as documented in RFC 2045.
2168 * @todo sort out the AUDIT comment in here. The case it mentions
2169 * ("====" or "x===") is not allowed in correct base64, so need to
2170 * decide what to do with that kind of input. Probably ignore it
2171 * since we ignore any other junk seen.
2173 * @param source the string to decode
2174 * @param start byte index to start decode
2175 * @param dest string where decoded data should be placed
2176 * @param insert_at where to place decoded data
2177 * @returns #TRUE if decoding was successful, #FALSE if no memory etc.
2180 _dbus_string_base64_decode (const DBusString *source,
2189 unsigned int triplet = 0;
2192 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
2193 _dbus_assert (source != dest);
2195 source_len = real_source->len - start;
2196 s = real_source->str + start;
2197 end = real_source->str + source_len;
2199 if (source_len == 0)
2202 if (!_dbus_string_init (&result))
2209 /* The idea is to just skip anything that isn't
2210 * a base64 char - it's allowed to have whitespace,
2211 * newlines, etc. in here. We also ignore trailing
2212 * base64 chars, though that's suspicious.
2215 if (*s >= UNBASE64_MIN_CHAR &&
2216 *s <= UNBASE64_MAX_CHAR)
2220 /* '=' is padding, doesn't represent additional data
2221 * but does increment our count.
2230 val = unbase64_table[(*s) - UNBASE64_TABLE_OFFSET];
2235 triplet |= (unsigned int) val;
2240 if (sextet_count == 4)
2242 /* no pad = 3 bytes, 1 pad = 2 bytes, 2 pad = 1 byte */
2245 /* AUDIT: Comment doesn't mention 4 pad => 0,
2246 * 3 pad => 1 byte, though the code should
2247 * work fine if those are the required outputs.
2249 * I assume that the spec requires dropping
2250 * the top two bits of, say, ///= which is > 2
2251 * bytes worth of bits. (Or otherwise, you couldn't
2252 * actually represent 2 byte sequences.
2257 if (!_dbus_string_append_byte (&result,
2264 if (!_dbus_string_append_byte (&result,
2265 (triplet >> 8) & 0xff))
2269 if (!_dbus_string_append_byte (&result,
2282 if (!_dbus_string_move (&result, 0, dest, insert_at))
2284 _dbus_string_free (&result);
2288 _dbus_string_free (&result);
2293 _dbus_string_free (&result);
2299 * Encodes a string in hex, the way MD5 and SHA-1 are usually
2300 * encoded. (Each byte is two hex digits.)
2302 * @param source the string to encode
2303 * @param start byte index to start encoding
2304 * @param dest string where encoded data should be placed
2305 * @param insert_at where to place encoded data
2306 * @returns #TRUE if encoding was successful, #FALSE if no memory etc.
2309 _dbus_string_hex_encode (const DBusString *source,
2315 const char hexdigits[16] = {
2316 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
2317 'a', 'b', 'c', 'd', 'e', 'f'
2319 const unsigned char *p;
2320 const unsigned char *end;
2323 _dbus_assert (start <= _dbus_string_get_length (source));
2325 if (!_dbus_string_init (&result))
2330 p = (const unsigned char*) _dbus_string_get_const_data (source);
2331 end = p + _dbus_string_get_length (source);
2336 if (!_dbus_string_append_byte (&result,
2337 hexdigits[(*p >> 4)]))
2340 if (!_dbus_string_append_byte (&result,
2341 hexdigits[(*p & 0x0f)]))
2347 if (!_dbus_string_move (&result, 0, dest, insert_at))
2353 _dbus_string_free (&result);
2358 * Decodes a string from hex encoding.
2360 * @param source the string to decode
2361 * @param start byte index to start decode
2362 * @param dest string where decoded data should be placed
2363 * @param insert_at where to place decoded data
2364 * @returns #TRUE if decoding was successful, #FALSE if no memory etc.
2367 _dbus_string_hex_decode (const DBusString *source,
2373 const unsigned char *p;
2374 const unsigned char *end;
2376 dbus_bool_t high_bits;
2378 _dbus_assert (start <= _dbus_string_get_length (source));
2380 if (!_dbus_string_init (&result))
2386 p = (const unsigned char*) _dbus_string_get_const_data (source);
2387 end = p + _dbus_string_get_length (source);
2452 _dbus_verbose ("invalid character '%c' in hex encoded text\n",
2459 if (!_dbus_string_append_byte (&result,
2468 len = _dbus_string_get_length (&result);
2470 b = _dbus_string_get_byte (&result, len - 1);
2474 _dbus_string_set_byte (&result, len - 1, b);
2477 high_bits = !high_bits;
2482 if (!_dbus_string_move (&result, 0, dest, insert_at))
2488 _dbus_string_free (&result);
2493 * Checks that the given range of the string is valid ASCII with no
2494 * nul bytes. If the given range is not entirely contained in the
2495 * string, returns #FALSE.
2497 * @todo this is inconsistent with most of DBusString in that
2498 * it allows a start,len range that isn't in the string.
2500 * @param str the string
2501 * @param start first byte index to check
2502 * @param len number of bytes to check
2503 * @returns #TRUE if the byte range exists and is all valid ASCII
2506 _dbus_string_validate_ascii (const DBusString *str,
2510 const unsigned char *s;
2511 const unsigned char *end;
2512 DBUS_CONST_STRING_PREAMBLE (str);
2513 _dbus_assert (start >= 0);
2514 _dbus_assert (start <= real->len);
2515 _dbus_assert (len >= 0);
2517 if (len > real->len - start)
2520 s = real->str + start;
2525 ((*s & ~0x7f) != 0))
2535 * Checks that the given range of the string is valid UTF-8. If the
2536 * given range is not entirely contained in the string, returns
2537 * #FALSE. If the string contains any nul bytes in the given range,
2538 * returns #FALSE. If the start and start+len are not on character
2539 * boundaries, returns #FALSE.
2541 * @todo this is inconsistent with most of DBusString in that
2542 * it allows a start,len range that isn't in the string.
2544 * @param str the string
2545 * @param start first byte index to check
2546 * @param len number of bytes to check
2547 * @returns #TRUE if the byte range exists and is all valid UTF-8
2550 _dbus_string_validate_utf8 (const DBusString *str,
2554 const unsigned char *p;
2555 const unsigned char *end;
2556 DBUS_CONST_STRING_PREAMBLE (str);
2557 _dbus_assert (start >= 0);
2558 _dbus_assert (start <= real->len);
2559 _dbus_assert (len >= 0);
2561 if (len > real->len - start)
2564 p = real->str + start;
2569 int i, mask = 0, char_len;
2570 dbus_unichar_t result;
2571 unsigned char c = (unsigned char) *p;
2573 UTF8_COMPUTE (c, mask, char_len);
2578 /* check that the expected number of bytes exists in the remaining length */
2579 if ((end - p) < char_len)
2582 UTF8_GET (result, p, i, mask, char_len);
2584 if (UTF8_LENGTH (result) != char_len) /* Check for overlong UTF-8 */
2587 if (result == (dbus_unichar_t)-1)
2590 if (!UNICODE_VALID (result))
2596 /* See that we covered the entire length if a length was
2606 * Checks that the given range of the string is all nul bytes. If the
2607 * given range is not entirely contained in the string, returns
2610 * @todo this is inconsistent with most of DBusString in that
2611 * it allows a start,len range that isn't in the string.
2613 * @param str the string
2614 * @param start first byte index to check
2615 * @param len number of bytes to check
2616 * @returns #TRUE if the byte range exists and is all nul bytes
2619 _dbus_string_validate_nul (const DBusString *str,
2623 const unsigned char *s;
2624 const unsigned char *end;
2625 DBUS_CONST_STRING_PREAMBLE (str);
2626 _dbus_assert (start >= 0);
2627 _dbus_assert (len >= 0);
2628 _dbus_assert (start <= real->len);
2630 if (len > real->len - start)
2633 s = real->str + start;
2646 * Checks that the given range of the string is a valid message name
2647 * in the D-BUS protocol. This includes a length restriction, etc.,
2648 * see the specification. It does not validate UTF-8, that has to be
2649 * done separately for now.
2651 * @todo this is inconsistent with most of DBusString in that
2652 * it allows a start,len range that isn't in the string.
2654 * @param str the string
2655 * @param start first byte index to check
2656 * @param len number of bytes to check
2657 * @returns #TRUE if the byte range exists and is a valid name
2660 _dbus_string_validate_name (const DBusString *str,
2664 const unsigned char *s;
2665 const unsigned char *end;
2666 dbus_bool_t saw_dot;
2668 DBUS_CONST_STRING_PREAMBLE (str);
2669 _dbus_assert (start >= 0);
2670 _dbus_assert (len >= 0);
2671 _dbus_assert (start <= real->len);
2673 if (len > real->len - start)
2676 if (len > DBUS_MAXIMUM_NAME_LENGTH)
2683 s = real->str + start;
2704 * Checks that the given range of the string is a valid service name
2705 * in the D-BUS protocol. This includes a length restriction, etc.,
2706 * see the specification. It does not validate UTF-8, that has to be
2707 * done separately for now.
2709 * @todo this is inconsistent with most of DBusString in that
2710 * it allows a start,len range that isn't in the string.
2712 * @param str the string
2713 * @param start first byte index to check
2714 * @param len number of bytes to check
2715 * @returns #TRUE if the byte range exists and is a valid name
2718 _dbus_string_validate_service (const DBusString *str,
2722 const unsigned char *s;
2723 const unsigned char *end;
2724 dbus_bool_t saw_dot;
2725 dbus_bool_t is_base_service;
2727 DBUS_CONST_STRING_PREAMBLE (str);
2728 _dbus_assert (start >= 0);
2729 _dbus_assert (len >= 0);
2730 _dbus_assert (start <= real->len);
2732 if (len > real->len - start)
2735 if (len > DBUS_MAXIMUM_NAME_LENGTH)
2741 is_base_service = _dbus_string_get_byte (str, start) == ':';
2742 if (is_base_service)
2743 return TRUE; /* can have any content */
2745 /* non-base-service must have the '.' indicating a namespace */
2748 s = real->str + start;
2765 * Clears all allocated bytes in the string to zero.
2767 * @param str the string
2770 _dbus_string_zero (DBusString *str)
2772 DBUS_STRING_PREAMBLE (str);
2774 memset (real->str - real->align_offset, '\0', real->allocated);
2778 #ifdef DBUS_BUILD_TESTS
2779 #include "dbus-test.h"
2783 test_max_len (DBusString *str,
2788 if (!_dbus_string_set_length (str, max_len - 1))
2789 _dbus_assert_not_reached ("setting len to one less than max should have worked");
2792 if (!_dbus_string_set_length (str, max_len))
2793 _dbus_assert_not_reached ("setting len to max len should have worked");
2795 if (_dbus_string_set_length (str, max_len + 1))
2796 _dbus_assert_not_reached ("setting len to one more than max len should not have worked");
2798 if (!_dbus_string_set_length (str, 0))
2799 _dbus_assert_not_reached ("setting len to zero should have worked");
2803 test_base64_roundtrip (const unsigned char *data,
2811 len = strlen (data);
2813 if (!_dbus_string_init (&orig))
2814 _dbus_assert_not_reached ("could not init string");
2816 if (!_dbus_string_init (&encoded))
2817 _dbus_assert_not_reached ("could not init string");
2819 if (!_dbus_string_init (&decoded))
2820 _dbus_assert_not_reached ("could not init string");
2822 if (!_dbus_string_append_len (&orig, data, len))
2823 _dbus_assert_not_reached ("couldn't append orig data");
2825 if (!_dbus_string_base64_encode (&orig, 0, &encoded, 0))
2826 _dbus_assert_not_reached ("could not encode");
2828 if (!_dbus_string_base64_decode (&encoded, 0, &decoded, 0))
2829 _dbus_assert_not_reached ("could not decode");
2831 if (!_dbus_string_equal (&orig, &decoded))
2835 printf ("Original string %d bytes encoded %d bytes decoded %d bytes\n",
2836 _dbus_string_get_length (&orig),
2837 _dbus_string_get_length (&encoded),
2838 _dbus_string_get_length (&decoded));
2839 printf ("Original: %s\n", data);
2840 s = _dbus_string_get_const_data (&decoded);
2841 printf ("Decoded: %s\n", s);
2842 _dbus_assert_not_reached ("original string not the same as string decoded from base64");
2845 _dbus_string_free (&orig);
2846 _dbus_string_free (&encoded);
2847 _dbus_string_free (&decoded);
2851 test_hex_roundtrip (const unsigned char *data,
2859 len = strlen (data);
2861 if (!_dbus_string_init (&orig))
2862 _dbus_assert_not_reached ("could not init string");
2864 if (!_dbus_string_init (&encoded))
2865 _dbus_assert_not_reached ("could not init string");
2867 if (!_dbus_string_init (&decoded))
2868 _dbus_assert_not_reached ("could not init string");
2870 if (!_dbus_string_append_len (&orig, data, len))
2871 _dbus_assert_not_reached ("couldn't append orig data");
2873 if (!_dbus_string_hex_encode (&orig, 0, &encoded, 0))
2874 _dbus_assert_not_reached ("could not encode");
2876 if (!_dbus_string_hex_decode (&encoded, 0, &decoded, 0))
2877 _dbus_assert_not_reached ("could not decode");
2879 if (!_dbus_string_equal (&orig, &decoded))
2883 printf ("Original string %d bytes encoded %d bytes decoded %d bytes\n",
2884 _dbus_string_get_length (&orig),
2885 _dbus_string_get_length (&encoded),
2886 _dbus_string_get_length (&decoded));
2887 printf ("Original: %s\n", data);
2888 s = _dbus_string_get_const_data (&decoded);
2889 printf ("Decoded: %s\n", s);
2890 _dbus_assert_not_reached ("original string not the same as string decoded from base64");
2893 _dbus_string_free (&orig);
2894 _dbus_string_free (&encoded);
2895 _dbus_string_free (&decoded);
2898 typedef void (* TestRoundtripFunc) (const unsigned char *data,
2901 test_roundtrips (TestRoundtripFunc func)
2903 (* func) ("Hello this is a string\n", -1);
2904 (* func) ("Hello this is a string\n1", -1);
2905 (* func) ("Hello this is a string\n12", -1);
2906 (* func) ("Hello this is a string\n123", -1);
2907 (* func) ("Hello this is a string\n1234", -1);
2908 (* func) ("Hello this is a string\n12345", -1);
2912 (* func) ("123", 3);
2913 (* func) ("1234", 4);
2914 (* func) ("12345", 5);
2918 (* func) ("123", 4);
2919 (* func) ("1234", 5);
2920 (* func) ("12345", 6);
2922 unsigned char buf[512];
2926 while (i < _DBUS_N_ELEMENTS (buf))
2932 while (i < _DBUS_N_ELEMENTS (buf))
2942 * @ingroup DBusStringInternals
2943 * Unit test for DBusString.
2945 * @todo Need to write tests for _dbus_string_copy() and
2946 * _dbus_string_move() moving to/from each of start/middle/end of a
2947 * string. Also need tests for _dbus_string_move_len ()
2949 * @returns #TRUE on success.
2952 _dbus_string_test (void)
2959 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 };
2964 while (i < _DBUS_N_ELEMENTS (lens))
2966 if (!_dbus_string_init (&str))
2967 _dbus_assert_not_reached ("failed to init string");
2969 set_max_length (&str, lens[i]);
2971 test_max_len (&str, lens[i]);
2972 _dbus_string_free (&str);
2977 /* Test shortening and setting length */
2979 while (i < _DBUS_N_ELEMENTS (lens))
2983 if (!_dbus_string_init (&str))
2984 _dbus_assert_not_reached ("failed to init string");
2986 set_max_length (&str, lens[i]);
2988 if (!_dbus_string_set_length (&str, lens[i]))
2989 _dbus_assert_not_reached ("failed to set string length");
2994 _dbus_assert (_dbus_string_get_length (&str) == j);
2997 _dbus_string_shorten (&str, 1);
2998 _dbus_assert (_dbus_string_get_length (&str) == (j - 1));
3003 _dbus_string_free (&str);
3008 /* Test appending data */
3009 if (!_dbus_string_init (&str))
3010 _dbus_assert_not_reached ("failed to init string");
3015 if (!_dbus_string_append (&str, "a"))
3016 _dbus_assert_not_reached ("failed to append string to string\n");
3018 _dbus_assert (_dbus_string_get_length (&str) == i * 2 + 1);
3020 if (!_dbus_string_append_byte (&str, 'b'))
3021 _dbus_assert_not_reached ("failed to append byte to string\n");
3023 _dbus_assert (_dbus_string_get_length (&str) == i * 2 + 2);
3028 _dbus_string_free (&str);
3030 /* Check steal_data */
3032 if (!_dbus_string_init (&str))
3033 _dbus_assert_not_reached ("failed to init string");
3035 if (!_dbus_string_append (&str, "Hello World"))
3036 _dbus_assert_not_reached ("could not append to string");
3038 i = _dbus_string_get_length (&str);
3040 if (!_dbus_string_steal_data (&str, &s))
3041 _dbus_assert_not_reached ("failed to steal data");
3043 _dbus_assert (_dbus_string_get_length (&str) == 0);
3044 _dbus_assert (((int)strlen (s)) == i);
3050 if (!_dbus_string_append (&str, "Hello World"))
3051 _dbus_assert_not_reached ("could not append to string");
3053 i = _dbus_string_get_length (&str);
3055 if (!_dbus_string_init (&other))
3056 _dbus_assert_not_reached ("could not init string");
3058 if (!_dbus_string_move (&str, 0, &other, 0))
3059 _dbus_assert_not_reached ("could not move");
3061 _dbus_assert (_dbus_string_get_length (&str) == 0);
3062 _dbus_assert (_dbus_string_get_length (&other) == i);
3064 if (!_dbus_string_append (&str, "Hello World"))
3065 _dbus_assert_not_reached ("could not append to string");
3067 if (!_dbus_string_move (&str, 0, &other, _dbus_string_get_length (&other)))
3068 _dbus_assert_not_reached ("could not move");
3070 _dbus_assert (_dbus_string_get_length (&str) == 0);
3071 _dbus_assert (_dbus_string_get_length (&other) == i * 2);
3073 if (!_dbus_string_append (&str, "Hello World"))
3074 _dbus_assert_not_reached ("could not append to string");
3076 if (!_dbus_string_move (&str, 0, &other, _dbus_string_get_length (&other) / 2))
3077 _dbus_assert_not_reached ("could not move");
3079 _dbus_assert (_dbus_string_get_length (&str) == 0);
3080 _dbus_assert (_dbus_string_get_length (&other) == i * 3);
3082 _dbus_string_free (&other);
3086 if (!_dbus_string_append (&str, "Hello World"))
3087 _dbus_assert_not_reached ("could not append to string");
3089 i = _dbus_string_get_length (&str);
3091 if (!_dbus_string_init (&other))
3092 _dbus_assert_not_reached ("could not init string");
3094 if (!_dbus_string_copy (&str, 0, &other, 0))
3095 _dbus_assert_not_reached ("could not copy");
3097 _dbus_assert (_dbus_string_get_length (&str) == i);
3098 _dbus_assert (_dbus_string_get_length (&other) == i);
3100 if (!_dbus_string_copy (&str, 0, &other, _dbus_string_get_length (&other)))
3101 _dbus_assert_not_reached ("could not copy");
3103 _dbus_assert (_dbus_string_get_length (&str) == i);
3104 _dbus_assert (_dbus_string_get_length (&other) == i * 2);
3105 _dbus_assert (_dbus_string_equal_c_str (&other,
3106 "Hello WorldHello World"));
3108 if (!_dbus_string_copy (&str, 0, &other, _dbus_string_get_length (&other) / 2))
3109 _dbus_assert_not_reached ("could not copy");
3111 _dbus_assert (_dbus_string_get_length (&str) == i);
3112 _dbus_assert (_dbus_string_get_length (&other) == i * 3);
3113 _dbus_assert (_dbus_string_equal_c_str (&other,
3114 "Hello WorldHello WorldHello World"));
3116 _dbus_string_free (&str);
3117 _dbus_string_free (&other);
3121 if (!_dbus_string_init (&str))
3122 _dbus_assert_not_reached ("failed to init string");
3124 if (!_dbus_string_append (&str, "Hello World"))
3125 _dbus_assert_not_reached ("could not append to string");
3127 i = _dbus_string_get_length (&str);
3129 if (!_dbus_string_init (&other))
3130 _dbus_assert_not_reached ("could not init string");
3132 if (!_dbus_string_replace_len (&str, 0, _dbus_string_get_length (&str),
3133 &other, 0, _dbus_string_get_length (&other)))
3134 _dbus_assert_not_reached ("could not replace");
3136 _dbus_assert (_dbus_string_get_length (&str) == i);
3137 _dbus_assert (_dbus_string_get_length (&other) == i);
3138 _dbus_assert (_dbus_string_equal_c_str (&other, "Hello World"));
3140 if (!_dbus_string_replace_len (&str, 0, _dbus_string_get_length (&str),
3142 _dbus_assert_not_reached ("could not replace center space");
3144 _dbus_assert (_dbus_string_get_length (&str) == i);
3145 _dbus_assert (_dbus_string_get_length (&other) == i * 2 - 1);
3146 _dbus_assert (_dbus_string_equal_c_str (&other,
3147 "HelloHello WorldWorld"));
3150 if (!_dbus_string_replace_len (&str, 1, 1,
3152 _dbus_string_get_length (&other) - 1,
3154 _dbus_assert_not_reached ("could not replace end character");
3156 _dbus_assert (_dbus_string_get_length (&str) == i);
3157 _dbus_assert (_dbus_string_get_length (&other) == i * 2 - 1);
3158 _dbus_assert (_dbus_string_equal_c_str (&other,
3159 "HelloHello WorldWorle"));
3161 _dbus_string_free (&str);
3162 _dbus_string_free (&other);
3164 /* Check append/get unichar */
3166 if (!_dbus_string_init (&str))
3167 _dbus_assert_not_reached ("failed to init string");
3170 if (!_dbus_string_append_unichar (&str, 0xfffc))
3171 _dbus_assert_not_reached ("failed to append unichar");
3173 _dbus_string_get_unichar (&str, 0, &ch, &i);
3175 _dbus_assert (ch == 0xfffc);
3176 _dbus_assert (i == _dbus_string_get_length (&str));
3178 _dbus_string_free (&str);
3180 /* Check insert/set/get byte */
3182 if (!_dbus_string_init (&str))
3183 _dbus_assert_not_reached ("failed to init string");
3185 if (!_dbus_string_append (&str, "Hello"))
3186 _dbus_assert_not_reached ("failed to append Hello");
3188 _dbus_assert (_dbus_string_get_byte (&str, 0) == 'H');
3189 _dbus_assert (_dbus_string_get_byte (&str, 1) == 'e');
3190 _dbus_assert (_dbus_string_get_byte (&str, 2) == 'l');
3191 _dbus_assert (_dbus_string_get_byte (&str, 3) == 'l');
3192 _dbus_assert (_dbus_string_get_byte (&str, 4) == 'o');
3194 _dbus_string_set_byte (&str, 1, 'q');
3195 _dbus_assert (_dbus_string_get_byte (&str, 1) == 'q');
3197 if (!_dbus_string_insert_byte (&str, 0, 255))
3198 _dbus_assert_not_reached ("can't insert byte");
3200 if (!_dbus_string_insert_byte (&str, 2, 'Z'))
3201 _dbus_assert_not_reached ("can't insert byte");
3203 if (!_dbus_string_insert_byte (&str, _dbus_string_get_length (&str), 'W'))
3204 _dbus_assert_not_reached ("can't insert byte");
3206 _dbus_assert (_dbus_string_get_byte (&str, 0) == 255);
3207 _dbus_assert (_dbus_string_get_byte (&str, 1) == 'H');
3208 _dbus_assert (_dbus_string_get_byte (&str, 2) == 'Z');
3209 _dbus_assert (_dbus_string_get_byte (&str, 3) == 'q');
3210 _dbus_assert (_dbus_string_get_byte (&str, 4) == 'l');
3211 _dbus_assert (_dbus_string_get_byte (&str, 5) == 'l');
3212 _dbus_assert (_dbus_string_get_byte (&str, 6) == 'o');
3213 _dbus_assert (_dbus_string_get_byte (&str, 7) == 'W');
3215 _dbus_string_free (&str);
3217 /* Check append/parse int/double */
3219 if (!_dbus_string_init (&str))
3220 _dbus_assert_not_reached ("failed to init string");
3222 if (!_dbus_string_append_int (&str, 27))
3223 _dbus_assert_not_reached ("failed to append int");
3225 i = _dbus_string_get_length (&str);
3227 if (!_dbus_string_parse_int (&str, 0, &v, &end))
3228 _dbus_assert_not_reached ("failed to parse int");
3230 _dbus_assert (v == 27);
3231 _dbus_assert (end == i);
3233 _dbus_string_free (&str);
3235 if (!_dbus_string_init (&str))
3236 _dbus_assert_not_reached ("failed to init string");
3238 if (!_dbus_string_append_double (&str, 50.3))
3239 _dbus_assert_not_reached ("failed to append float");
3241 i = _dbus_string_get_length (&str);
3243 if (!_dbus_string_parse_double (&str, 0, &d, &end))
3244 _dbus_assert_not_reached ("failed to parse float");
3246 _dbus_assert (d > (50.3 - 1e-6) && d < (50.3 + 1e-6));
3247 _dbus_assert (end == i);
3249 _dbus_string_free (&str);
3252 if (!_dbus_string_init (&str))
3253 _dbus_assert_not_reached ("failed to init string");
3255 if (!_dbus_string_append (&str, "Hello"))
3256 _dbus_assert_not_reached ("couldn't append to string");
3258 if (!_dbus_string_find (&str, 0, "He", &i))
3259 _dbus_assert_not_reached ("didn't find 'He'");
3260 _dbus_assert (i == 0);
3262 if (!_dbus_string_find (&str, 0, "Hello", &i))
3263 _dbus_assert_not_reached ("didn't find 'Hello'");
3264 _dbus_assert (i == 0);
3266 if (!_dbus_string_find (&str, 0, "ello", &i))
3267 _dbus_assert_not_reached ("didn't find 'ello'");
3268 _dbus_assert (i == 1);
3270 if (!_dbus_string_find (&str, 0, "lo", &i))
3271 _dbus_assert_not_reached ("didn't find 'lo'");
3272 _dbus_assert (i == 3);
3274 if (!_dbus_string_find (&str, 2, "lo", &i))
3275 _dbus_assert_not_reached ("didn't find 'lo'");
3276 _dbus_assert (i == 3);
3278 if (_dbus_string_find (&str, 4, "lo", &i))
3279 _dbus_assert_not_reached ("did find 'lo'");
3281 if (!_dbus_string_find (&str, 0, "l", &i))
3282 _dbus_assert_not_reached ("didn't find 'l'");
3283 _dbus_assert (i == 2);
3285 if (!_dbus_string_find (&str, 0, "H", &i))
3286 _dbus_assert_not_reached ("didn't find 'H'");
3287 _dbus_assert (i == 0);
3289 if (!_dbus_string_find (&str, 0, "", &i))
3290 _dbus_assert_not_reached ("didn't find ''");
3291 _dbus_assert (i == 0);
3293 if (_dbus_string_find (&str, 0, "Hello!", NULL))
3294 _dbus_assert_not_reached ("Did find 'Hello!'");
3296 if (_dbus_string_find (&str, 0, "Oh, Hello", NULL))
3297 _dbus_assert_not_reached ("Did find 'Oh, Hello'");
3299 if (_dbus_string_find (&str, 0, "ill", NULL))
3300 _dbus_assert_not_reached ("Did find 'ill'");
3302 if (_dbus_string_find (&str, 0, "q", NULL))
3303 _dbus_assert_not_reached ("Did find 'q'");
3305 if (!_dbus_string_find_to (&str, 0, 2, "He", NULL))
3306 _dbus_assert_not_reached ("Didn't find 'He'");
3308 if (_dbus_string_find_to (&str, 0, 2, "Hello", NULL))
3309 _dbus_assert_not_reached ("Did find 'Hello'");
3311 if (!_dbus_string_find_byte_backward (&str, _dbus_string_get_length (&str), 'H', &i))
3312 _dbus_assert_not_reached ("Did not find 'H'");
3313 _dbus_assert (i == 0);
3315 if (!_dbus_string_find_byte_backward (&str, _dbus_string_get_length (&str), 'o', &i))
3316 _dbus_assert_not_reached ("Did not find 'o'");
3317 _dbus_assert (i == _dbus_string_get_length (&str) - 1);
3319 if (_dbus_string_find_byte_backward (&str, _dbus_string_get_length (&str) - 1, 'o', &i))
3320 _dbus_assert_not_reached ("Did find 'o'");
3321 _dbus_assert (i == -1);
3323 if (_dbus_string_find_byte_backward (&str, 1, 'e', &i))
3324 _dbus_assert_not_reached ("Did find 'e'");
3325 _dbus_assert (i == -1);
3327 if (!_dbus_string_find_byte_backward (&str, 2, 'e', &i))
3328 _dbus_assert_not_reached ("Didn't find 'e'");
3329 _dbus_assert (i == 1);
3331 _dbus_string_free (&str);
3333 /* Base 64 and Hex encoding */
3334 test_roundtrips (test_base64_roundtrip);
3335 test_roundtrips (test_hex_roundtrip);
3340 #endif /* DBUS_BUILD_TESTS */