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
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 #include "system/iconv.h"
27 #include "lib/ldb/include/ldb.h"
31 * @brief String utilities.
35 * Get the next token from a string, return False if none found.
36 * Handles double-quotes.
38 * Based on a routine by GJC@VILLAGE.COM.
39 * Extensively modified by Andrew.Tridgell@anu.edu.au
41 BOOL next_token(const char **ptr,char *buff, const char *sep, size_t bufsize)
52 /* default to simple separators */
56 /* find the first non sep char */
57 while (*s && strchr_m(sep,*s))
64 /* copy over the token */
65 for (quoted = False; len < bufsize && *s && (quoted || !strchr_m(sep,*s)); s++) {
74 *ptr = (*s) ? s+1 : s;
81 Case insensitive string compararison
83 int StrCaseCmp(const char *s1, const char *s2)
85 codepoint_t c1=0, c2=0;
89 c1 = next_codepoint(s1, &size1);
90 c2 = next_codepoint(s2, &size2);
99 if (c1 == INVALID_CODEPOINT ||
100 c2 == INVALID_CODEPOINT) {
101 /* what else can we do?? */
105 if (toupper_w(c1) != toupper_w(c2)) {
116 * @note The comparison is case-insensitive.
118 BOOL strequal(const char *s1, const char *s2)
125 return StrCaseCmp(s1,s2) == 0;
129 Compare 2 strings (case sensitive).
131 BOOL strcsequal(const char *s1,const char *s2)
138 return strcmp(s1,s2) == 0;
143 Do a case-insensitive, whitespace-ignoring string compare.
145 int strwicmp(const char *psz1, const char *psz2)
147 /* if BOTH strings are NULL, return TRUE, if ONE is NULL return */
148 /* appropriate value. */
151 else if (psz1 == NULL)
153 else if (psz2 == NULL)
156 /* sync the strings on first non-whitespace */
158 while (isspace((int)*psz1))
160 while (isspace((int)*psz2))
162 if (toupper((unsigned char)*psz1) != toupper((unsigned char)*psz2)
169 return (*psz1 - *psz2);
174 NOTE: oldc and newc must be 7 bit characters
176 void string_replace(char *s, char oldc, char newc)
180 codepoint_t c = next_codepoint(s, &size);
189 Trim the specified elements off the front and back of a string.
191 BOOL trim_string(char *s,const char *front,const char *back)
198 /* Ignore null or empty strings. */
199 if (!s || (s[0] == '\0'))
202 front_len = front? strlen(front) : 0;
203 back_len = back? strlen(back) : 0;
208 while (len && strncmp(s, front, front_len)==0) {
209 /* Must use memmove here as src & dest can
210 * easily overlap. Found by valgrind. JRA. */
211 memmove(s, s+front_len, (len-front_len)+1);
218 while ((len >= back_len) && strncmp(s+len-back_len,back,back_len)==0) {
219 s[len-back_len]='\0';
228 Find the number of 'c' chars in a string
230 size_t count_chars(const char *s, char c)
236 codepoint_t c2 = next_codepoint(s, &size);
237 if (c2 == c) count++;
245 Safe string copy into a known length string. maxlength does not
246 include the terminating zero.
248 char *safe_strcpy(char *dest,const char *src, size_t maxlength)
253 DEBUG(0,("ERROR: NULL dest in safe_strcpy\n"));
258 /* We intentionally write out at the extremity of the destination
259 * string. If the destination is too short (e.g. pstrcpy into mallocd
260 * or fstring) then this should cause an error under a memory
262 dest[maxlength] = '\0';
263 if (PTR_DIFF(&len, dest) > 0) { /* check if destination is on the stack, ok if so */
264 log_suspicious_usage("safe_strcpy", src);
275 if (len > maxlength) {
276 DEBUG(0,("ERROR: string overflow by %u (%u - %u) in safe_strcpy [%.50s]\n",
277 (uint_t)(len-maxlength), (unsigned)len, (unsigned)maxlength, src));
281 memmove(dest, src, len);
287 Safe string cat into a string. maxlength does not
288 include the terminating zero.
290 char *safe_strcat(char *dest, const char *src, size_t maxlength)
292 size_t src_len, dest_len;
295 DEBUG(0,("ERROR: NULL dest in safe_strcat\n"));
303 if (PTR_DIFF(&src_len, dest) > 0) { /* check if destination is on the stack, ok if so */
304 log_suspicious_usage("safe_strcat", src);
307 src_len = strlen(src);
308 dest_len = strlen(dest);
310 if (src_len + dest_len > maxlength) {
311 DEBUG(0,("ERROR: string overflow by %d in safe_strcat [%.50s]\n",
312 (int)(src_len + dest_len - maxlength), src));
313 if (maxlength > dest_len) {
314 memcpy(&dest[dest_len], src, maxlength - dest_len);
320 memcpy(&dest[dest_len], src, src_len);
321 dest[dest_len + src_len] = 0;
326 Paranoid strcpy into a buffer of given length (includes terminating
327 zero. Strips out all but 'a-Z0-9' and the character in other_safe_chars
328 and replaces with '_'. Deliberately does *NOT* check for multibyte
329 characters. Don't change it !
332 char *alpha_strcpy(char *dest, const char *src, const char *other_safe_chars, size_t maxlength)
336 if (maxlength == 0) {
337 /* can't fit any bytes at all! */
342 DEBUG(0,("ERROR: NULL dest in alpha_strcpy\n"));
352 if (len >= maxlength)
355 if (!other_safe_chars)
356 other_safe_chars = "";
358 for(i = 0; i < len; i++) {
359 int val = (src[i] & 0xff);
360 if (isupper(val) || islower(val) || isdigit(val) || strchr_m(other_safe_chars, val))
372 Like strncpy but always null terminates. Make sure there is room!
373 The variable n should always be one less than the available size.
376 char *StrnCpy(char *dest,const char *src,size_t n)
385 while (n-- && (*d++ = *src++))
393 Routine to get hex characters and turn them into a 16 byte array.
394 the array can be variable length, and any non-hex-numeric
395 characters are skipped. "0xnn" or "0Xnn" is specially catered
398 valid examples: "0A5D15"; "0x15, 0x49, 0xa2"; "59\ta9\te3\n"
402 size_t strhex_to_str(char *p, size_t len, const char *strhex)
405 size_t num_chars = 0;
406 uint8_t lonybble, hinybble;
407 const char *hexchars = "0123456789ABCDEF";
408 char *p1 = NULL, *p2 = NULL;
410 for (i = 0; i < len && strhex[i] != 0; i++) {
411 if (strncasecmp(hexchars, "0x", 2) == 0) {
412 i++; /* skip two chars */
416 if (!(p1 = strchr_m(hexchars, toupper((unsigned char)strhex[i]))))
419 i++; /* next hex digit */
421 if (!(p2 = strchr_m(hexchars, toupper((unsigned char)strhex[i]))))
424 /* get the two nybbles */
425 hinybble = PTR_DIFF(p1, hexchars);
426 lonybble = PTR_DIFF(p2, hexchars);
428 p[num_chars] = (hinybble << 4) | lonybble;
437 DATA_BLOB strhex_to_data_blob(const char *strhex)
439 DATA_BLOB ret_blob = data_blob(NULL, strlen(strhex)/2+1);
441 ret_blob.length = strhex_to_str(ret_blob.data,
450 * Routine to print a buffer as HEX digits, into an allocated string.
452 void hex_encode(const unsigned char *buff_in, size_t len, char **out_hex_buffer)
457 *out_hex_buffer = smb_xmalloc((len*2)+1);
458 hex_buffer = *out_hex_buffer;
460 for (i = 0; i < len; i++)
461 slprintf(&hex_buffer[i*2], 3, "%02X", buff_in[i]);
465 Check if a string is part of a list.
467 BOOL in_list(const char *s, const char *list, BOOL casesensitive)
475 while (next_token(&p,tok,LIST_SEP,sizeof(tok))) {
477 if (strcmp(tok,s) == 0)
480 if (StrCaseCmp(tok,s) == 0)
488 Set a string value, allocing the space for the string
490 static BOOL string_init(char **dest,const char *src)
494 (*dest) = strdup(src);
495 if ((*dest) == NULL) {
496 DEBUG(0,("Out of memory in string_init\n"));
505 void string_free(char **s)
507 if (s) SAFE_FREE(*s);
511 Set a string value, deallocating any existing space, and allocing the space
514 BOOL string_set(char **dest, const char *src)
517 return string_init(dest,src);
521 Substitute a string for a pattern in another string. Make sure there is
524 This routine looks for pattern in s and replaces it with
525 insert. It may do multiple replacements.
527 Any of " ; ' $ or ` in the insert string are replaced with _
528 if len==0 then the string cannot be extended. This is different from the old
529 use of len==0 which was for no length checks to be done.
532 void string_sub(char *s,const char *pattern, const char *insert, size_t len)
537 if (!insert || !pattern || !*pattern || !s)
540 ls = (ssize_t)strlen(s);
541 lp = (ssize_t)strlen(pattern);
542 li = (ssize_t)strlen(insert);
545 len = ls + 1; /* len is number of *bytes* */
547 while (lp <= ls && (p = strstr(s,pattern))) {
548 if (ls + (li-lp) >= len) {
549 DEBUG(0,("ERROR: string overflow by %d in string_sub(%.50s, %d)\n",
550 (int)(ls + (li-lp) - len),
555 memmove(p+li,p+lp,strlen(p+lp)+1);
580 Similar to string_sub() but allows for any character to be substituted.
582 if len==0 then the string cannot be extended. This is different from the old
583 use of len==0 which was for no length checks to be done.
586 void all_string_sub(char *s,const char *pattern,const char *insert, size_t len)
591 if (!insert || !pattern || !s)
594 ls = (ssize_t)strlen(s);
595 lp = (ssize_t)strlen(pattern);
596 li = (ssize_t)strlen(insert);
602 len = ls + 1; /* len is number of *bytes* */
604 while (lp <= ls && (p = strstr(s,pattern))) {
605 if (ls + (li-lp) >= len) {
606 DEBUG(0,("ERROR: string overflow by %d in all_string_sub(%.50s, %d)\n",
607 (int)(ls + (li-lp) - len),
612 memmove(p+li,p+lp,strlen(p+lp)+1);
614 memcpy(p, insert, li);
622 Strchr and strrchr_m are a bit complex on general multi-byte strings.
624 char *strchr_m(const char *s, char c)
626 /* characters below 0x3F are guaranteed to not appear in
627 non-initial position in multi-byte charsets */
628 if ((c & 0xC0) == 0) {
634 codepoint_t c2 = next_codepoint(s, &size);
636 return discard_const(s);
644 char *strrchr_m(const char *s, char c)
648 /* characters below 0x3F are guaranteed to not appear in
649 non-initial position in multi-byte charsets */
650 if ((c & 0xC0) == 0) {
651 return strrchr(s, c);
656 codepoint_t c2 = next_codepoint(s, &size);
658 ret = discard_const(s);
667 Convert a string to lower case, allocated with talloc
669 char *strlower_talloc(TALLOC_CTX *ctx, const char *src)
674 /* this takes advantage of the fact that upper/lower can't
675 change the length of a character by more than 1 byte */
676 dest = talloc_size(ctx, 2*(strlen(src))+1);
683 codepoint_t c = next_codepoint(src, &c_size);
688 c_size = push_codepoint(dest+size, c);
702 Convert a string to UPPER case, allocated with talloc
704 char *strupper_talloc(TALLOC_CTX *ctx, const char *src)
709 /* this takes advantage of the fact that upper/lower can't
710 change the length of a character by more than 1 byte */
711 dest = talloc_size(ctx, 2*(strlen(src))+1);
718 codepoint_t c = next_codepoint(src, &c_size);
723 c_size = push_codepoint(dest+size, c);
737 Convert a string to lower case.
739 void strlower_m(char *s)
743 /* this is quite a common operation, so we want it to be
744 fast. We optimise for the ascii case, knowing that all our
745 supported multi-byte character sets are ascii-compatible
746 (ie. they match for the first 128 chars) */
747 while (*s && !(((uint8_t)s[0]) & 0x7F)) {
748 *s = tolower((uint8_t)*s);
758 size_t c_size, c_size2;
759 codepoint_t c = next_codepoint(s, &c_size);
760 c_size2 = push_codepoint(d, tolower_w(c));
761 if (c_size2 > c_size) {
762 DEBUG(0,("FATAL: codepoint 0x%x (0x%x) expanded from %d to %d bytes in strlower_m\n",
763 c, tolower_w(c), (int)c_size, (int)c_size2));
764 smb_panic("codepoint expansion in strlower_m\n");
773 Convert a string to UPPER case.
775 void strupper_m(char *s)
779 /* this is quite a common operation, so we want it to be
780 fast. We optimise for the ascii case, knowing that all our
781 supported multi-byte character sets are ascii-compatible
782 (ie. they match for the first 128 chars) */
783 while (*s && !(((uint8_t)s[0]) & 0x7F)) {
784 *s = toupper((uint8_t)*s);
794 size_t c_size, c_size2;
795 codepoint_t c = next_codepoint(s, &c_size);
796 c_size2 = push_codepoint(d, toupper_w(c));
797 if (c_size2 > c_size) {
798 DEBUG(0,("FATAL: codepoint 0x%x (0x%x) expanded from %d to %d bytes in strupper_m\n",
799 c, toupper_w(c), (int)c_size, (int)c_size2));
800 smb_panic("codepoint expansion in strupper_m\n");
809 Count the number of UCS2 characters in a string. Normally this will
810 be the same as the number of bytes in a string for single byte strings,
811 but will be different for multibyte.
813 size_t strlen_m(const char *s)
821 while (*s && !(((uint8_t)s[0]) & 0x7F)) {
832 codepoint_t c = next_codepoint(s, &c_size);
845 Work out the number of multibyte chars in a string, including the NULL
848 size_t strlen_m_term(const char *s)
854 return strlen_m(s) + 1;
858 Unescape a URL encoded string, in place.
861 void rfc1738_unescape(char *buf)
865 while ((p=strchr_m(p,'+')))
870 while (p && *p && (p=strchr_m(p,'%'))) {
874 if (c1 >= '0' && c1 <= '9')
876 else if (c1 >= 'A' && c1 <= 'F')
878 else if (c1 >= 'a' && c1 <= 'f')
880 else {p++; continue;}
882 if (c2 >= '0' && c2 <= '9')
884 else if (c2 >= 'A' && c2 <= 'F')
886 else if (c2 >= 'a' && c2 <= 'f')
888 else {p++; continue;}
892 memmove(p+1, p+3, strlen(p+3)+1);
898 * Decode a base64 string into a DATA_BLOB - simple and slow algorithm
900 DATA_BLOB base64_decode_data_blob(TALLOC_CTX *mem_ctx, const char *s)
902 DATA_BLOB ret = data_blob_talloc(mem_ctx, s, strlen(s)+1);
903 ret.length = ldb_base64_decode(ret.data);
908 * Decode a base64 string in-place - wrapper for the above
910 void base64_decode_inplace(char *s)
912 ldb_base64_decode(s);
916 * Encode a base64 string into a talloc()ed string caller to free.
918 char *base64_encode_data_blob(TALLOC_CTX *mem_ctx, DATA_BLOB data)
920 return ldb_base64_encode(mem_ctx, data.data, data.length);
924 size_t valgrind_strlen(const char *s)
927 for(count = 0; *s++; count++)
935 format a string into length-prefixed dotted domain format, as used in NBT
936 and in some ADS structures
938 const char *str_format_nbt_domain(TALLOC_CTX *mem_ctx, const char *s)
943 return talloc_strdup(mem_ctx, "");
945 ret = talloc_size(mem_ctx, strlen(s)+2);
950 memcpy(ret+1, s, strlen(s)+1);
953 for (i=0;ret[i];i++) {
955 char *p = strchr(ret+i+1, '.');
957 ret[i] = p-(ret+i+1);
959 ret[i] = strlen(ret+i+1);
967 BOOL add_string_to_array(TALLOC_CTX *mem_ctx,
968 const char *str, const char ***strings, int *num)
970 char *dup_str = talloc_strdup(mem_ctx, str);
972 *strings = talloc_realloc(mem_ctx,
974 const char *, ((*num)+1));
976 if ((*strings == NULL) || (dup_str == NULL))
979 (*strings)[*num] = dup_str;
988 varient of strcmp() that handles NULL ptrs
990 int strcmp_safe(const char *s1, const char *s2)
995 if (s1 == NULL || s2 == NULL) {
998 return strcmp(s1, s2);
1002 /*******************************************************************
1003 return the number of bytes occupied by a buffer in ASCII format
1004 the result includes the null termination
1005 limited by 'n' bytes
1006 ********************************************************************/
1007 size_t ascii_len_n(const char *src, size_t n)
1011 len = strnlen(src, n);
1020 /*******************************************************************
1021 Return a string representing a CIFS attribute for a file.
1022 ********************************************************************/
1023 char *attrib_string(TALLOC_CTX *mem_ctx, uint32_t attrib)
1030 {'V', FILE_ATTRIBUTE_VOLUME},
1031 {'D', FILE_ATTRIBUTE_DIRECTORY},
1032 {'A', FILE_ATTRIBUTE_ARCHIVE},
1033 {'H', FILE_ATTRIBUTE_HIDDEN},
1034 {'S', FILE_ATTRIBUTE_SYSTEM},
1035 {'N', FILE_ATTRIBUTE_NORMAL},
1036 {'R', FILE_ATTRIBUTE_READONLY},
1037 {'d', FILE_ATTRIBUTE_DEVICE},
1038 {'t', FILE_ATTRIBUTE_TEMPORARY},
1039 {'s', FILE_ATTRIBUTE_SPARSE},
1040 {'r', FILE_ATTRIBUTE_REPARSE_POINT},
1041 {'c', FILE_ATTRIBUTE_COMPRESSED},
1042 {'o', FILE_ATTRIBUTE_OFFLINE},
1043 {'n', FILE_ATTRIBUTE_NONINDEXED},
1044 {'e', FILE_ATTRIBUTE_ENCRYPTED}
1048 ret = talloc_size(mem_ctx, ARRAY_SIZE(attr_strs)+1);
1053 for (len=i=0; i<ARRAY_SIZE(attr_strs); i++) {
1054 if (attrib & attr_strs[i].attr) {
1055 ret[len++] = attr_strs[i].c;