2 Unix SMB/CIFS implementation.
3 Samba utility functions
5 Copyright (C) Andrew Tridgell 1992-2001
6 Copyright (C) Simo Sorce 2001-2002
7 Copyright (C) Martin Pool 2003
8 Copyright (C) James Peach 2005
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #include "lib/ldb/include/ldb.h"
29 #include "system/iconv.h"
33 * @brief String utilities.
38 Trim the specified elements off the front and back of a string.
40 _PUBLIC_ BOOL trim_string(char *s,const char *front,const char *back)
47 /* Ignore null or empty strings. */
48 if (!s || (s[0] == '\0'))
51 front_len = front? strlen(front) : 0;
52 back_len = back? strlen(back) : 0;
57 while (len && strncmp(s, front, front_len)==0) {
58 /* Must use memmove here as src & dest can
59 * easily overlap. Found by valgrind. JRA. */
60 memmove(s, s+front_len, (len-front_len)+1);
67 while ((len >= back_len) && strncmp(s+len-back_len,back,back_len)==0) {
77 Find the number of 'c' chars in a string
79 _PUBLIC_ size_t count_chars(const char *s, char c)
94 Safe string copy into a known length string. maxlength does not
95 include the terminating zero.
97 _PUBLIC_ char *safe_strcpy(char *dest,const char *src, size_t maxlength)
102 DEBUG(0,("ERROR: NULL dest in safe_strcpy\n"));
107 /* We intentionally write out at the extremity of the destination
108 * string. If the destination is too short (e.g. pstrcpy into mallocd
109 * or fstring) then this should cause an error under a memory
111 dest[maxlength] = '\0';
112 if (PTR_DIFF(&len, dest) > 0) { /* check if destination is on the stack, ok if so */
113 log_suspicious_usage("safe_strcpy", src);
124 if (len > maxlength) {
125 DEBUG(0,("ERROR: string overflow by %u (%u - %u) in safe_strcpy [%.50s]\n",
126 (uint_t)(len-maxlength), (unsigned)len, (unsigned)maxlength, src));
130 memmove(dest, src, len);
136 Safe string cat into a string. maxlength does not
137 include the terminating zero.
139 _PUBLIC_ char *safe_strcat(char *dest, const char *src, size_t maxlength)
141 size_t src_len, dest_len;
144 DEBUG(0,("ERROR: NULL dest in safe_strcat\n"));
152 if (PTR_DIFF(&src_len, dest) > 0) { /* check if destination is on the stack, ok if so */
153 log_suspicious_usage("safe_strcat", src);
156 src_len = strlen(src);
157 dest_len = strlen(dest);
159 if (src_len + dest_len > maxlength) {
160 DEBUG(0,("ERROR: string overflow by %d in safe_strcat [%.50s]\n",
161 (int)(src_len + dest_len - maxlength), src));
162 if (maxlength > dest_len) {
163 memcpy(&dest[dest_len], src, maxlength - dest_len);
169 memcpy(&dest[dest_len], src, src_len);
170 dest[dest_len + src_len] = 0;
175 Routine to get hex characters and turn them into a 16 byte array.
176 the array can be variable length, and any non-hex-numeric
177 characters are skipped. "0xnn" or "0Xnn" is specially catered
180 valid examples: "0A5D15"; "0x15, 0x49, 0xa2"; "59\ta9\te3\n"
184 _PUBLIC_ size_t strhex_to_str(char *p, size_t len, const char *strhex)
187 size_t num_chars = 0;
188 uint8_t lonybble, hinybble;
189 const char *hexchars = "0123456789ABCDEF";
190 char *p1 = NULL, *p2 = NULL;
192 for (i = 0; i < len && strhex[i] != 0; i++) {
193 if (strncasecmp(hexchars, "0x", 2) == 0) {
194 i++; /* skip two chars */
198 if (!(p1 = strchr(hexchars, toupper((unsigned char)strhex[i]))))
201 i++; /* next hex digit */
203 if (!(p2 = strchr(hexchars, toupper((unsigned char)strhex[i]))))
206 /* get the two nybbles */
207 hinybble = PTR_DIFF(p1, hexchars);
208 lonybble = PTR_DIFF(p2, hexchars);
210 p[num_chars] = (hinybble << 4) | lonybble;
220 * Parse a hex string and return a data blob.
222 _PUBLIC_ DATA_BLOB strhex_to_data_blob(const char *strhex)
224 DATA_BLOB ret_blob = data_blob(NULL, strlen(strhex)/2+1);
226 ret_blob.length = strhex_to_str((char *)ret_blob.data,
235 * Routine to print a buffer as HEX digits, into an allocated string.
237 _PUBLIC_ void hex_encode(const unsigned char *buff_in, size_t len, char **out_hex_buffer)
242 *out_hex_buffer = smb_xmalloc((len*2)+1);
243 hex_buffer = *out_hex_buffer;
245 for (i = 0; i < len; i++)
246 slprintf(&hex_buffer[i*2], 3, "%02X", buff_in[i]);
250 Check if a string is part of a list.
252 _PUBLIC_ BOOL in_list(const char *s, const char *list, BOOL casesensitive)
260 while (next_token(&p,tok,LIST_SEP,sizeof(tok))) {
262 if (strcmp(tok,s) == 0)
265 if (strcasecmp_m(tok,s) == 0)
273 Set a string value, allocing the space for the string
275 static BOOL string_init(char **dest,const char *src)
279 (*dest) = strdup(src);
280 if ((*dest) == NULL) {
281 DEBUG(0,("Out of memory in string_init\n"));
290 _PUBLIC_ void string_free(char **s)
292 if (s) SAFE_FREE(*s);
296 Set a string value, deallocating any existing space, and allocing the space
299 _PUBLIC_ BOOL string_set(char **dest, const char *src)
302 return string_init(dest,src);
306 Substitute a string for a pattern in another string. Make sure there is
309 This routine looks for pattern in s and replaces it with
310 insert. It may do multiple replacements.
312 Any of " ; ' $ or ` in the insert string are replaced with _
313 if len==0 then the string cannot be extended. This is different from the old
314 use of len==0 which was for no length checks to be done.
317 _PUBLIC_ void string_sub(char *s,const char *pattern, const char *insert, size_t len)
322 if (!insert || !pattern || !*pattern || !s)
325 ls = (ssize_t)strlen(s);
326 lp = (ssize_t)strlen(pattern);
327 li = (ssize_t)strlen(insert);
330 len = ls + 1; /* len is number of *bytes* */
332 while (lp <= ls && (p = strstr(s,pattern))) {
333 if (ls + (li-lp) >= len) {
334 DEBUG(0,("ERROR: string overflow by %d in string_sub(%.50s, %d)\n",
335 (int)(ls + (li-lp) - len),
340 memmove(p+li,p+lp,strlen(p+lp)+1);
365 Similar to string_sub() but allows for any character to be substituted.
367 if len==0 then the string cannot be extended. This is different from the old
368 use of len==0 which was for no length checks to be done.
371 _PUBLIC_ void all_string_sub(char *s,const char *pattern,const char *insert, size_t len)
376 if (!insert || !pattern || !s)
379 ls = (ssize_t)strlen(s);
380 lp = (ssize_t)strlen(pattern);
381 li = (ssize_t)strlen(insert);
387 len = ls + 1; /* len is number of *bytes* */
389 while (lp <= ls && (p = strstr(s,pattern))) {
390 if (ls + (li-lp) >= len) {
391 DEBUG(0,("ERROR: string overflow by %d in all_string_sub(%.50s, %d)\n",
392 (int)(ls + (li-lp) - len),
397 memmove(p+li,p+lp,strlen(p+lp)+1);
399 memcpy(p, insert, li);
408 Unescape a URL encoded string, in place.
411 _PUBLIC_ void rfc1738_unescape(char *buf)
415 while ((p=strchr(p,'+')))
420 while (p && *p && (p=strchr(p,'%'))) {
424 if (c1 >= '0' && c1 <= '9')
426 else if (c1 >= 'A' && c1 <= 'F')
428 else if (c1 >= 'a' && c1 <= 'f')
430 else {p++; continue;}
432 if (c2 >= '0' && c2 <= '9')
434 else if (c2 >= 'A' && c2 <= 'F')
436 else if (c2 >= 'a' && c2 <= 'f')
438 else {p++; continue;}
442 memmove(p+1, p+3, strlen(p+3)+1);
448 size_t valgrind_strlen(const char *s)
451 for(count = 0; *s++; count++)
459 format a string into length-prefixed dotted domain format, as used in NBT
460 and in some ADS structures
462 _PUBLIC_ const char *str_format_nbt_domain(TALLOC_CTX *mem_ctx, const char *s)
467 return talloc_strdup(mem_ctx, "");
469 ret = talloc_size(mem_ctx, strlen(s)+2);
474 memcpy(ret+1, s, strlen(s)+1);
477 for (i=0;ret[i];i++) {
479 char *p = strchr(ret+i+1, '.');
481 ret[i] = p-(ret+i+1);
483 ret[i] = strlen(ret+i+1);
492 * Add a string to an array of strings.
494 * num should be a pointer to an integer that holds the current
495 * number of elements in strings. It will be updated by this function.
497 _PUBLIC_ BOOL add_string_to_array(TALLOC_CTX *mem_ctx,
498 const char *str, const char ***strings, int *num)
500 char *dup_str = talloc_strdup(mem_ctx, str);
502 *strings = talloc_realloc(mem_ctx,
504 const char *, ((*num)+1));
506 if ((*strings == NULL) || (dup_str == NULL))
509 (*strings)[*num] = dup_str;
518 varient of strcmp() that handles NULL ptrs
520 _PUBLIC_ int strcmp_safe(const char *s1, const char *s2)
525 if (s1 == NULL || s2 == NULL) {
528 return strcmp(s1, s2);
533 return the number of bytes occupied by a buffer in ASCII format
534 the result includes the null termination
537 _PUBLIC_ size_t ascii_len_n(const char *src, size_t n)
541 len = strnlen(src, n);
551 Return a string representing a CIFS attribute for a file.
553 _PUBLIC_ char *attrib_string(TALLOC_CTX *mem_ctx, uint32_t attrib)
560 {'V', FILE_ATTRIBUTE_VOLUME},
561 {'D', FILE_ATTRIBUTE_DIRECTORY},
562 {'A', FILE_ATTRIBUTE_ARCHIVE},
563 {'H', FILE_ATTRIBUTE_HIDDEN},
564 {'S', FILE_ATTRIBUTE_SYSTEM},
565 {'N', FILE_ATTRIBUTE_NORMAL},
566 {'R', FILE_ATTRIBUTE_READONLY},
567 {'d', FILE_ATTRIBUTE_DEVICE},
568 {'t', FILE_ATTRIBUTE_TEMPORARY},
569 {'s', FILE_ATTRIBUTE_SPARSE},
570 {'r', FILE_ATTRIBUTE_REPARSE_POINT},
571 {'c', FILE_ATTRIBUTE_COMPRESSED},
572 {'o', FILE_ATTRIBUTE_OFFLINE},
573 {'n', FILE_ATTRIBUTE_NONINDEXED},
574 {'e', FILE_ATTRIBUTE_ENCRYPTED}
578 ret = talloc_size(mem_ctx, ARRAY_SIZE(attr_strs)+1);
583 for (len=i=0; i<ARRAY_SIZE(attr_strs); i++) {
584 if (attrib & attr_strs[i].attr) {
585 ret[len++] = attr_strs[i].c;
595 Set a boolean variable from the text value stored in the passed string.
596 Returns True in success, False if the passed string does not correctly
600 _PUBLIC_ BOOL set_boolean(const char *boolean_string, BOOL *boolean)
602 if (strwicmp(boolean_string, "yes") == 0 ||
603 strwicmp(boolean_string, "true") == 0 ||
604 strwicmp(boolean_string, "on") == 0 ||
605 strwicmp(boolean_string, "1") == 0) {
608 } else if (strwicmp(boolean_string, "no") == 0 ||
609 strwicmp(boolean_string, "false") == 0 ||
610 strwicmp(boolean_string, "off") == 0 ||
611 strwicmp(boolean_string, "0") == 0) {
619 * Parse a string containing a boolean value.
621 * val will be set to the read value.
623 * @retval True if a boolean value was parsed, False otherwise.
625 _PUBLIC_ BOOL conv_str_bool(const char * str, BOOL * val)
630 if (str == NULL || *str == '\0') {
634 lval = strtol(str, &end, 10 /* base */);
635 if (end == NULL || *end != '\0' || end == str) {
636 return set_boolean(str, val);
639 *val = (lval) ? True : False;
644 * Convert a size specification like 16K into an integral number of bytes.
646 _PUBLIC_ BOOL conv_str_size(const char * str, uint64_t * val)
649 unsigned long long lval;
651 if (str == NULL || *str == '\0') {
655 lval = strtoull(str, &end, 10 /* base */);
656 if (end == NULL || end == str) {
661 if (strwicmp(end, "K") == 0) {
663 } else if (strwicmp(end, "M") == 0) {
664 lval *= (1024ULL * 1024ULL);
665 } else if (strwicmp(end, "G") == 0) {
666 lval *= (1024ULL * 1024ULL * 1024ULL);
667 } else if (strwicmp(end, "T") == 0) {
668 lval *= (1024ULL * 1024ULL * 1024ULL * 1024ULL);
669 } else if (strwicmp(end, "P") == 0) {
670 lval *= (1024ULL * 1024ULL * 1024ULL * 1024ULL * 1024ULL);
676 *val = (uint64_t)lval;
681 * Parse a uint64_t value from a string
683 * val will be set to the value read.
685 * @retval True if parsing was successful, False otherwise
687 _PUBLIC_ BOOL conv_str_u64(const char * str, uint64_t * val)
690 unsigned long long lval;
692 if (str == NULL || *str == '\0') {
696 lval = strtoull(str, &end, 10 /* base */);
697 if (end == NULL || *end != '\0' || end == str) {
701 *val = (uint64_t)lval;
706 return the number of bytes occupied by a buffer in CH_UTF16 format
707 the result includes the null termination
709 _PUBLIC_ size_t utf16_len(const void *buf)
713 for (len = 0; SVAL(buf,len); len += 2) ;
719 return the number of bytes occupied by a buffer in CH_UTF16 format
720 the result includes the null termination
723 _PUBLIC_ size_t utf16_len_n(const void *src, size_t n)
727 for (len = 0; (len+2 < n) && SVAL(src, len); len += 2) ;
736 _PUBLIC_ size_t ucs2_align(const void *base_ptr, const void *p, int flags)
738 if (flags & (STR_NOALIGN|STR_ASCII))
740 return PTR_DIFF(p, base_ptr) & 1;
744 Do a case-insensitive, whitespace-ignoring string compare.
746 _PUBLIC_ int strwicmp(const char *psz1, const char *psz2)
748 /* if BOTH strings are NULL, return TRUE, if ONE is NULL return */
749 /* appropriate value. */
752 else if (psz1 == NULL)
754 else if (psz2 == NULL)
757 /* sync the strings on first non-whitespace */
759 while (isspace((int)*psz1))
761 while (isspace((int)*psz2))
763 if (toupper((unsigned char)*psz1) != toupper((unsigned char)*psz2)
770 return (*psz1 - *psz2);
776 _PUBLIC_ void string_replace(char *s, char oldc, char newc)
780 if (*s == oldc) *s = newc;
787 * @note The comparison is case-insensitive.
789 _PUBLIC_ BOOL strequal(const char *s1, const char *s2)
796 return strcasecmp(s1,s2) == 0;