1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-string.c String utility class (internal to D-BUS implementation)
4 * Copyright (C) 2002 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 */
30 * @defgroup DBusString string class
31 * @ingroup DBusInternals
32 * @brief DBusString data structure
34 * Types and functions related to DBusString. DBusString is intended
35 * to be a string class that makes it hard to mess up security issues
36 * (and just in general harder to write buggy code). It should be
37 * used (or extended and then used) rather than the libc stuff in
38 * string.h. The string class is a bit inconvenient at spots because
39 * it handles out-of-memory failures and tries to be extra-robust.
41 * A DBusString has a maximum length set at initialization time; this
42 * can be used to ensure that a buffer doesn't get too big. The
43 * _dbus_string_lengthen() method checks for overflow, and for max
44 * length being exceeded.
46 * Try to avoid conversion to a plain C string, i.e. add methods on
47 * the string object instead, only convert to C string when passing
48 * things out to the public API. In particular, no sprintf, strcpy,
49 * strcat, any of that should be used. The GString feature of
50 * accepting negative numbers for "length of string" is also absent,
51 * because it could keep us from detecting bogus huge lengths. i.e. if
52 * we passed in some bogus huge length it would be taken to mean
53 * "current length of string" instead of "broken crack"
57 * @defgroup DBusStringInternals DBusString implementation details
58 * @ingroup DBusInternals
59 * @brief DBusString implementation details
61 * The guts of DBusString.
67 * @brief Internals of DBusString.
69 * DBusString internals. DBusString is an opaque objects, it must be
70 * used via accessor functions.
74 unsigned char *str; /**< String data, plus nul termination */
75 int len; /**< Length without nul */
76 int allocated; /**< Allocated size of data */
77 int max_length; /**< Max length of this string. */
78 unsigned int constant : 1; /**< String data is not owned by DBusString */
79 unsigned int locked : 1; /**< DBusString has been locked and can't be changed */
80 unsigned int invalid : 1; /**< DBusString is invalid (e.g. already freed) */
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); _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 * Initializes a string. The maximum length may be _DBUS_INT_MAX for
129 * no maximum. The string starts life with zero length.
130 * The string must eventually be freed with _dbus_string_free().
132 * @param str memory to hold the string
133 * @param max_length the maximum size of the string
134 * @returns #TRUE on success
137 _dbus_string_init (DBusString *str,
140 DBusRealString *real;
142 _dbus_assert (str != NULL);
143 _dbus_assert (max_length >= 0);
145 _dbus_assert (sizeof (DBusString) == sizeof (DBusRealString));
147 real = (DBusRealString*) str;
149 /* It's very important not to touch anything
150 * other than real->str if we're going to fail,
151 * since we also use this function to reset
152 * an existing string, e.g. in _dbus_string_steal_data()
155 #define INITIAL_ALLOC 2
157 real->str = dbus_malloc (INITIAL_ALLOC);
158 if (real->str == NULL)
161 real->allocated = INITIAL_ALLOC;
163 real->str[real->len] = '\0';
165 real->max_length = max_length;
166 real->constant = FALSE;
167 real->locked = FALSE;
168 real->invalid = FALSE;
174 * Initializes a constant string. The value parameter is not copied
175 * (should be static), and the string may never be modified.
176 * It is safe but not necessary to call _dbus_string_free()
179 * @param str memory to use for the string
180 * @param value a string to be stored in str (not copied!!!)
183 _dbus_string_init_const (DBusString *str,
186 DBusRealString *real;
188 _dbus_assert (str != NULL);
189 _dbus_assert (value != NULL);
191 real = (DBusRealString*) str;
193 real->str = (char*) value;
194 real->len = strlen (real->str);
195 real->allocated = real->len;
196 real->max_length = real->len;
197 real->constant = TRUE;
198 real->invalid = FALSE;
202 * Frees a string created by _dbus_string_init().
204 * @param str memory where the string is stored.
207 _dbus_string_free (DBusString *str)
209 DBUS_LOCKED_STRING_PREAMBLE (str);
214 dbus_free (real->str);
216 real->invalid = TRUE;
220 * Locks a string such that any attempts to change the string
221 * will result in aborting the program. Also, if the string
222 * is wasting a lot of memory (allocation is larger than what
223 * the string is really using), _dbus_string_lock() will realloc
224 * the string's data to "compact" it.
226 * @param str the string to lock.
229 _dbus_string_lock (DBusString *str)
231 DBUS_LOCKED_STRING_PREAMBLE (str); /* can lock multiple times */
235 /* Try to realloc to avoid excess memory usage, since
236 * we know we won't change the string further
239 if (real->allocated > (real->len + MAX_WASTE))
244 new_allocated = real->len + 1;
246 new_str = dbus_realloc (real->str, new_allocated);
250 real->allocated = new_allocated;
256 * Gets the raw character buffer from the string. The returned buffer
257 * will be nul-terminated, but note that strings may contain binary
258 * data so there may be extra nul characters prior to the termination.
259 * This function should be little-used, extend DBusString or add
260 * stuff to dbus-sysdeps.c instead. It's an error to use this
261 * function on a const string.
263 * @param str the string
264 * @param data_return place to store the returned data
267 _dbus_string_get_data (DBusString *str,
270 DBUS_STRING_PREAMBLE (str);
271 _dbus_assert (data_return != NULL);
273 *data_return = real->str;
277 * Gets the raw character buffer from a const string.
279 * @param str the string
280 * @param data_return location to store returned data
283 _dbus_string_get_const_data (const DBusString *str,
284 const char **data_return)
286 DBUS_CONST_STRING_PREAMBLE (str);
287 _dbus_assert (data_return != NULL);
289 *data_return = real->str;
293 * Gets a sub-portion of the raw character buffer from the
294 * string. The "len" field is required simply for error
295 * checking, to be sure you don't try to use more
296 * string than exists. The nul termination of the
297 * returned buffer remains at the end of the entire
298 * string, not at start + len.
300 * @param str the string
301 * @param data_return location to return the buffer
302 * @param start byte offset to return
303 * @param len length of segment to return
306 _dbus_string_get_data_len (DBusString *str,
311 DBUS_STRING_PREAMBLE (str);
312 _dbus_assert (data_return != NULL);
313 _dbus_assert (start >= 0);
314 _dbus_assert (len >= 0);
315 _dbus_assert ((start + len) <= real->len);
317 *data_return = real->str + start;
321 * const version of _dbus_string_get_data_len().
323 * @param str the string
324 * @param data_return location to return the buffer
325 * @param start byte offset to return
326 * @param len length of segment to return
329 _dbus_string_get_const_data_len (const DBusString *str,
330 const char **data_return,
334 DBUS_CONST_STRING_PREAMBLE (str);
335 _dbus_assert (data_return != NULL);
336 _dbus_assert (start >= 0);
337 _dbus_assert (len >= 0);
338 _dbus_assert ((start + len) <= real->len);
340 *data_return = real->str + start;
344 * Like _dbus_string_get_data(), but removes the
345 * gotten data from the original string. The caller
346 * must free the data returned. This function may
347 * fail due to lack of memory, and return #FALSE.
349 * @param str the string
350 * @param data_return location to return the buffer
351 * @returns #TRUE on success
354 _dbus_string_steal_data (DBusString *str,
357 DBUS_STRING_PREAMBLE (str);
358 _dbus_assert (data_return != NULL);
360 *data_return = real->str;
362 /* reset the string */
363 if (!_dbus_string_init (str, real->max_length))
365 /* hrm, put it back then */
366 real->str = *data_return;
375 * Like _dbus_string_get_data_len(), but removes the gotten data from
376 * the original string. The caller must free the data returned. This
377 * function may fail due to lack of memory, and return #FALSE.
378 * The returned string is nul-terminated and has length len.
380 * @param str the string
381 * @param data_return location to return the buffer
382 * @param start the start of segment to steal
383 * @param len the length of segment to steal
384 * @returns #TRUE on success
387 _dbus_string_steal_data_len (DBusString *str,
394 DBUS_STRING_PREAMBLE (str);
395 _dbus_assert (data_return != NULL);
396 _dbus_assert (start >= 0);
397 _dbus_assert (len >= 0);
398 _dbus_assert ((start + len) <= real->len);
400 if (!_dbus_string_init (&dest, real->max_length))
403 if (!_dbus_string_move_len (str, start, len, &dest, 0))
405 _dbus_string_free (&dest);
409 if (!_dbus_string_steal_data (&dest, data_return))
411 _dbus_string_free (&dest);
415 _dbus_string_free (&dest);
420 * Gets the length of a string (not including nul termination).
422 * @returns the length.
425 _dbus_string_get_length (const DBusString *str)
427 DBUS_CONST_STRING_PREAMBLE (str);
433 set_length (DBusRealString *real,
436 /* Note, we are setting the length without nul termination */
438 /* exceeding max length is the same as failure to allocate memory */
439 if (new_length > real->max_length)
442 while (new_length >= real->allocated)
447 new_allocated = 2 + real->allocated * 2;
448 if (new_allocated < real->allocated)
449 return FALSE; /* overflow */
451 new_str = dbus_realloc (real->str, new_allocated);
456 real->allocated = new_allocated;
459 real->len = new_length;
460 real->str[real->len] = '\0';
466 * Makes a string longer by the given number of bytes. Checks whether
467 * adding additional_length to the current length would overflow an
468 * integer, and checks for exceeding a string's max length.
469 * The new bytes are not initialized, other than nul-terminating
470 * the end of the string. The uninitialized bytes may contain
471 * unexpected nul bytes or other junk.
473 * @param str a string
474 * @param additional_length length to add to the string.
475 * @returns #TRUE on success.
478 _dbus_string_lengthen (DBusString *str,
479 int additional_length)
481 DBUS_STRING_PREAMBLE (str);
482 _dbus_assert (additional_length >= 0);
484 if ((real->len + additional_length) < real->len)
485 return FALSE; /* overflow */
487 return set_length (real,
488 real->len + additional_length);
492 * Makes a string shorter by the given number of bytes.
494 * @param str a string
495 * @param length_to_remove length to remove from the string.
498 _dbus_string_shorten (DBusString *str,
499 int length_to_remove)
501 DBUS_STRING_PREAMBLE (str);
502 _dbus_assert (length_to_remove >= 0);
503 _dbus_assert (length_to_remove <= real->len);
506 real->len - length_to_remove);
510 * Sets the length of a string. Can be used to truncate or lengthen
511 * the string. If the string is lengthened, the function may fail and
512 * return #FALSE. Newly-added bytes are not initialized, as with
513 * _dbus_string_lengthen().
515 * @param str a string
516 * @param length new length of the string.
517 * @returns #FALSE on failure.
520 _dbus_string_set_length (DBusString *str,
523 DBUS_STRING_PREAMBLE (str);
524 _dbus_assert (length >= 0);
526 return set_length (real, length);
530 * Align the length of a string to a specific alignment (typically 4 or 8)
531 * by appending nul bytes to the string.
533 * @param str a string
534 * @param alignment the alignment
535 * @returns #FALSE if no memory
538 _dbus_string_align_length (DBusString *str,
543 DBUS_STRING_PREAMBLE (str);
544 _dbus_assert (alignment >= 1);
545 _dbus_assert (alignment <= 16); /* arbitrary */
547 new_len = _DBUS_ALIGN_VALUE (real->len, alignment);
549 delta = new_len - real->len;
550 _dbus_assert (delta >= 0);
555 if (!set_length (real, new_len))
558 memset (real->str + (new_len - delta),
565 append (DBusRealString *real,
572 if (!_dbus_string_lengthen ((DBusString*)real, buffer_len))
575 memcpy (real->str + (real->len - buffer_len),
583 * Appends a nul-terminated C-style string to a DBusString.
585 * @param str the DBusString
586 * @param buffer the nul-terminated characters to append
587 * @returns #FALSE if not enough memory.
590 _dbus_string_append (DBusString *str,
595 DBUS_STRING_PREAMBLE (str);
596 _dbus_assert (buffer != NULL);
598 buffer_len = strlen (buffer);
600 return append (real, buffer, buffer_len);
604 * Appends block of bytes with the given length to a DBusString.
606 * @param str the DBusString
607 * @param buffer the bytes to append
608 * @param len the number of bytes to append
609 * @returns #FALSE if not enough memory.
612 _dbus_string_append_len (DBusString *str,
616 DBUS_STRING_PREAMBLE (str);
617 _dbus_assert (buffer != NULL);
618 _dbus_assert (len >= 0);
620 return append (real, buffer, len);
624 * Appends a single byte to the string, returning #FALSE
625 * if not enough memory.
627 * @param str the string
628 * @param byte the byte to append
629 * @returns #TRUE on success
632 _dbus_string_append_byte (DBusString *str,
635 DBUS_STRING_PREAMBLE (str);
637 if (!set_length (real, real->len + 1))
640 real->str[real->len-1] = byte;
646 * Appends a single Unicode character, encoding the character
649 * @param str the string
650 * @param ch the Unicode character
653 _dbus_string_append_unichar (DBusString *str,
661 DBUS_STRING_PREAMBLE (str);
663 /* this code is from GLib but is pretty standard I think */
677 else if (ch < 0x10000)
682 else if (ch < 0x200000)
687 else if (ch < 0x4000000)
698 if (!set_length (real, real->len + len))
701 out = real->str + (real->len - len);
703 for (i = len - 1; i > 0; --i)
705 out[i] = (ch & 0x3f) | 0x80;
714 delete (DBusRealString *real,
721 memmove (real->str + start, real->str + start + len, real->len - (start + len));
723 real->str[real->len] = '\0';
727 * Deletes a segment of a DBusString with length len starting at
728 * start. (Hint: to clear an entire string, setting length to 0
729 * with _dbus_string_set_length() is easier.)
731 * @param str the DBusString
732 * @param start where to start deleting
733 * @param len the number of bytes to delete
736 _dbus_string_delete (DBusString *str,
740 DBUS_STRING_PREAMBLE (str);
741 _dbus_assert (start >= 0);
742 _dbus_assert (len >= 0);
743 _dbus_assert ((start + len) <= real->len);
745 delete (real, start, len);
750 DBusRealString *dest,
756 if (!set_length (dest, dest->len + len))
759 memmove (dest->str + insert_at + len,
760 dest->str + insert_at,
761 dest->len - len - insert_at);
767 copy (DBusRealString *source,
770 DBusRealString *dest,
773 if (!open_gap (len, dest, insert_at))
776 memcpy (dest->str + insert_at,
784 * Checks assertions for two strings we're copying a segment between,
785 * and declares real_source/real_dest variables.
787 * @param source the source string
788 * @param start the starting offset
789 * @param dest the dest string
790 * @param insert_at where the copied segment is inserted
792 #define DBUS_STRING_COPY_PREAMBLE(source, start, dest, insert_at) \
793 DBusRealString *real_source = (DBusRealString*) source; \
794 DBusRealString *real_dest = (DBusRealString*) dest; \
795 _dbus_assert ((source) != (dest)); \
796 DBUS_GENERIC_STRING_PREAMBLE (real_source); \
797 DBUS_GENERIC_STRING_PREAMBLE (real_dest); \
798 _dbus_assert (!real_source->constant); \
799 _dbus_assert (!real_source->locked); \
800 _dbus_assert (!real_dest->constant); \
801 _dbus_assert (!real_dest->locked); \
802 _dbus_assert ((start) >= 0); \
803 _dbus_assert ((start) <= real_source->len); \
804 _dbus_assert ((insert_at) >= 0); \
805 _dbus_assert ((insert_at) <= real_dest->len)
808 * Moves the end of one string into another string. Both strings
809 * must be initialized, valid strings.
811 * @param source the source string
812 * @param start where to chop off the source string
813 * @param dest the destination string
814 * @param insert_at where to move the chopped-off part of source string
815 * @returns #FALSE if not enough memory
818 _dbus_string_move (DBusString *source,
823 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
825 if (!copy (real_source, start,
826 real_source->len - start,
831 delete (real_source, start,
832 real_source->len - start);
838 * Like _dbus_string_move(), but does not delete the section
839 * of the source string that's copied to the dest string.
841 * @param source the source string
842 * @param start where to start copying the source string
843 * @param dest the destination string
844 * @param insert_at where to place the copied part of source string
845 * @returns #FALSE if not enough memory
848 _dbus_string_copy (const DBusString *source,
853 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
855 return copy (real_source, start,
856 real_source->len - start,
862 * Like _dbus_string_move(), but can move a segment from
863 * the middle of the source string.
865 * @param source the source string
866 * @param start first byte of source string to move
867 * @param len length of segment to move
868 * @param dest the destination string
869 * @param insert_at where to move the bytes from the source string
870 * @returns #FALSE if not enough memory
873 _dbus_string_move_len (DBusString *source,
880 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
881 _dbus_assert (len >= 0);
882 _dbus_assert ((start + len) <= real_source->len);
884 if (!copy (real_source, start, len,
889 delete (real_source, start,
890 real_source->len - start);
896 * Like _dbus_string_copy(), but can copy a segment from the middle of
899 * @param source the source string
900 * @param start where to start copying the source string
901 * @param len length of segment to copy
902 * @param dest the destination string
903 * @param insert_at where to place the copied segment of source string
904 * @returns #FALSE if not enough memory
907 _dbus_string_copy_len (const DBusString *source,
913 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
914 _dbus_assert (len >= 0);
915 _dbus_assert ((start + len) <= real_source->len);
917 return copy (real_source, start, len,
922 /* Unicode macros from GLib */
924 /** computes length and mask of a unicode character
925 * @param Char the char
926 * @param Mask the mask variable to assign to
927 * @param Len the length variable to assign to
929 #define UTF8_COMPUTE(Char, Mask, Len) \
935 else if ((Char & 0xe0) == 0xc0) \
940 else if ((Char & 0xf0) == 0xe0) \
945 else if ((Char & 0xf8) == 0xf0) \
950 else if ((Char & 0xfc) == 0xf8) \
955 else if ((Char & 0xfe) == 0xfc) \
964 * computes length of a unicode character in UTF-8
965 * @param Char the char
967 #define UTF8_LENGTH(Char) \
968 ((Char) < 0x80 ? 1 : \
969 ((Char) < 0x800 ? 2 : \
970 ((Char) < 0x10000 ? 3 : \
971 ((Char) < 0x200000 ? 4 : \
972 ((Char) < 0x4000000 ? 5 : 6)))))
975 * Gets a UTF-8 value.
977 * @param Result variable for extracted unicode char.
978 * @param Chars the bytes to decode
979 * @param Count counter variable
980 * @param Mask mask for this char
981 * @param Len length for this char in bytes
983 #define UTF8_GET(Result, Chars, Count, Mask, Len) \
984 (Result) = (Chars)[0] & (Mask); \
985 for ((Count) = 1; (Count) < (Len); ++(Count)) \
987 if (((Chars)[(Count)] & 0xc0) != 0x80) \
993 (Result) |= ((Chars)[(Count)] & 0x3f); \
997 * Check whether a unicode char is in a valid range.
999 * @param Char the character
1001 #define UNICODE_VALID(Char) \
1002 ((Char) < 0x110000 && \
1003 ((Char) < 0xD800 || (Char) >= 0xE000) && \
1004 (Char) != 0xFFFE && (Char) != 0xFFFF)
1007 * Gets a unicode character from a UTF-8 string. Does no validation;
1008 * you must verify that the string is valid UTF-8 in advance and must
1009 * pass in the start of a character.
1011 * @param str the string
1012 * @param start the start of the UTF-8 character.
1013 * @param ch_return location to return the character
1014 * @param end_return location to return the byte index of next character
1015 * @returns #TRUE on success, #FALSE otherwise.
1018 _dbus_string_get_unichar (const DBusString *str,
1020 dbus_unichar_t *ch_return,
1024 dbus_unichar_t result;
1027 DBUS_CONST_STRING_PREAMBLE (str);
1032 *end_return = real->len;
1035 p = real->str + start;
1038 UTF8_COMPUTE (c, mask, len);
1041 UTF8_GET (result, p, i, mask, len);
1043 if (result == (dbus_unichar_t)-1)
1047 *ch_return = result;
1049 *end_return = start + len;
1053 * Finds the given substring in the string,
1054 * returning #TRUE and filling in the byte index
1055 * where the substring was found, if it was found.
1056 * Returns #FALSE if the substring wasn't found.
1057 * Sets *start to the length of the string if the substring
1060 * @param str the string
1061 * @param start where to start looking
1062 * @param substr the substring
1063 * @param found return location for where it was found, or #NULL
1064 * @returns #TRUE if found
1067 _dbus_string_find (const DBusString *str,
1073 DBUS_CONST_STRING_PREAMBLE (str);
1074 _dbus_assert (substr != NULL);
1075 _dbus_assert (start <= real->len);
1077 /* we always "find" an empty string */
1078 if (*substr == '\0')
1086 while (i < real->len)
1088 if (real->str[i] == substr[0])
1092 while (j < real->len)
1094 if (substr[j - i] == '\0')
1096 else if (real->str[j] != substr[j - i])
1102 if (substr[j - i] == '\0')
1120 * Finds a blank (space or tab) in the string. Returns #TRUE
1121 * if found, #FALSE otherwise. If a blank is not found sets
1122 * *found to the length of the string.
1124 * @param str the string
1125 * @param start byte index to start looking
1126 * @param found place to store the location of the first blank
1127 * @returns #TRUE if a blank was found
1130 _dbus_string_find_blank (const DBusString *str,
1135 DBUS_CONST_STRING_PREAMBLE (str);
1136 _dbus_assert (start <= real->len);
1139 while (i < real->len)
1141 if (real->str[i] == ' ' ||
1142 real->str[i] == '\t')
1159 * Skips blanks from start, storing the first non-blank in *end
1161 * @param str the string
1162 * @param start where to start
1163 * @param end where to store the first non-blank byte index
1166 _dbus_string_skip_blank (const DBusString *str,
1171 DBUS_CONST_STRING_PREAMBLE (str);
1172 _dbus_assert (start <= real->len);
1175 while (i < real->len)
1177 if (!(real->str[i] == ' ' ||
1178 real->str[i] == '\t'))
1184 _dbus_assert (i == real->len || !(real->str[i] == ' ' ||
1185 real->str[i] == '\t'));
1192 * Tests two DBusString for equality.
1194 * @param a first string
1195 * @param b second string
1196 * @returns #TRUE if equal
1199 _dbus_string_equal (const DBusString *a,
1200 const DBusString *b)
1202 const unsigned char *ap;
1203 const unsigned char *bp;
1204 const unsigned char *a_end;
1205 const DBusRealString *real_a = (const DBusRealString*) a;
1206 const DBusRealString *real_b = (const DBusRealString*) b;
1207 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1208 DBUS_GENERIC_STRING_PREAMBLE (real_b);
1210 if (real_a->len != real_b->len)
1215 a_end = real_a->str + real_a->len;
1229 * Checks whether a string is equal to a C string.
1231 * @param a the string
1232 * @param c_str the C string
1233 * @returns #TRUE if equal
1236 _dbus_string_equal_c_str (const DBusString *a,
1239 const unsigned char *ap;
1240 const unsigned char *bp;
1241 const unsigned char *a_end;
1242 const DBusRealString *real_a = (const DBusRealString*) a;
1243 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1246 bp = (const unsigned char*) c_str;
1247 a_end = real_a->str + real_a->len;
1248 while (ap != a_end && *bp)
1257 if (*ap && *bp == '\0')
1259 else if (ap == a_end && *bp)
1265 static const signed char base64_table[] = {
1332 /** The minimum char that's a valid char in Base64-encoded text */
1333 #define UNBASE64_MIN_CHAR (43)
1334 /** The maximum char that's a valid char in Base64-encoded text */
1335 #define UNBASE64_MAX_CHAR (122)
1336 /** Must subtract this from a char's integer value before offsetting
1337 * into unbase64_table
1339 #define UNBASE64_TABLE_OFFSET UNBASE64_MIN_CHAR
1340 static const signed char unbase64_table[] = {
1424 * Encodes a string using Base64, as documented in RFC 2045.
1426 * @param source the string to encode
1427 * @param start byte index to start encoding
1428 * @param dest string where encoded data should be placed
1429 * @param insert_at where to place encoded data
1430 * @returns #TRUE if encoding was successful, #FALSE if no memory etc.
1433 _dbus_string_base64_encode (const DBusString *source,
1440 const unsigned char *s;
1442 const unsigned char *triplet_end;
1443 const unsigned char *final_end;
1444 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1445 _dbus_assert (source != dest);
1447 /* For each 24 bits (3 bytes) of input, we have 4 chars of
1450 source_len = real_source->len - start;
1451 dest_len = (source_len / 3) * 4;
1452 if (source_len % 3 != 0)
1455 if (source_len == 0)
1458 if (!open_gap (dest_len, real_dest, insert_at))
1461 d = real_dest->str + insert_at;
1462 s = real_source->str + start;
1463 final_end = real_source->str + (start + source_len);
1464 triplet_end = final_end - (source_len % 3);
1465 _dbus_assert (triplet_end <= final_end);
1466 _dbus_assert ((final_end - triplet_end) < 3);
1468 #define ENCODE_64(v) (base64_table[ (unsigned char) (v) ])
1469 #define SIX_BITS_MASK (0x3f)
1470 _dbus_assert (SIX_BITS_MASK < _DBUS_N_ELEMENTS (base64_table));
1472 while (s != triplet_end)
1474 unsigned int triplet;
1476 triplet = s[0] | (s[1] << 8) | (s[2] << 16);
1478 /* Encode each 6 bits */
1480 *d++ = ENCODE_64 (triplet >> 18);
1481 *d++ = ENCODE_64 ((triplet >> 12) & SIX_BITS_MASK);
1482 *d++ = ENCODE_64 ((triplet >> 6) & SIX_BITS_MASK);
1483 *d++ = ENCODE_64 (triplet & SIX_BITS_MASK);
1488 switch (final_end - triplet_end)
1492 unsigned int doublet;
1494 doublet = s[0] | (s[1] << 8);
1496 *d++ = ENCODE_64 (doublet >> 12);
1497 *d++ = ENCODE_64 ((doublet >> 6) & SIX_BITS_MASK);
1498 *d++ = ENCODE_64 (doublet & SIX_BITS_MASK);
1504 unsigned int singlet;
1508 *d++ = ENCODE_64 ((singlet >> 6) & SIX_BITS_MASK);
1509 *d++ = ENCODE_64 (singlet & SIX_BITS_MASK);
1518 _dbus_assert (d == (real_dest->str + (insert_at + dest_len)));
1525 * Decodes a string from Base64, as documented in RFC 2045.
1527 * @param source the string to decode
1528 * @param start byte index to start decode
1529 * @param dest string where decoded data should be placed
1530 * @param insert_at where to place decoded data
1531 * @returns #TRUE if decoding was successful, #FALSE if no memory etc.
1534 _dbus_string_base64_decode (const DBusString *source,
1543 unsigned int triplet = 0;
1546 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1547 _dbus_assert (source != dest);
1549 source_len = real_source->len - start;
1550 s = real_source->str + start;
1551 end = real_source->str + source_len;
1553 if (source_len == 0)
1556 if (!_dbus_string_init (&result, _DBUS_INT_MAX))
1563 /* The idea is to just skip anything that isn't
1564 * a base64 char - it's allowed to have whitespace,
1565 * newlines, etc. in here. We also ignore trailing
1566 * base64 chars, though that's suspicious.
1569 if (*s >= UNBASE64_MIN_CHAR &&
1570 *s <= UNBASE64_MAX_CHAR)
1574 /* '=' is padding, doesn't represent additional data
1575 * but does increment our count.
1584 val = unbase64_table[(*s) - UNBASE64_TABLE_OFFSET];
1589 triplet |= (unsigned int) val;
1594 if (sextet_count == 4)
1596 /* no pad = 3 bytes, 1 pad = 2 bytes, 2 pad = 1 byte */
1598 _dbus_string_append_byte (&result,
1602 _dbus_string_append_byte (&result,
1603 (triplet >> 8) & 0xff);
1606 _dbus_string_append_byte (&result,
1618 if (!_dbus_string_move (&result, 0, dest, insert_at))
1620 _dbus_string_free (&result);
1624 _dbus_string_free (&result);
1630 * Checks that the given range of the string
1631 * is valid ASCII. If the given range is not contained
1632 * in the string, returns #FALSE.
1634 * @param str the string
1635 * @param start first byte index to check
1636 * @param len number of bytes to check
1637 * @returns #TRUE if the byte range exists and is all valid ASCII
1640 _dbus_string_validate_ascii (const DBusString *str,
1644 const unsigned char *s;
1645 const unsigned char *end;
1646 DBUS_CONST_STRING_PREAMBLE (str);
1647 _dbus_assert (start >= 0);
1648 _dbus_assert (len >= 0);
1650 if ((start + len) > real->len)
1653 s = real->str + start;
1658 ((*s & ~0x7f) != 0))
1669 #ifdef DBUS_BUILD_TESTS
1670 #include "dbus-test.h"
1674 test_max_len (DBusString *str,
1679 if (!_dbus_string_set_length (str, max_len - 1))
1680 _dbus_assert_not_reached ("setting len to one less than max should have worked");
1683 if (!_dbus_string_set_length (str, max_len))
1684 _dbus_assert_not_reached ("setting len to max len should have worked");
1686 if (_dbus_string_set_length (str, max_len + 1))
1687 _dbus_assert_not_reached ("setting len to one more than max len should not have worked");
1689 if (!_dbus_string_set_length (str, 0))
1690 _dbus_assert_not_reached ("setting len to zero should have worked");
1694 test_base64_roundtrip (const unsigned char *data,
1702 len = strlen (data);
1704 if (!_dbus_string_init (&orig, _DBUS_INT_MAX))
1705 _dbus_assert_not_reached ("could not init string");
1707 if (!_dbus_string_init (&encoded, _DBUS_INT_MAX))
1708 _dbus_assert_not_reached ("could not init string");
1710 if (!_dbus_string_init (&decoded, _DBUS_INT_MAX))
1711 _dbus_assert_not_reached ("could not init string");
1713 if (!_dbus_string_append_len (&orig, data, len))
1714 _dbus_assert_not_reached ("couldn't append orig data");
1716 if (!_dbus_string_base64_encode (&orig, 0, &encoded, 0))
1717 _dbus_assert_not_reached ("could not encode");
1719 if (!_dbus_string_base64_decode (&encoded, 0, &decoded, 0))
1720 _dbus_assert_not_reached ("could not decode");
1722 if (!_dbus_string_equal (&orig, &decoded))
1726 printf ("Original string %d bytes encoded %d bytes decoded %d bytes\n",
1727 _dbus_string_get_length (&orig),
1728 _dbus_string_get_length (&encoded),
1729 _dbus_string_get_length (&decoded));
1730 printf ("Original: %s\n", data);
1731 _dbus_string_get_const_data (&decoded, &s);
1732 printf ("Decoded: %s\n", s);
1733 _dbus_assert_not_reached ("original string not the same as string decoded from base64");
1736 _dbus_string_free (&orig);
1737 _dbus_string_free (&encoded);
1738 _dbus_string_free (&decoded);
1742 * @ingroup DBusStringInternals
1743 * Unit test for DBusString.
1745 * @todo Need to write tests for _dbus_string_copy() and
1746 * _dbus_string_move() moving to/from each of start/middle/end of a
1749 * @returns #TRUE on success.
1752 _dbus_string_test (void)
1759 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 };
1764 while (i < _DBUS_N_ELEMENTS (lens))
1766 if (!_dbus_string_init (&str, lens[i]))
1767 _dbus_assert_not_reached ("failed to init string");
1769 test_max_len (&str, lens[i]);
1770 _dbus_string_free (&str);
1775 /* Test shortening and setting length */
1777 while (i < _DBUS_N_ELEMENTS (lens))
1781 if (!_dbus_string_init (&str, lens[i]))
1782 _dbus_assert_not_reached ("failed to init string");
1784 if (!_dbus_string_set_length (&str, lens[i]))
1785 _dbus_assert_not_reached ("failed to set string length");
1790 _dbus_assert (_dbus_string_get_length (&str) == j);
1793 _dbus_string_shorten (&str, 1);
1794 _dbus_assert (_dbus_string_get_length (&str) == (j - 1));
1799 _dbus_string_free (&str);
1804 /* Test appending data */
1805 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
1806 _dbus_assert_not_reached ("failed to init string");
1811 if (!_dbus_string_append (&str, "a"))
1812 _dbus_assert_not_reached ("failed to append string to string\n");
1814 _dbus_assert (_dbus_string_get_length (&str) == i * 2 + 1);
1816 if (!_dbus_string_append_byte (&str, 'b'))
1817 _dbus_assert_not_reached ("failed to append byte to string\n");
1819 _dbus_assert (_dbus_string_get_length (&str) == i * 2 + 2);
1824 _dbus_string_free (&str);
1826 /* Check steal_data */
1828 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
1829 _dbus_assert_not_reached ("failed to init string");
1831 if (!_dbus_string_append (&str, "Hello World"))
1832 _dbus_assert_not_reached ("could not append to string");
1834 i = _dbus_string_get_length (&str);
1836 if (!_dbus_string_steal_data (&str, &s))
1837 _dbus_assert_not_reached ("failed to steal data");
1839 _dbus_assert (_dbus_string_get_length (&str) == 0);
1840 _dbus_assert (((int)strlen (s)) == i);
1846 if (!_dbus_string_append (&str, "Hello World"))
1847 _dbus_assert_not_reached ("could not append to string");
1849 i = _dbus_string_get_length (&str);
1851 if (!_dbus_string_init (&other, _DBUS_INT_MAX))
1852 _dbus_assert_not_reached ("could not init string");
1854 if (!_dbus_string_move (&str, 0, &other, 0))
1855 _dbus_assert_not_reached ("could not move");
1857 _dbus_assert (_dbus_string_get_length (&str) == 0);
1858 _dbus_assert (_dbus_string_get_length (&other) == i);
1860 if (!_dbus_string_append (&str, "Hello World"))
1861 _dbus_assert_not_reached ("could not append to string");
1863 if (!_dbus_string_move (&str, 0, &other, _dbus_string_get_length (&other)))
1864 _dbus_assert_not_reached ("could not move");
1866 _dbus_assert (_dbus_string_get_length (&str) == 0);
1867 _dbus_assert (_dbus_string_get_length (&other) == i * 2);
1869 if (!_dbus_string_append (&str, "Hello World"))
1870 _dbus_assert_not_reached ("could not append to string");
1872 if (!_dbus_string_move (&str, 0, &other, _dbus_string_get_length (&other) / 2))
1873 _dbus_assert_not_reached ("could not move");
1875 _dbus_assert (_dbus_string_get_length (&str) == 0);
1876 _dbus_assert (_dbus_string_get_length (&other) == i * 3);
1878 _dbus_string_free (&other);
1882 if (!_dbus_string_append (&str, "Hello World"))
1883 _dbus_assert_not_reached ("could not append to string");
1885 i = _dbus_string_get_length (&str);
1887 if (!_dbus_string_init (&other, _DBUS_INT_MAX))
1888 _dbus_assert_not_reached ("could not init string");
1890 if (!_dbus_string_copy (&str, 0, &other, 0))
1891 _dbus_assert_not_reached ("could not copy");
1893 _dbus_assert (_dbus_string_get_length (&str) == i);
1894 _dbus_assert (_dbus_string_get_length (&other) == i);
1896 if (!_dbus_string_copy (&str, 0, &other, _dbus_string_get_length (&other)))
1897 _dbus_assert_not_reached ("could not copy");
1899 _dbus_assert (_dbus_string_get_length (&str) == i);
1900 _dbus_assert (_dbus_string_get_length (&other) == i * 2);
1901 _dbus_assert (_dbus_string_equal_c_str (&other,
1902 "Hello WorldHello World"));
1904 if (!_dbus_string_copy (&str, 0, &other, _dbus_string_get_length (&other) / 2))
1905 _dbus_assert_not_reached ("could not copy");
1907 _dbus_assert (_dbus_string_get_length (&str) == i);
1908 _dbus_assert (_dbus_string_get_length (&other) == i * 3);
1909 _dbus_assert (_dbus_string_equal_c_str (&other,
1910 "Hello WorldHello WorldHello World"));
1912 _dbus_string_free (&str);
1913 _dbus_string_free (&other);
1915 /* Check append/get unichar */
1917 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
1918 _dbus_assert_not_reached ("failed to init string");
1921 if (!_dbus_string_append_unichar (&str, 0xfffc))
1922 _dbus_assert_not_reached ("failed to append unichar");
1924 _dbus_string_get_unichar (&str, 0, &ch, &i);
1926 _dbus_assert (ch == 0xfffc);
1927 _dbus_assert (i == _dbus_string_get_length (&str));
1929 _dbus_string_free (&str);
1931 /* Check append/parse int/double */
1933 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
1934 _dbus_assert_not_reached ("failed to init string");
1936 if (!_dbus_string_append_int (&str, 27))
1937 _dbus_assert_not_reached ("failed to append int");
1939 i = _dbus_string_get_length (&str);
1941 if (!_dbus_string_parse_int (&str, 0, &v, &end))
1942 _dbus_assert_not_reached ("failed to parse int");
1944 _dbus_assert (v == 27);
1945 _dbus_assert (end == i);
1947 _dbus_string_free (&str);
1949 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
1950 _dbus_assert_not_reached ("failed to init string");
1952 if (!_dbus_string_append_double (&str, 50.3))
1953 _dbus_assert_not_reached ("failed to append float");
1955 i = _dbus_string_get_length (&str);
1957 if (!_dbus_string_parse_double (&str, 0, &d, &end))
1958 _dbus_assert_not_reached ("failed to parse float");
1960 _dbus_assert (d > (50.3 - 1e-6) && d < (50.3 + 1e-6));
1961 _dbus_assert (end == i);
1963 _dbus_string_free (&str);
1966 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
1967 _dbus_assert_not_reached ("failed to init string");
1969 if (!_dbus_string_append (&str, "Hello"))
1970 _dbus_assert_not_reached ("couldn't append to string");
1972 if (!_dbus_string_find (&str, 0, "He", &i))
1973 _dbus_assert_not_reached ("didn't find 'He'");
1974 _dbus_assert (i == 0);
1976 if (!_dbus_string_find (&str, 0, "ello", &i))
1977 _dbus_assert_not_reached ("didn't find 'ello'");
1978 _dbus_assert (i == 1);
1980 if (!_dbus_string_find (&str, 0, "lo", &i))
1981 _dbus_assert_not_reached ("didn't find 'lo'");
1982 _dbus_assert (i == 3);
1984 if (!_dbus_string_find (&str, 2, "lo", &i))
1985 _dbus_assert_not_reached ("didn't find 'lo'");
1986 _dbus_assert (i == 3);
1988 if (_dbus_string_find (&str, 4, "lo", &i))
1989 _dbus_assert_not_reached ("did find 'lo'");
1991 if (!_dbus_string_find (&str, 0, "l", &i))
1992 _dbus_assert_not_reached ("didn't find 'l'");
1993 _dbus_assert (i == 2);
1995 if (!_dbus_string_find (&str, 0, "H", &i))
1996 _dbus_assert_not_reached ("didn't find 'H'");
1997 _dbus_assert (i == 0);
1999 if (!_dbus_string_find (&str, 0, "", &i))
2000 _dbus_assert_not_reached ("didn't find ''");
2001 _dbus_assert (i == 0);
2003 if (_dbus_string_find (&str, 0, "Hello!", NULL))
2004 _dbus_assert_not_reached ("Did find 'Hello!'");
2006 if (_dbus_string_find (&str, 0, "Oh, Hello", NULL))
2007 _dbus_assert_not_reached ("Did find 'Oh, Hello'");
2009 if (_dbus_string_find (&str, 0, "ill", NULL))
2010 _dbus_assert_not_reached ("Did find 'ill'");
2012 if (_dbus_string_find (&str, 0, "q", NULL))
2013 _dbus_assert_not_reached ("Did find 'q'");
2015 _dbus_string_free (&str);
2018 test_base64_roundtrip ("Hello this is a string\n", -1);
2019 test_base64_roundtrip ("Hello this is a string\n1", -1);
2020 test_base64_roundtrip ("Hello this is a string\n12", -1);
2021 test_base64_roundtrip ("Hello this is a string\n123", -1);
2022 test_base64_roundtrip ("Hello this is a string\n1234", -1);
2023 test_base64_roundtrip ("Hello this is a string\n12345", -1);
2024 test_base64_roundtrip ("", 0);
2025 test_base64_roundtrip ("1", 1);
2026 test_base64_roundtrip ("12", 2);
2027 test_base64_roundtrip ("123", 3);
2028 test_base64_roundtrip ("1234", 4);
2029 test_base64_roundtrip ("12345", 5);
2030 test_base64_roundtrip ("", 1);
2031 test_base64_roundtrip ("1", 2);
2032 test_base64_roundtrip ("12", 3);
2033 test_base64_roundtrip ("123", 4);
2034 test_base64_roundtrip ("1234", 5);
2035 test_base64_roundtrip ("12345", 6);
2037 unsigned char buf[512];
2039 while (i < _DBUS_N_ELEMENTS (buf))
2045 while (i < _DBUS_N_ELEMENTS (buf))
2047 test_base64_roundtrip (buf, i);
2055 #endif /* DBUS_BUILD_TESTS */