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.
28 * @brief String utilities.
32 * Internal function to get the next token from a string, return False if none
33 * found. Handles double-quotes. This is the work horse function called by
34 * next_token() and next_token_no_ltrim().
36 * Based on a routine by GJC@VILLAGE.COM.
37 * Extensively modified by Andrew.Tridgell@anu.edu.au
39 static BOOL next_token_internal(const char **ptr,
55 /* default to simple separators */
59 /* find the first non sep char, if left-trimming is requested */
61 while (*s && strchr_m(sep,*s))
69 /* copy over the token */
71 for (quoted = False; len < bufsize && *s && (quoted || !strchr_m(sep,*s)); s++) {
80 *ptr = (*s) ? s+1 : s;
87 * Get the next token from a string, return False if none found. Handles
88 * double-quotes. This version trims leading separator characters before
89 * looking for a token.
91 BOOL next_token(const char **ptr, char *buff, const char *sep, size_t bufsize)
93 return next_token_internal(ptr, buff, sep, bufsize, True);
97 * Get the next token from a string, return False if none found. Handles
98 * double-quotes. This version does not trim leading separator characters
99 * before looking for a token.
101 BOOL next_token_no_ltrim(const char **ptr,
106 return next_token_internal(ptr, buff, sep, bufsize, False);
110 This is like next_token but is not re-entrant and "remembers" the first
111 parameter so you can pass NULL. This is useful for user interface code
112 but beware the fact that it is not re-entrant!
115 static const char *last_ptr=NULL;
117 BOOL next_token_nr(const char **ptr,char *buff, const char *sep, size_t bufsize)
123 ret = next_token(ptr, buff, sep, bufsize);
128 static uint16 tmpbuf[sizeof(pstring)];
130 void set_first_token(char *ptr)
136 Convert list of tokens to array; dependent on above routine.
137 Uses last_ptr from above - bit of a hack.
140 char **toktocliplist(int *ctok, const char *sep)
142 char *s=(char *)last_ptr;
149 while(*s && strchr_m(sep,*s))
158 while(*s && (!strchr_m(sep,*s)))
160 while(*s && strchr_m(sep,*s))
167 if (!(ret=iret=SMB_MALLOC_ARRAY(char *,ictok+1)))
185 * Case insensitive string compararison.
187 * iconv does not directly give us a way to compare strings in
188 * arbitrary unix character sets -- all we can is convert and then
189 * compare. This is expensive.
191 * As an optimization, we do a first pass that considers only the
192 * prefix of the strings that is entirely 7-bit. Within this, we
193 * check whether they have the same value.
195 * Hopefully this will often give the answer without needing to copy.
196 * In particular it should speed comparisons to literal ascii strings
197 * or comparisons of strings that are "obviously" different.
199 * If we find a non-ascii character we fall back to converting via
202 * This should never be slower than convering the whole thing, and
205 * A different optimization would be to compare for bitwise equality
206 * in the binary encoding. (It would be possible thought hairy to do
207 * both simultaneously.) But in that case if they turn out to be
208 * different, we'd need to restart the whole thing.
210 * Even better is to implement strcasecmp for each encoding and use a
213 int StrCaseCmp(const char *s, const char *t)
218 smb_ucs2_t *buffer_s, *buffer_t;
221 for (ps = s, pt = t; ; ps++, pt++) {
225 return 0; /* both ended */
227 return -1; /* s is a prefix */
229 return +1; /* t is a prefix */
230 else if ((*ps & 0x80) || (*pt & 0x80))
231 /* not ascii anymore, do it the hard way from here on in */
234 us = toupper_ascii(*ps);
235 ut = toupper_ascii(*pt);
244 size = push_ucs2_allocate(&buffer_s, ps);
245 if (size == (size_t)-1) {
246 return strcmp(ps, pt);
247 /* Not quite the right answer, but finding the right one
248 under this failure case is expensive, and it's pretty close */
251 size = push_ucs2_allocate(&buffer_t, pt);
252 if (size == (size_t)-1) {
254 return strcmp(ps, pt);
255 /* Not quite the right answer, but finding the right one
256 under this failure case is expensive, and it's pretty close */
259 ret = strcasecmp_w(buffer_s, buffer_t);
267 Case insensitive string compararison, length limited.
269 int StrnCaseCmp(const char *s, const char *t, size_t n)
272 unix_strupper(s, strlen(s)+1, buf1, sizeof(buf1));
273 unix_strupper(t, strlen(t)+1, buf2, sizeof(buf2));
274 return strncmp(buf1,buf2,n);
280 * @note The comparison is case-insensitive.
282 BOOL strequal(const char *s1, const char *s2)
289 return(StrCaseCmp(s1,s2)==0);
293 * Compare 2 strings up to and including the nth char.
295 * @note The comparison is case-insensitive.
297 BOOL strnequal(const char *s1,const char *s2,size_t n)
301 if (!s1 || !s2 || !n)
304 return(StrnCaseCmp(s1,s2,n)==0);
308 Compare 2 strings (case sensitive).
311 BOOL strcsequal(const char *s1,const char *s2)
318 return(strcmp(s1,s2)==0);
322 Do a case-insensitive, whitespace-ignoring string compare.
325 int strwicmp(const char *psz1, const char *psz2)
327 /* if BOTH strings are NULL, return TRUE, if ONE is NULL return */
328 /* appropriate value. */
331 else if (psz1 == NULL)
333 else if (psz2 == NULL)
336 /* sync the strings on first non-whitespace */
338 while (isspace((int)*psz1))
340 while (isspace((int)*psz2))
342 if (toupper_ascii(*psz1) != toupper_ascii(*psz2) || *psz1 == '\0'
348 return (*psz1 - *psz2);
353 Convert a string to upper case, but don't modify it.
356 char *strupper_static(const char *s)
367 Convert a string to "normal" form.
370 void strnorm(char *s, int case_default)
372 if (case_default == CASE_UPPER)
379 Check if a string is in "normal" case.
382 BOOL strisnormal(const char *s, int case_default)
384 if (case_default == CASE_UPPER)
385 return(!strhaslower(s));
387 return(!strhasupper(s));
393 NOTE: oldc and newc must be 7 bit characters
396 void string_replace( pstring s, char oldc, char newc )
400 /* this is quite a common operation, so we want it to be
401 fast. We optimise for the ascii case, knowing that all our
402 supported multi-byte character sets are ascii-compatible
403 (ie. they match for the first 128 chars) */
405 for (p = s; *p; p++) {
406 if (*p & 0x80) /* mb string - slow path. */
415 /* Slow (mb) path. */
416 #ifdef BROKEN_UNICODE_COMPOSE_CHARACTERS
417 /* With compose characters we must restart from the beginning. JRA. */
420 push_ucs2(NULL, tmpbuf, p, sizeof(tmpbuf), STR_TERMINATE);
421 string_replace_w(tmpbuf, UCS2_CHAR(oldc), UCS2_CHAR(newc));
422 pull_ucs2(NULL, p, tmpbuf, -1, sizeof(tmpbuf), STR_TERMINATE);
426 Skip past some strings in a buffer.
429 char *skip_string(char *buf,size_t n)
432 buf += strlen(buf) + 1;
437 Count the number of characters in a string. Normally this will
438 be the same as the number of bytes in a string for single byte strings,
439 but will be different for multibyte.
442 size_t str_charnum(const char *s)
444 uint16 tmpbuf2[sizeof(pstring)];
445 push_ucs2(NULL, tmpbuf2,s, sizeof(tmpbuf2), STR_TERMINATE);
446 return strlen_w(tmpbuf2);
450 Count the number of characters in a string. Normally this will
451 be the same as the number of bytes in a string for single byte strings,
452 but will be different for multibyte.
455 size_t str_ascii_charnum(const char *s)
458 push_ascii(tmpbuf2, s, sizeof(tmpbuf2), STR_TERMINATE);
459 return strlen(tmpbuf2);
462 BOOL trim_char(char *s,char cfront,char cback)
468 /* Ignore null or empty strings. */
469 if (!s || (s[0] == '\0'))
473 while (*fp && *fp == cfront)
476 /* We ate the string. */
484 ep = fp + strlen(fp) - 1;
486 /* Attempt ascii only. Bail for mb strings. */
487 while ((ep >= fp) && (*ep == cback)) {
489 if ((ep > fp) && (((unsigned char)ep[-1]) & 0x80)) {
490 /* Could be mb... bail back to tim_string. */
498 return trim_string(s, cfront ? fs : NULL, bs);
504 /* We ate the string. */
511 memmove(s, fp, ep-fp+2);
516 Trim the specified elements off the front and back of a string.
519 BOOL trim_string(char *s,const char *front,const char *back)
526 /* Ignore null or empty strings. */
527 if (!s || (s[0] == '\0'))
530 front_len = front? strlen(front) : 0;
531 back_len = back? strlen(back) : 0;
536 while (len && strncmp(s, front, front_len)==0) {
537 /* Must use memmove here as src & dest can
538 * easily overlap. Found by valgrind. JRA. */
539 memmove(s, s+front_len, (len-front_len)+1);
546 while ((len >= back_len) && strncmp(s+len-back_len,back,back_len)==0) {
547 s[len-back_len]='\0';
556 Does a string have any uppercase chars in it?
559 BOOL strhasupper(const char *s)
562 push_ucs2(NULL, tmpbuf,s, sizeof(tmpbuf), STR_TERMINATE);
563 for(ptr=tmpbuf;*ptr;ptr++)
570 Does a string have any lowercase chars in it?
573 BOOL strhaslower(const char *s)
576 push_ucs2(NULL, tmpbuf,s, sizeof(tmpbuf), STR_TERMINATE);
577 for(ptr=tmpbuf;*ptr;ptr++)
584 Find the number of 'c' chars in a string
587 size_t count_chars(const char *s,char c)
591 smb_ucs2_t *alloc_tmpbuf = NULL;
593 if (push_ucs2_allocate(&alloc_tmpbuf, s) == (size_t)-1) {
597 for(count=0,ptr=alloc_tmpbuf;*ptr;ptr++)
598 if(*ptr==UCS2_CHAR(c))
601 SAFE_FREE(alloc_tmpbuf);
606 Safe string copy into a known length string. maxlength does not
607 include the terminating zero.
610 char *safe_strcpy_fn(const char *fn, int line, char *dest,const char *src, size_t maxlength)
615 DEBUG(0,("ERROR: NULL dest in safe_strcpy, called from [%s][%d]\n", fn, line));
620 clobber_region(fn,line,dest, maxlength+1);
628 len = strnlen(src, maxlength+1);
630 if (len > maxlength) {
631 DEBUG(0,("ERROR: string overflow by %lu (%lu - %lu) in safe_strcpy [%.50s]\n",
632 (unsigned long)(len-maxlength), (unsigned long)len,
633 (unsigned long)maxlength, src));
637 memmove(dest, src, len);
643 Safe string cat into a string. maxlength does not
644 include the terminating zero.
646 char *safe_strcat_fn(const char *fn, int line, char *dest, const char *src, size_t maxlength)
648 size_t src_len, dest_len;
651 DEBUG(0,("ERROR: NULL dest in safe_strcat, called from [%s][%d]\n", fn, line));
658 src_len = strnlen(src, maxlength + 1);
659 dest_len = strnlen(dest, maxlength + 1);
662 clobber_region(fn, line, dest + dest_len, maxlength + 1 - dest_len);
665 if (src_len + dest_len > maxlength) {
666 DEBUG(0,("ERROR: string overflow by %d in safe_strcat [%.50s]\n",
667 (int)(src_len + dest_len - maxlength), src));
668 if (maxlength > dest_len) {
669 memcpy(&dest[dest_len], src, maxlength - dest_len);
675 memcpy(&dest[dest_len], src, src_len);
676 dest[dest_len + src_len] = 0;
681 Paranoid strcpy into a buffer of given length (includes terminating
682 zero. Strips out all but 'a-Z0-9' and the character in other_safe_chars
683 and replaces with '_'. Deliberately does *NOT* check for multibyte
684 characters. Don't change it !
686 char *alpha_strcpy_fn(const char *fn, int line, char *dest, const char *src, const char *other_safe_chars, size_t maxlength)
691 clobber_region(fn, line, dest, maxlength);
695 DEBUG(0,("ERROR: NULL dest in alpha_strcpy, called from [%s][%d]\n", fn, line));
705 if (len >= maxlength)
708 if (!other_safe_chars)
709 other_safe_chars = "";
711 for(i = 0; i < len; i++) {
712 int val = (src[i] & 0xff);
713 if (isupper_ascii(val) || islower_ascii(val) || isdigit(val) || strchr_m(other_safe_chars, val))
725 Like strncpy but always null terminates. Make sure there is room!
726 The variable n should always be one less than the available size.
728 char *StrnCpy_fn(const char *fn, int line,char *dest,const char *src,size_t n)
733 clobber_region(fn, line, dest, n+1);
737 DEBUG(0,("ERROR: NULL dest in StrnCpy, called from [%s][%d]\n", fn, line));
746 while (n-- && (*d = *src)) {
757 Like strncpy but copies up to the character marker. always null terminates.
758 returns a pointer to the character marker in the source string (src).
761 static char *strncpyn(char *dest, const char *src, size_t n, char c)
767 clobber_region(dest, n+1);
769 p = strchr_m(src, c);
771 DEBUG(5, ("strncpyn: separator character (%c) not found\n", c));
775 str_len = PTR_DIFF(p, src);
776 strncpy(dest, src, MIN(n, str_len));
777 dest[str_len] = '\0';
784 Routine to get hex characters and turn them into a 16 byte array.
785 the array can be variable length, and any non-hex-numeric
786 characters are skipped. "0xnn" or "0Xnn" is specially catered
789 valid examples: "0A5D15"; "0x15, 0x49, 0xa2"; "59\ta9\te3\n"
793 size_t strhex_to_str(char *p, size_t len, const char *strhex)
796 size_t num_chars = 0;
797 unsigned char lonybble, hinybble;
798 const char *hexchars = "0123456789ABCDEF";
799 char *p1 = NULL, *p2 = NULL;
801 for (i = 0; i < len && strhex[i] != 0; i++) {
802 if (strnequal(hexchars, "0x", 2)) {
803 i++; /* skip two chars */
807 if (!(p1 = strchr_m(hexchars, toupper_ascii(strhex[i]))))
810 i++; /* next hex digit */
812 if (!(p2 = strchr_m(hexchars, toupper_ascii(strhex[i]))))
815 /* get the two nybbles */
816 hinybble = PTR_DIFF(p1, hexchars);
817 lonybble = PTR_DIFF(p2, hexchars);
819 p[num_chars] = (hinybble << 4) | lonybble;
828 DATA_BLOB strhex_to_data_blob(TALLOC_CTX *mem_ctx, const char *strhex)
833 ret_blob = data_blob_talloc(mem_ctx, NULL, strlen(strhex)/2+1);
835 ret_blob = data_blob(NULL, strlen(strhex)/2+1);
837 ret_blob.length = strhex_to_str((char*)ret_blob.data,
845 * Routine to print a buffer as HEX digits, into an allocated string.
848 char *hex_encode(TALLOC_CTX *mem_ctx, const unsigned char *buff_in, size_t len)
853 hex_buffer = TALLOC_ARRAY(mem_ctx, char, (len*2)+1);
855 for (i = 0; i < len; i++)
856 slprintf(&hex_buffer[i*2], 3, "%02X", buff_in[i]);
862 Check if a string is part of a list.
865 BOOL in_list(const char *s, const char *list, BOOL casesensitive)
873 while (next_token(&p,tok,LIST_SEP,sizeof(tok))) {
875 if (strcmp(tok,s) == 0)
878 if (StrCaseCmp(tok,s) == 0)
885 /* this is used to prevent lots of mallocs of size 1 */
886 static const char *null_string = "";
889 Set a string value, allocing the space for the string
892 static BOOL string_init(char **dest,const char *src)
902 *dest = CONST_DISCARD(char*, null_string);
904 (*dest) = SMB_STRDUP(src);
905 if ((*dest) == NULL) {
906 DEBUG(0,("Out of memory in string_init\n"));
917 void string_free(char **s)
921 if (*s == null_string)
927 Set a string value, deallocating any existing space, and allocing the space
931 BOOL string_set(char **dest,const char *src)
934 return(string_init(dest,src));
938 Substitute a string for a pattern in another string. Make sure there is
941 This routine looks for pattern in s and replaces it with
942 insert. It may do multiple replacements or just one.
944 Any of " ; ' $ or ` in the insert string are replaced with _
945 if len==0 then the string cannot be extended. This is different from the old
946 use of len==0 which was for no length checks to be done.
949 void string_sub2(char *s,const char *pattern, const char *insert, size_t len,
950 BOOL remove_unsafe_characters, BOOL replace_once, BOOL allow_trailing_dollar)
955 if (!insert || !pattern || !*pattern || !s)
958 ls = (ssize_t)strlen(s);
959 lp = (ssize_t)strlen(pattern);
960 li = (ssize_t)strlen(insert);
963 len = ls + 1; /* len is number of *bytes* */
965 while (lp <= ls && (p = strstr_m(s,pattern))) {
966 if (ls + (li-lp) >= len) {
967 DEBUG(0,("ERROR: string overflow by %d in string_sub(%.50s, %d)\n",
968 (int)(ls + (li-lp) - len),
973 memmove(p+li,p+lp,strlen(p+lp)+1);
982 /* allow a trailing $ (as in machine accounts) */
983 if (allow_trailing_dollar && (i == li - 1 )) {
990 if ( remove_unsafe_characters ) {
992 /* yes this break should be here since we want to
993 fall throw if not replacing unsafe chars */
1008 void string_sub_once(char *s, const char *pattern, const char *insert, size_t len)
1010 string_sub2( s, pattern, insert, len, True, True, False );
1013 void string_sub(char *s,const char *pattern, const char *insert, size_t len)
1015 string_sub2( s, pattern, insert, len, True, False, False );
1018 void fstring_sub(char *s,const char *pattern,const char *insert)
1020 string_sub(s, pattern, insert, sizeof(fstring));
1023 void pstring_sub(char *s,const char *pattern,const char *insert)
1025 string_sub(s, pattern, insert, sizeof(pstring));
1029 Similar to string_sub, but it will accept only allocated strings
1030 and may realloc them so pay attention at what you pass on no
1031 pointers inside strings, no pstrings or const may be passed
1035 char *realloc_string_sub(char *string, const char *pattern,
1040 ssize_t ls,lp,li,ld, i;
1042 if (!insert || !pattern || !*pattern || !string || !*string)
1047 in = SMB_STRDUP(insert);
1049 DEBUG(0, ("realloc_string_sub: out of memory!\n"));
1052 ls = (ssize_t)strlen(s);
1053 lp = (ssize_t)strlen(pattern);
1054 li = (ssize_t)strlen(insert);
1056 for (i=0;i<li;i++) {
1073 while ((p = strstr_m(s,pattern))) {
1075 int offset = PTR_DIFF(s,string);
1076 string = SMB_REALLOC(string, ls + ld + 1);
1078 DEBUG(0, ("realloc_string_sub: out of memory!\n"));
1082 p = string + offset + (p - s);
1085 memmove(p+li,p+lp,strlen(p+lp)+1);
1095 /* Same as string_sub, but returns a talloc'ed string */
1097 char *talloc_string_sub(TALLOC_CTX *mem_ctx, const char *src,
1098 const char *pattern, const char *insert)
1103 ssize_t ls,lp,li,ld, i;
1105 if (!insert || !pattern || !*pattern || !src || !*src)
1108 string = talloc_strdup(mem_ctx, src);
1109 if (string == NULL) {
1110 DEBUG(0, ("talloc_strdup failed\n"));
1116 in = SMB_STRDUP(insert);
1118 DEBUG(0, ("talloc_string_sub: out of memory!\n"));
1121 ls = (ssize_t)strlen(s);
1122 lp = (ssize_t)strlen(pattern);
1123 li = (ssize_t)strlen(insert);
1125 for (i=0;i<li;i++) {
1142 while ((p = strstr_m(s,pattern))) {
1144 int offset = PTR_DIFF(s,string);
1145 string = TALLOC_REALLOC(mem_ctx, string, ls + ld + 1);
1147 DEBUG(0, ("talloc_string_sub: out of "
1152 p = string + offset + (p - s);
1155 memmove(p+li,p+lp,strlen(p+lp)+1);
1166 Similar to string_sub() but allows for any character to be substituted.
1168 if len==0 then the string cannot be extended. This is different from the old
1169 use of len==0 which was for no length checks to be done.
1172 void all_string_sub(char *s,const char *pattern,const char *insert, size_t len)
1177 if (!insert || !pattern || !s)
1180 ls = (ssize_t)strlen(s);
1181 lp = (ssize_t)strlen(pattern);
1182 li = (ssize_t)strlen(insert);
1188 len = ls + 1; /* len is number of *bytes* */
1190 while (lp <= ls && (p = strstr_m(s,pattern))) {
1191 if (ls + (li-lp) >= len) {
1192 DEBUG(0,("ERROR: string overflow by %d in all_string_sub(%.50s, %d)\n",
1193 (int)(ls + (li-lp) - len),
1194 pattern, (int)len));
1198 memmove(p+li,p+lp,strlen(p+lp)+1);
1200 memcpy(p, insert, li);
1207 Similar to all_string_sub but for unicode strings.
1208 Return a new allocated unicode string.
1209 similar to string_sub() but allows for any character to be substituted.
1213 static smb_ucs2_t *all_string_sub_w(const smb_ucs2_t *s, const smb_ucs2_t *pattern,
1214 const smb_ucs2_t *insert)
1217 const smb_ucs2_t *sp;
1218 size_t lr, lp, li, lt;
1220 if (!insert || !pattern || !*pattern || !s)
1223 lt = (size_t)strlen_w(s);
1224 lp = (size_t)strlen_w(pattern);
1225 li = (size_t)strlen_w(insert);
1228 const smb_ucs2_t *st = s;
1230 while ((sp = strstr_w(st, pattern))) {
1236 r = rp = SMB_MALLOC_ARRAY(smb_ucs2_t, lt + 1);
1238 DEBUG(0, ("all_string_sub_w: out of memory!\n"));
1242 while ((sp = strstr_w(s, pattern))) {
1243 memcpy(rp, s, (sp - s));
1244 rp += ((sp - s) / sizeof(smb_ucs2_t));
1245 memcpy(rp, insert, (li * sizeof(smb_ucs2_t)));
1249 lr = ((rp - r) / sizeof(smb_ucs2_t));
1251 memcpy(rp, s, ((lt - lr) * sizeof(smb_ucs2_t)));
1259 smb_ucs2_t *all_string_sub_wa(smb_ucs2_t *s, const char *pattern,
1264 if (!insert || !pattern || !s)
1266 push_ucs2(NULL, p, pattern, sizeof(wpstring) - 1, STR_TERMINATE);
1267 push_ucs2(NULL, i, insert, sizeof(wpstring) - 1, STR_TERMINATE);
1268 return all_string_sub_w(s, p, i);
1273 Splits out the front and back at a separator.
1276 static void split_at_last_component(char *path, char *front, char sep, char *back)
1278 char *p = strrchr_m(path, sep);
1284 pstrcpy(front, path);
1298 Write an octal as a string.
1301 const char *octal_string(int i)
1303 static char ret[64];
1306 slprintf(ret, sizeof(ret)-1, "0%o", i);
1312 Truncate a string at a specified length.
1315 char *string_truncate(char *s, unsigned int length)
1317 if (s && strlen(s) > length)
1323 Strchr and strrchr_m are very hard to do on general multi-byte strings.
1324 We convert via ucs2 for now.
1327 char *strchr_m(const char *src, char c)
1334 /* characters below 0x3F are guaranteed to not appear in
1335 non-initial position in multi-byte charsets */
1336 if ((c & 0xC0) == 0) {
1337 return strchr(src, c);
1340 /* this is quite a common operation, so we want it to be
1341 fast. We optimise for the ascii case, knowing that all our
1342 supported multi-byte character sets are ascii-compatible
1343 (ie. they match for the first 128 chars) */
1345 for (s = src; *s && !(((unsigned char)s[0]) & 0x80); s++) {
1353 #ifdef BROKEN_UNICODE_COMPOSE_CHARACTERS
1354 /* With compose characters we must restart from the beginning. JRA. */
1358 push_ucs2(NULL, ws, s, sizeof(ws), STR_TERMINATE);
1359 p = strchr_w(ws, UCS2_CHAR(c));
1363 pull_ucs2_pstring(s2, ws);
1364 return (char *)(s+strlen(s2));
1367 char *strrchr_m(const char *s, char c)
1369 /* characters below 0x3F are guaranteed to not appear in
1370 non-initial position in multi-byte charsets */
1371 if ((c & 0xC0) == 0) {
1372 return strrchr(s, c);
1375 /* this is quite a common operation, so we want it to be
1376 fast. We optimise for the ascii case, knowing that all our
1377 supported multi-byte character sets are ascii-compatible
1378 (ie. they match for the first 128 chars). Also, in Samba
1379 we only search for ascii characters in 'c' and that
1380 in all mb character sets with a compound character
1381 containing c, if 'c' is not a match at position
1382 p, then p[-1] > 0x7f. JRA. */
1385 size_t len = strlen(s);
1387 BOOL got_mb = False;
1394 /* Could be a match. Part of a multibyte ? */
1395 if ((cp > s) && (((unsigned char)cp[-1]) & 0x80)) {
1396 /* Yep - go slow :-( */
1400 /* No - we have a match ! */
1403 } while (cp-- != s);
1408 /* String contained a non-ascii char. Slow path. */
1414 push_ucs2(NULL, ws, s, sizeof(ws), STR_TERMINATE);
1415 p = strrchr_w(ws, UCS2_CHAR(c));
1419 pull_ucs2_pstring(s2, ws);
1420 return (char *)(s+strlen(s2));
1424 /***********************************************************************
1425 Return the equivalent of doing strrchr 'n' times - always going
1427 ***********************************************************************/
1429 char *strnrchr_m(const char *s, char c, unsigned int n)
1435 push_ucs2(NULL, ws, s, sizeof(ws), STR_TERMINATE);
1436 p = strnrchr_w(ws, UCS2_CHAR(c), n);
1440 pull_ucs2_pstring(s2, ws);
1441 return (char *)(s+strlen(s2));
1444 /***********************************************************************
1445 strstr_m - We convert via ucs2 for now.
1446 ***********************************************************************/
1448 char *strstr_m(const char *src, const char *findstr)
1451 smb_ucs2_t *src_w, *find_w;
1456 size_t findstr_len = 0;
1458 /* for correctness */
1463 /* Samba does single character findstr calls a *lot*. */
1464 if (findstr[1] == '\0')
1465 return strchr_m(src, *findstr);
1467 /* We optimise for the ascii case, knowing that all our
1468 supported multi-byte character sets are ascii-compatible
1469 (ie. they match for the first 128 chars) */
1471 for (s = src; *s && !(((unsigned char)s[0]) & 0x80); s++) {
1472 if (*s == *findstr) {
1474 findstr_len = strlen(findstr);
1476 if (strncmp(s, findstr, findstr_len) == 0) {
1485 #if 1 /* def BROKEN_UNICODE_COMPOSE_CHARACTERS */
1486 /* 'make check' fails unless we do this */
1488 /* With compose characters we must restart from the beginning. JRA. */
1492 if (push_ucs2_allocate(&src_w, src) == (size_t)-1) {
1493 DEBUG(0,("strstr_m: src malloc fail\n"));
1497 if (push_ucs2_allocate(&find_w, findstr) == (size_t)-1) {
1499 DEBUG(0,("strstr_m: find malloc fail\n"));
1503 p = strstr_w(src_w, find_w);
1512 if (pull_ucs2_allocate(&s2, src_w) == (size_t)-1) {
1515 DEBUG(0,("strstr_m: dest malloc fail\n"));
1518 retp = (char *)(s+strlen(s2));
1526 Convert a string to lower case.
1529 void strlower_m(char *s)
1534 /* this is quite a common operation, so we want it to be
1535 fast. We optimise for the ascii case, knowing that all our
1536 supported multi-byte character sets are ascii-compatible
1537 (ie. they match for the first 128 chars) */
1539 while (*s && !(((unsigned char)s[0]) & 0x80)) {
1540 *s = tolower_ascii((unsigned char)*s);
1547 /* I assume that lowercased string takes the same number of bytes
1548 * as source string even in UTF-8 encoding. (VIV) */
1549 len = strlen(s) + 1;
1552 unix_strlower(s,len,s,len);
1553 /* Catch mb conversion errors that may not terminate. */
1560 Convert a string to upper case.
1563 void strupper_m(char *s)
1568 /* this is quite a common operation, so we want it to be
1569 fast. We optimise for the ascii case, knowing that all our
1570 supported multi-byte character sets are ascii-compatible
1571 (ie. they match for the first 128 chars) */
1573 while (*s && !(((unsigned char)s[0]) & 0x80)) {
1574 *s = toupper_ascii((unsigned char)*s);
1581 /* I assume that lowercased string takes the same number of bytes
1582 * as source string even in multibyte encoding. (VIV) */
1583 len = strlen(s) + 1;
1586 unix_strupper(s,len,s,len);
1587 /* Catch mb conversion errors that may not terminate. */
1594 Return a RFC2254 binary string representation of a buffer.
1595 Used in LDAP filters.
1599 char *binary_string_rfc2254(char *buf, int len)
1603 const char *hex = "0123456789ABCDEF";
1604 s = SMB_MALLOC(len * 3 + 1);
1607 for (j=i=0;i<len;i++) {
1609 s[j+1] = hex[((unsigned char)buf[i]) >> 4];
1610 s[j+2] = hex[((unsigned char)buf[i]) & 0xF];
1617 char *binary_string(char *buf, int len)
1621 const char *hex = "0123456789ABCDEF";
1622 s = SMB_MALLOC(len * 2 + 1);
1625 for (j=i=0;i<len;i++) {
1626 s[j] = hex[((unsigned char)buf[i]) >> 4];
1627 s[j+1] = hex[((unsigned char)buf[i]) & 0xF];
1634 Just a typesafety wrapper for snprintf into a pstring.
1637 int pstr_sprintf(pstring s, const char *fmt, ...)
1643 ret = vsnprintf(s, PSTRING_LEN, fmt, ap);
1650 Just a typesafety wrapper for snprintf into a fstring.
1653 int fstr_sprintf(fstring s, const char *fmt, ...)
1659 ret = vsnprintf(s, FSTRING_LEN, fmt, ap);
1665 #if !defined(HAVE_STRNDUP) || defined(BROKEN_STRNDUP)
1667 Some platforms don't have strndup.
1669 #if defined(PARANOID_MALLOC_CHECKER)
1673 char *strndup(const char *s, size_t n)
1678 ret = SMB_MALLOC(n+1);
1687 #if defined(PARANOID_MALLOC_CHECKER)
1688 #define strndup(s,n) __ERROR_DONT_USE_STRNDUP_DIRECTLY
1693 #if !defined(HAVE_STRNLEN) || defined(BROKEN_STRNLEN)
1695 Some platforms don't have strnlen
1698 size_t strnlen(const char *s, size_t n)
1701 for (i=0; i<n && s[i] != '\0'; i++)
1708 List of Strings manipulation functions
1711 #define S_LIST_ABS 16 /* List Allocation Block Size */
1713 static char **str_list_make_internal(TALLOC_CTX *mem_ctx, const char *string, const char *sep)
1715 char **list, **rlist;
1721 if (!string || !*string)
1724 s = talloc_strdup(mem_ctx, string);
1726 s = SMB_STRDUP(string);
1729 DEBUG(0,("str_list_make: Unable to allocate memory"));
1732 if (!sep) sep = LIST_SEP;
1738 while (next_token(&str, tok, sep, sizeof(tok))) {
1740 lsize += S_LIST_ABS;
1742 rlist = TALLOC_REALLOC_ARRAY(mem_ctx, list, char *, lsize +1);
1744 /* We need to keep the old list on error so we can free the elements
1745 if the realloc fails. */
1746 rlist = SMB_REALLOC_ARRAY_KEEP_OLD_ON_ERROR(list, char *, lsize +1);
1749 DEBUG(0,("str_list_make: Unable to allocate memory"));
1750 str_list_free(&list);
1760 memset (&list[num], 0, ((sizeof(char**)) * (S_LIST_ABS +1)));
1764 list[num] = talloc_strdup(mem_ctx, tok);
1766 list[num] = SMB_STRDUP(tok);
1770 DEBUG(0,("str_list_make: Unable to allocate memory"));
1771 str_list_free(&list);
1792 char **str_list_make_talloc(TALLOC_CTX *mem_ctx, const char *string, const char *sep)
1794 return str_list_make_internal(mem_ctx, string, sep);
1797 char **str_list_make(const char *string, const char *sep)
1799 return str_list_make_internal(NULL, string, sep);
1802 BOOL str_list_copy(char ***dest, const char **src)
1804 char **list, **rlist;
1816 lsize += S_LIST_ABS;
1817 rlist = SMB_REALLOC_ARRAY_KEEP_OLD_ON_ERROR(list, char *, lsize +1);
1819 DEBUG(0,("str_list_copy: Unable to re-allocate memory"));
1820 str_list_free(&list);
1825 memset (&list[num], 0, ((sizeof(char **)) * (S_LIST_ABS +1)));
1828 list[num] = SMB_STRDUP(src[num]);
1830 DEBUG(0,("str_list_copy: Unable to allocate memory"));
1831 str_list_free(&list);
1843 * Return true if all the elements of the list match exactly.
1845 BOOL str_list_compare(char **list1, char **list2)
1849 if (!list1 || !list2)
1850 return (list1 == list2);
1852 for (num = 0; list1[num]; num++) {
1855 if (!strcsequal(list1[num], list2[num]))
1859 return False; /* if list2 has more elements than list1 fail */
1864 static void str_list_free_internal(TALLOC_CTX *mem_ctx, char ***list)
1868 if (!list || !*list)
1871 for(; *tlist; tlist++) {
1873 TALLOC_FREE(*tlist);
1879 TALLOC_FREE(*tlist);
1885 void str_list_free_talloc(TALLOC_CTX *mem_ctx, char ***list)
1887 str_list_free_internal(mem_ctx, list);
1890 void str_list_free(char ***list)
1892 str_list_free_internal(NULL, list);
1895 /******************************************************************************
1896 *****************************************************************************/
1898 int str_list_count( const char **list )
1905 /* count the number of list members */
1907 for ( i=0; *list; i++, list++ );
1912 /******************************************************************************
1913 version of standard_sub_basic() for string lists; uses alloc_sub_basic()
1915 *****************************************************************************/
1917 BOOL str_list_sub_basic( char **list, const char *smb_name )
1923 tmpstr = alloc_sub_basic(smb_name, s);
1925 DEBUG(0,("str_list_sub_basic: alloc_sub_basic() return NULL!\n"));
1938 /******************************************************************************
1939 substritute a specific pattern in a string list
1940 *****************************************************************************/
1942 BOOL str_list_substitute(char **list, const char *pattern, const char *insert)
1945 ssize_t ls, lp, li, ld, i, d;
1954 lp = (ssize_t)strlen(pattern);
1955 li = (ssize_t)strlen(insert);
1960 ls = (ssize_t)strlen(s);
1962 while ((p = strstr_m(s, pattern))) {
1966 t = (char *) SMB_MALLOC(ls +ld +1);
1968 DEBUG(0,("str_list_substitute: Unable to allocate memory"));
1971 memcpy(t, *list, d);
1972 memcpy(t +d +li, p +lp, ls -d -lp +1);
1979 for (i = 0; i < li; i++) {
1980 switch (insert[i]) {
1992 t[d +i] = insert[i];
2005 #define IPSTR_LIST_SEP ","
2006 #define IPSTR_LIST_CHAR ','
2009 * Add ip string representation to ipstr list. Used also
2010 * as part of @function ipstr_list_make
2012 * @param ipstr_list pointer to string containing ip list;
2013 * MUST BE already allocated and IS reallocated if necessary
2014 * @param ipstr_size pointer to current size of ipstr_list (might be changed
2015 * as a result of reallocation)
2016 * @param ip IP address which is to be added to list
2017 * @return pointer to string appended with new ip and possibly
2018 * reallocated to new length
2021 char* ipstr_list_add(char** ipstr_list, const struct ip_service *service)
2023 char* new_ipstr = NULL;
2025 /* arguments checking */
2026 if (!ipstr_list || !service) return NULL;
2028 /* attempt to convert ip to a string and append colon separator to it */
2030 asprintf(&new_ipstr, "%s%s%s:%d", *ipstr_list, IPSTR_LIST_SEP,
2031 inet_ntoa(service->ip), service->port);
2032 SAFE_FREE(*ipstr_list);
2034 asprintf(&new_ipstr, "%s:%d", inet_ntoa(service->ip), service->port);
2036 *ipstr_list = new_ipstr;
2042 * Allocate and initialise an ipstr list using ip adresses
2043 * passed as arguments.
2045 * @param ipstr_list pointer to string meant to be allocated and set
2046 * @param ip_list array of ip addresses to place in the list
2047 * @param ip_count number of addresses stored in ip_list
2048 * @return pointer to allocated ip string
2051 char* ipstr_list_make(char** ipstr_list, const struct ip_service* ip_list, int ip_count)
2055 /* arguments checking */
2056 if (!ip_list && !ipstr_list) return 0;
2060 /* process ip addresses given as arguments */
2061 for (i = 0; i < ip_count; i++)
2062 *ipstr_list = ipstr_list_add(ipstr_list, &ip_list[i]);
2064 return (*ipstr_list);
2069 * Parse given ip string list into array of ip addresses
2070 * (as ip_service structures)
2071 * e.g. 192.168.1.100:389,192.168.1.78, ...
2073 * @param ipstr ip string list to be parsed
2074 * @param ip_list pointer to array of ip addresses which is
2075 * allocated by this function and must be freed by caller
2076 * @return number of succesfully parsed addresses
2079 int ipstr_list_parse(const char* ipstr_list, struct ip_service **ip_list)
2085 if (!ipstr_list || !ip_list)
2088 count = count_chars(ipstr_list, IPSTR_LIST_CHAR) + 1;
2089 if ( (*ip_list = SMB_MALLOC_ARRAY(struct ip_service, count)) == NULL ) {
2090 DEBUG(0,("ipstr_list_parse: malloc failed for %lu entries\n", (unsigned long)count));
2095 next_token(&ipstr_list, token_str, IPSTR_LIST_SEP, FSTRING_LEN) && i<count;
2098 struct in_addr addr;
2100 char *p = strchr(token_str, ':');
2107 /* convert single token to ip address */
2108 if ( (addr.s_addr = inet_addr(token_str)) == INADDR_NONE )
2111 (*ip_list)[i].ip = addr;
2112 (*ip_list)[i].port = port;
2120 * Safely free ip string list
2122 * @param ipstr_list ip string list to be freed
2125 void ipstr_list_free(char* ipstr_list)
2127 SAFE_FREE(ipstr_list);
2132 Unescape a URL encoded string, in place.
2135 void rfc1738_unescape(char *buf)
2139 while (p && *p && (p=strchr_m(p,'%'))) {
2143 if (c1 >= '0' && c1 <= '9')
2145 else if (c1 >= 'A' && c1 <= 'F')
2147 else if (c1 >= 'a' && c1 <= 'f')
2149 else {p++; continue;}
2151 if (c2 >= '0' && c2 <= '9')
2153 else if (c2 >= 'A' && c2 <= 'F')
2155 else if (c2 >= 'a' && c2 <= 'f')
2157 else {p++; continue;}
2161 memmove(p+1, p+3, strlen(p+3)+1);
2166 static const char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2169 * Decode a base64 string into a DATA_BLOB - simple and slow algorithm
2171 DATA_BLOB base64_decode_data_blob(const char *s)
2173 int bit_offset, byte_offset, idx, i, n;
2174 DATA_BLOB decoded = data_blob(s, strlen(s)+1);
2175 unsigned char *d = decoded.data;
2180 while (*s && (p=strchr_m(b64,*s))) {
2181 idx = (int)(p - b64);
2182 byte_offset = (i*6)/8;
2183 bit_offset = (i*6)%8;
2184 d[byte_offset] &= ~((1<<(8-bit_offset))-1);
2185 if (bit_offset < 3) {
2186 d[byte_offset] |= (idx << (2-bit_offset));
2189 d[byte_offset] |= (idx >> (bit_offset-2));
2190 d[byte_offset+1] = 0;
2191 d[byte_offset+1] |= (idx << (8-(bit_offset-2))) & 0xFF;
2197 if ((n > 0) && (*s == '=')) {
2207 * Decode a base64 string in-place - wrapper for the above
2209 void base64_decode_inplace(char *s)
2211 DATA_BLOB decoded = base64_decode_data_blob(s);
2213 if ( decoded.length != 0 ) {
2214 memcpy(s, decoded.data, decoded.length);
2216 /* null terminate */
2217 s[decoded.length] = '\0';
2222 data_blob_free(&decoded);
2226 * Encode a base64 string into a malloc()ed string caller to free.
2228 *From SQUID: adopted from http://ftp.sunet.se/pub2/gnu/vm/base64-encode.c with adjustments
2230 char * base64_encode_data_blob(DATA_BLOB data)
2234 size_t out_cnt, len, output_len;
2237 if (!data.length || !data.data)
2242 output_len = data.length * 2;
2243 result = SMB_MALLOC(output_len); /* get us plenty of space */
2245 while (len-- && out_cnt < (data.length * 2) - 5) {
2246 int c = (unsigned char) *(data.data++);
2249 if (char_count == 3) {
2250 result[out_cnt++] = b64[bits >> 18];
2251 result[out_cnt++] = b64[(bits >> 12) & 0x3f];
2252 result[out_cnt++] = b64[(bits >> 6) & 0x3f];
2253 result[out_cnt++] = b64[bits & 0x3f];
2260 if (char_count != 0) {
2261 bits <<= 16 - (8 * char_count);
2262 result[out_cnt++] = b64[bits >> 18];
2263 result[out_cnt++] = b64[(bits >> 12) & 0x3f];
2264 if (char_count == 1) {
2265 result[out_cnt++] = '=';
2266 result[out_cnt++] = '=';
2268 result[out_cnt++] = b64[(bits >> 6) & 0x3f];
2269 result[out_cnt++] = '=';
2272 result[out_cnt] = '\0'; /* terminate */
2276 /* read a SMB_BIG_UINT from a string */
2277 SMB_BIG_UINT STR_TO_SMB_BIG_UINT(const char *nptr, const char **entptr)
2280 SMB_BIG_UINT val = -1;
2281 const char *p = nptr;
2288 while (*p && isspace(*p))
2291 #ifdef LARGE_SMB_OFF_T
2292 sscanf(p,"%llu",&val);
2293 #else /* LARGE_SMB_OFF_T */
2294 sscanf(p,"%lu",&val);
2295 #endif /* LARGE_SMB_OFF_T */
2297 while (*p && isdigit(*p))
2305 void string_append(char **left, const char *right)
2307 int new_len = strlen(right) + 1;
2309 if (*left == NULL) {
2310 *left = SMB_MALLOC(new_len);
2313 new_len += strlen(*left);
2314 *left = SMB_REALLOC(*left, new_len);
2317 if (*left == NULL) {
2321 safe_strcat(*left, right, new_len-1);
2324 BOOL add_string_to_array(TALLOC_CTX *mem_ctx,
2325 const char *str, const char ***strings,
2328 char *dup_str = talloc_strdup(mem_ctx, str);
2330 *strings = TALLOC_REALLOC_ARRAY(mem_ctx, *strings, const char *, (*num)+1);
2332 if ((*strings == NULL) || (dup_str == NULL))
2335 (*strings)[*num] = dup_str;
2340 /* Append an sprintf'ed string. Double buffer size on demand. Usable without
2341 * error checking in between. The indiation that something weird happened is
2344 void sprintf_append(TALLOC_CTX *mem_ctx, char **string, ssize_t *len,
2345 size_t *bufsize, const char *fmt, ...)
2352 /* len<0 is an internal marker that something failed */
2356 if (*string == NULL) {
2360 if (mem_ctx != NULL)
2361 *string = TALLOC_ARRAY(mem_ctx, char, *bufsize);
2363 *string = SMB_MALLOC_ARRAY(char, *bufsize);
2365 if (*string == NULL)
2370 ret = vasprintf(&newstr, fmt, ap);
2378 while ((*len)+ret >= *bufsize) {
2381 if (*bufsize >= (1024*1024*256))
2386 if (mem_ctx != NULL) {
2387 *string = TALLOC_REALLOC_ARRAY(mem_ctx, *string, char,
2390 *string = SMB_REALLOC_ARRAY(*string, char, *bufsize);
2393 if (*string == NULL) {
2398 StrnCpy((*string)+(*len), newstr, ret);
2405 if (mem_ctx == NULL) {
2412 Returns the substring from src between the first occurrence of
2413 the char "front" and the first occurence of the char "back".
2414 Mallocs the return string which must be freed. Not for use
2415 with wide character strings.
2417 char *sstring_sub(const char *src, char front, char back)
2419 char *temp1, *temp2, *temp3;
2422 temp1 = strchr(src, front);
2423 if (temp1 == NULL) return NULL;
2424 temp2 = strchr(src, back);
2425 if (temp2 == NULL) return NULL;
2426 len = temp2 - temp1;
2427 if (len <= 0) return NULL;
2428 temp3 = (char*)SMB_MALLOC(len);
2429 if (temp3 == NULL) {
2430 DEBUG(1,("Malloc failure in sstring_sub\n"));
2433 memcpy(temp3, temp1+1, len-1);
2434 temp3[len-1] = '\0';
2438 /********************************************************************
2439 Check a string for any occurrences of a specified list of invalid
2441 ********************************************************************/
2443 BOOL validate_net_name( const char *name, const char *invalid_chars, int max_len )
2447 for ( i=0; i<max_len && name[i]; i++ ) {
2448 /* fail if strchr_m() finds one of the invalid characters */
2449 if ( name[i] && strchr_m( invalid_chars, name[i] ) ) {