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 */
60 while (ltrim && *s && strchr_m(sep,*s))
67 /* copy over the token */
69 for (quoted = False; len < bufsize && *s && (quoted || !strchr_m(sep,*s)); s++) {
78 *ptr = (*s) ? s+1 : s;
85 * Get the next token from a string, return False if none found. Handles
86 * double-quotes. This version trims leading separator characters before
87 * looking for a token.
89 BOOL next_token(const char **ptr, char *buff, const char *sep, size_t bufsize)
91 return next_token_internal(ptr, buff, sep, bufsize, True);
95 * Get the next token from a string, return False if none found. Handles
96 * double-quotes. This version does not trim leading separator characters
97 * before looking for a token.
99 BOOL next_token_no_ltrim(const char **ptr,
104 return next_token_internal(ptr, buff, sep, bufsize, False);
108 This is like next_token but is not re-entrant and "remembers" the first
109 parameter so you can pass NULL. This is useful for user interface code
110 but beware the fact that it is not re-entrant!
113 static const char *last_ptr=NULL;
115 BOOL next_token_nr(const char **ptr,char *buff, const char *sep, size_t bufsize)
121 ret = next_token(ptr, buff, sep, bufsize);
126 static uint16 tmpbuf[sizeof(pstring)];
128 void set_first_token(char *ptr)
134 Convert list of tokens to array; dependent on above routine.
135 Uses last_ptr from above - bit of a hack.
138 char **toktocliplist(int *ctok, const char *sep)
140 char *s=(char *)last_ptr;
147 while(*s && strchr_m(sep,*s))
156 while(*s && (!strchr_m(sep,*s)))
158 while(*s && strchr_m(sep,*s))
165 if (!(ret=iret=SMB_MALLOC_ARRAY(char *,ictok+1)))
183 * Case insensitive string compararison.
185 * iconv does not directly give us a way to compare strings in
186 * arbitrary unix character sets -- all we can is convert and then
187 * compare. This is expensive.
189 * As an optimization, we do a first pass that considers only the
190 * prefix of the strings that is entirely 7-bit. Within this, we
191 * check whether they have the same value.
193 * Hopefully this will often give the answer without needing to copy.
194 * In particular it should speed comparisons to literal ascii strings
195 * or comparisons of strings that are "obviously" different.
197 * If we find a non-ascii character we fall back to converting via
200 * This should never be slower than convering the whole thing, and
203 * A different optimization would be to compare for bitwise equality
204 * in the binary encoding. (It would be possible thought hairy to do
205 * both simultaneously.) But in that case if they turn out to be
206 * different, we'd need to restart the whole thing.
208 * Even better is to implement strcasecmp for each encoding and use a
211 int StrCaseCmp(const char *s, const char *t)
216 smb_ucs2_t *buffer_s, *buffer_t;
219 for (ps = s, pt = t; ; ps++, pt++) {
223 return 0; /* both ended */
225 return -1; /* s is a prefix */
227 return +1; /* t is a prefix */
228 else if ((*ps & 0x80) || (*pt & 0x80))
229 /* not ascii anymore, do it the hard way from here on in */
232 us = toupper_ascii(*ps);
233 ut = toupper_ascii(*pt);
242 size = push_ucs2_allocate(&buffer_s, ps);
243 if (size == (size_t)-1) {
244 return strcmp(ps, pt);
245 /* Not quite the right answer, but finding the right one
246 under this failure case is expensive, and it's pretty close */
249 size = push_ucs2_allocate(&buffer_t, pt);
250 if (size == (size_t)-1) {
252 return strcmp(ps, pt);
253 /* Not quite the right answer, but finding the right one
254 under this failure case is expensive, and it's pretty close */
257 ret = strcasecmp_w(buffer_s, buffer_t);
265 Case insensitive string compararison, length limited.
267 int StrnCaseCmp(const char *s, const char *t, size_t n)
270 unix_strupper(s, strlen(s)+1, buf1, sizeof(buf1));
271 unix_strupper(t, strlen(t)+1, buf2, sizeof(buf2));
272 return strncmp(buf1,buf2,n);
278 * @note The comparison is case-insensitive.
280 BOOL strequal(const char *s1, const char *s2)
287 return(StrCaseCmp(s1,s2)==0);
291 * Compare 2 strings up to and including the nth char.
293 * @note The comparison is case-insensitive.
295 BOOL strnequal(const char *s1,const char *s2,size_t n)
299 if (!s1 || !s2 || !n)
302 return(StrnCaseCmp(s1,s2,n)==0);
306 Compare 2 strings (case sensitive).
309 BOOL strcsequal(const char *s1,const char *s2)
316 return(strcmp(s1,s2)==0);
320 Do a case-insensitive, whitespace-ignoring string compare.
323 int strwicmp(const char *psz1, const char *psz2)
325 /* if BOTH strings are NULL, return TRUE, if ONE is NULL return */
326 /* appropriate value. */
329 else if (psz1 == NULL)
331 else if (psz2 == NULL)
334 /* sync the strings on first non-whitespace */
336 while (isspace((int)*psz1))
338 while (isspace((int)*psz2))
340 if (toupper_ascii(*psz1) != toupper_ascii(*psz2) || *psz1 == '\0'
346 return (*psz1 - *psz2);
351 Convert a string to upper case, but don't modify it.
354 char *strupper_static(const char *s)
365 Convert a string to "normal" form.
368 void strnorm(char *s, int case_default)
370 if (case_default == CASE_UPPER)
377 Check if a string is in "normal" case.
380 BOOL strisnormal(const char *s, int case_default)
382 if (case_default == CASE_UPPER)
383 return(!strhaslower(s));
385 return(!strhasupper(s));
391 NOTE: oldc and newc must be 7 bit characters
394 void string_replace( pstring s, char oldc, char newc )
398 /* this is quite a common operation, so we want it to be
399 fast. We optimise for the ascii case, knowing that all our
400 supported multi-byte character sets are ascii-compatible
401 (ie. they match for the first 128 chars) */
403 for (p = s; *p; p++) {
404 if (*p & 0x80) /* mb string - slow path. */
413 /* Slow (mb) path. */
414 #ifdef BROKEN_UNICODE_COMPOSE_CHARACTERS
415 /* With compose characters we must restart from the beginning. JRA. */
418 push_ucs2(NULL, tmpbuf, p, sizeof(tmpbuf), STR_TERMINATE);
419 string_replace_w(tmpbuf, UCS2_CHAR(oldc), UCS2_CHAR(newc));
420 pull_ucs2(NULL, p, tmpbuf, -1, sizeof(tmpbuf), STR_TERMINATE);
424 Skip past some strings in a buffer.
427 char *skip_string(char *buf,size_t n)
430 buf += strlen(buf) + 1;
435 Count the number of characters in a string. Normally this will
436 be the same as the number of bytes in a string for single byte strings,
437 but will be different for multibyte.
440 size_t str_charnum(const char *s)
442 uint16 tmpbuf2[sizeof(pstring)];
443 push_ucs2(NULL, tmpbuf2,s, sizeof(tmpbuf2), STR_TERMINATE);
444 return strlen_w(tmpbuf2);
448 Count the number of characters in a string. Normally this will
449 be the same as the number of bytes in a string for single byte strings,
450 but will be different for multibyte.
453 size_t str_ascii_charnum(const char *s)
456 push_ascii(tmpbuf2, s, sizeof(tmpbuf2), STR_TERMINATE);
457 return strlen(tmpbuf2);
460 BOOL trim_char(char *s,char cfront,char cback)
466 /* Ignore null or empty strings. */
467 if (!s || (s[0] == '\0'))
471 while (*fp && *fp == cfront)
474 /* We ate the string. */
482 ep = fp + strlen(fp) - 1;
484 /* Attempt ascii only. Bail for mb strings. */
485 while ((ep >= fp) && (*ep == cback)) {
487 if ((ep > fp) && (((unsigned char)ep[-1]) & 0x80)) {
488 /* Could be mb... bail back to tim_string. */
496 return trim_string(s, cfront ? fs : NULL, bs);
502 /* We ate the string. */
509 memmove(s, fp, ep-fp+2);
514 Trim the specified elements off the front and back of a string.
517 BOOL trim_string(char *s,const char *front,const char *back)
524 /* Ignore null or empty strings. */
525 if (!s || (s[0] == '\0'))
528 front_len = front? strlen(front) : 0;
529 back_len = back? strlen(back) : 0;
534 while (len && strncmp(s, front, front_len)==0) {
535 /* Must use memmove here as src & dest can
536 * easily overlap. Found by valgrind. JRA. */
537 memmove(s, s+front_len, (len-front_len)+1);
544 while ((len >= back_len) && strncmp(s+len-back_len,back,back_len)==0) {
545 s[len-back_len]='\0';
554 Does a string have any uppercase chars in it?
557 BOOL strhasupper(const char *s)
560 push_ucs2(NULL, tmpbuf,s, sizeof(tmpbuf), STR_TERMINATE);
561 for(ptr=tmpbuf;*ptr;ptr++)
568 Does a string have any lowercase chars in it?
571 BOOL strhaslower(const char *s)
574 push_ucs2(NULL, tmpbuf,s, sizeof(tmpbuf), STR_TERMINATE);
575 for(ptr=tmpbuf;*ptr;ptr++)
582 Find the number of 'c' chars in a string
585 size_t count_chars(const char *s,char c)
589 smb_ucs2_t *alloc_tmpbuf = NULL;
591 if (push_ucs2_allocate(&alloc_tmpbuf, s) == (size_t)-1) {
595 for(count=0,ptr=alloc_tmpbuf;*ptr;ptr++)
596 if(*ptr==UCS2_CHAR(c))
599 SAFE_FREE(alloc_tmpbuf);
604 Safe string copy into a known length string. maxlength does not
605 include the terminating zero.
608 char *safe_strcpy_fn(const char *fn, int line, char *dest,const char *src, size_t maxlength)
613 DEBUG(0,("ERROR: NULL dest in safe_strcpy, called from [%s][%d]\n", fn, line));
618 clobber_region(fn,line,dest, maxlength+1);
626 len = strnlen(src, maxlength+1);
628 if (len > maxlength) {
629 DEBUG(0,("ERROR: string overflow by %lu (%lu - %lu) in safe_strcpy [%.50s]\n",
630 (unsigned long)(len-maxlength), (unsigned long)len,
631 (unsigned long)maxlength, src));
635 memmove(dest, src, len);
641 Safe string cat into a string. maxlength does not
642 include the terminating zero.
644 char *safe_strcat_fn(const char *fn, int line, char *dest, const char *src, size_t maxlength)
646 size_t src_len, dest_len;
649 DEBUG(0,("ERROR: NULL dest in safe_strcat, called from [%s][%d]\n", fn, line));
656 src_len = strnlen(src, maxlength + 1);
657 dest_len = strnlen(dest, maxlength + 1);
660 clobber_region(fn, line, dest + dest_len, maxlength + 1 - dest_len);
663 if (src_len + dest_len > maxlength) {
664 DEBUG(0,("ERROR: string overflow by %d in safe_strcat [%.50s]\n",
665 (int)(src_len + dest_len - maxlength), src));
666 if (maxlength > dest_len) {
667 memcpy(&dest[dest_len], src, maxlength - dest_len);
673 memcpy(&dest[dest_len], src, src_len);
674 dest[dest_len + src_len] = 0;
679 Paranoid strcpy into a buffer of given length (includes terminating
680 zero. Strips out all but 'a-Z0-9' and the character in other_safe_chars
681 and replaces with '_'. Deliberately does *NOT* check for multibyte
682 characters. Don't change it !
684 char *alpha_strcpy_fn(const char *fn, int line, char *dest, const char *src, const char *other_safe_chars, size_t maxlength)
689 clobber_region(fn, line, dest, maxlength);
693 DEBUG(0,("ERROR: NULL dest in alpha_strcpy, called from [%s][%d]\n", fn, line));
703 if (len >= maxlength)
706 if (!other_safe_chars)
707 other_safe_chars = "";
709 for(i = 0; i < len; i++) {
710 int val = (src[i] & 0xff);
711 if (isupper_ascii(val) || islower_ascii(val) || isdigit(val) || strchr_m(other_safe_chars, val))
723 Like strncpy but always null terminates. Make sure there is room!
724 The variable n should always be one less than the available size.
726 char *StrnCpy_fn(const char *fn, int line,char *dest,const char *src,size_t n)
731 clobber_region(fn, line, dest, n+1);
735 DEBUG(0,("ERROR: NULL dest in StrnCpy, called from [%s][%d]\n", fn, line));
744 while (n-- && (*d = *src)) {
755 Like strncpy but copies up to the character marker. always null terminates.
756 returns a pointer to the character marker in the source string (src).
759 static char *strncpyn(char *dest, const char *src, size_t n, char c)
765 clobber_region(dest, n+1);
767 p = strchr_m(src, c);
769 DEBUG(5, ("strncpyn: separator character (%c) not found\n", c));
773 str_len = PTR_DIFF(p, src);
774 strncpy(dest, src, MIN(n, str_len));
775 dest[str_len] = '\0';
782 Routine to get hex characters and turn them into a 16 byte array.
783 the array can be variable length, and any non-hex-numeric
784 characters are skipped. "0xnn" or "0Xnn" is specially catered
787 valid examples: "0A5D15"; "0x15, 0x49, 0xa2"; "59\ta9\te3\n"
791 size_t strhex_to_str(char *p, size_t len, const char *strhex)
794 size_t num_chars = 0;
795 unsigned char lonybble, hinybble;
796 const char *hexchars = "0123456789ABCDEF";
797 char *p1 = NULL, *p2 = NULL;
799 for (i = 0; i < len && strhex[i] != 0; i++) {
800 if (strnequal(hexchars, "0x", 2)) {
801 i++; /* skip two chars */
805 if (!(p1 = strchr_m(hexchars, toupper_ascii(strhex[i]))))
808 i++; /* next hex digit */
810 if (!(p2 = strchr_m(hexchars, toupper_ascii(strhex[i]))))
813 /* get the two nybbles */
814 hinybble = PTR_DIFF(p1, hexchars);
815 lonybble = PTR_DIFF(p2, hexchars);
817 p[num_chars] = (hinybble << 4) | lonybble;
826 DATA_BLOB strhex_to_data_blob(TALLOC_CTX *mem_ctx, const char *strhex)
831 ret_blob = data_blob_talloc(mem_ctx, NULL, strlen(strhex)/2+1);
833 ret_blob = data_blob(NULL, strlen(strhex)/2+1);
835 ret_blob.length = strhex_to_str((char*)ret_blob.data,
843 * Routine to print a buffer as HEX digits, into an allocated string.
846 char *hex_encode(TALLOC_CTX *mem_ctx, const unsigned char *buff_in, size_t len)
851 hex_buffer = TALLOC_ARRAY(mem_ctx, char, (len*2)+1);
853 for (i = 0; i < len; i++)
854 slprintf(&hex_buffer[i*2], 3, "%02X", buff_in[i]);
860 Check if a string is part of a list.
863 BOOL in_list(const char *s, const char *list, BOOL casesensitive)
871 while (next_token(&p,tok,LIST_SEP,sizeof(tok))) {
873 if (strcmp(tok,s) == 0)
876 if (StrCaseCmp(tok,s) == 0)
883 /* this is used to prevent lots of mallocs of size 1 */
884 static const char *null_string = "";
887 Set a string value, allocing the space for the string
890 static BOOL string_init(char **dest,const char *src)
900 *dest = CONST_DISCARD(char*, null_string);
902 (*dest) = SMB_STRDUP(src);
903 if ((*dest) == NULL) {
904 DEBUG(0,("Out of memory in string_init\n"));
915 void string_free(char **s)
919 if (*s == null_string)
925 Set a string value, deallocating any existing space, and allocing the space
929 BOOL string_set(char **dest,const char *src)
932 return(string_init(dest,src));
936 Substitute a string for a pattern in another string. Make sure there is
939 This routine looks for pattern in s and replaces it with
940 insert. It may do multiple replacements or just one.
942 Any of " ; ' $ or ` in the insert string are replaced with _
943 if len==0 then the string cannot be extended. This is different from the old
944 use of len==0 which was for no length checks to be done.
947 void string_sub2(char *s,const char *pattern, const char *insert, size_t len,
948 BOOL remove_unsafe_characters, BOOL replace_once, BOOL allow_trailing_dollar)
953 if (!insert || !pattern || !*pattern || !s)
956 ls = (ssize_t)strlen(s);
957 lp = (ssize_t)strlen(pattern);
958 li = (ssize_t)strlen(insert);
961 len = ls + 1; /* len is number of *bytes* */
963 while (lp <= ls && (p = strstr_m(s,pattern))) {
964 if (ls + (li-lp) >= len) {
965 DEBUG(0,("ERROR: string overflow by %d in string_sub(%.50s, %d)\n",
966 (int)(ls + (li-lp) - len),
971 memmove(p+li,p+lp,strlen(p+lp)+1);
980 /* allow a trailing $ (as in machine accounts) */
981 if (allow_trailing_dollar && (i == li - 1 )) {
988 if ( remove_unsafe_characters ) {
990 /* yes this break should be here since we want to
991 fall throw if not replacing unsafe chars */
1006 void string_sub_once(char *s, const char *pattern, const char *insert, size_t len)
1008 string_sub2( s, pattern, insert, len, True, True, False );
1011 void string_sub(char *s,const char *pattern, const char *insert, size_t len)
1013 string_sub2( s, pattern, insert, len, True, False, False );
1016 void fstring_sub(char *s,const char *pattern,const char *insert)
1018 string_sub(s, pattern, insert, sizeof(fstring));
1021 void pstring_sub(char *s,const char *pattern,const char *insert)
1023 string_sub(s, pattern, insert, sizeof(pstring));
1027 Similar to string_sub, but it will accept only allocated strings
1028 and may realloc them so pay attention at what you pass on no
1029 pointers inside strings, no pstrings or const may be passed
1033 char *realloc_string_sub(char *string, const char *pattern,
1038 ssize_t ls,lp,li,ld, i;
1040 if (!insert || !pattern || !*pattern || !string || !*string)
1045 in = SMB_STRDUP(insert);
1047 DEBUG(0, ("realloc_string_sub: out of memory!\n"));
1050 ls = (ssize_t)strlen(s);
1051 lp = (ssize_t)strlen(pattern);
1052 li = (ssize_t)strlen(insert);
1054 for (i=0;i<li;i++) {
1071 while ((p = strstr_m(s,pattern))) {
1073 int offset = PTR_DIFF(s,string);
1074 string = SMB_REALLOC(string, ls + ld + 1);
1076 DEBUG(0, ("realloc_string_sub: out of memory!\n"));
1080 p = string + offset + (p - s);
1083 memmove(p+li,p+lp,strlen(p+lp)+1);
1093 /* Same as string_sub, but returns a talloc'ed string */
1095 char *talloc_string_sub(TALLOC_CTX *mem_ctx, const char *src,
1096 const char *pattern, const char *insert)
1101 ssize_t ls,lp,li,ld, i;
1103 if (!insert || !pattern || !*pattern || !src || !*src)
1106 string = talloc_strdup(mem_ctx, src);
1107 if (string == NULL) {
1108 DEBUG(0, ("talloc_strdup failed\n"));
1114 in = SMB_STRDUP(insert);
1116 DEBUG(0, ("talloc_string_sub: out of memory!\n"));
1119 ls = (ssize_t)strlen(s);
1120 lp = (ssize_t)strlen(pattern);
1121 li = (ssize_t)strlen(insert);
1123 for (i=0;i<li;i++) {
1140 while ((p = strstr_m(s,pattern))) {
1142 int offset = PTR_DIFF(s,string);
1143 string = TALLOC_REALLOC(mem_ctx, string, ls + ld + 1);
1145 DEBUG(0, ("talloc_string_sub: out of "
1150 p = string + offset + (p - s);
1153 memmove(p+li,p+lp,strlen(p+lp)+1);
1164 Similar to string_sub() but allows for any character to be substituted.
1166 if len==0 then the string cannot be extended. This is different from the old
1167 use of len==0 which was for no length checks to be done.
1170 void all_string_sub(char *s,const char *pattern,const char *insert, size_t len)
1175 if (!insert || !pattern || !s)
1178 ls = (ssize_t)strlen(s);
1179 lp = (ssize_t)strlen(pattern);
1180 li = (ssize_t)strlen(insert);
1186 len = ls + 1; /* len is number of *bytes* */
1188 while (lp <= ls && (p = strstr_m(s,pattern))) {
1189 if (ls + (li-lp) >= len) {
1190 DEBUG(0,("ERROR: string overflow by %d in all_string_sub(%.50s, %d)\n",
1191 (int)(ls + (li-lp) - len),
1192 pattern, (int)len));
1196 memmove(p+li,p+lp,strlen(p+lp)+1);
1198 memcpy(p, insert, li);
1205 Similar to all_string_sub but for unicode strings.
1206 Return a new allocated unicode string.
1207 similar to string_sub() but allows for any character to be substituted.
1211 static smb_ucs2_t *all_string_sub_w(const smb_ucs2_t *s, const smb_ucs2_t *pattern,
1212 const smb_ucs2_t *insert)
1215 const smb_ucs2_t *sp;
1216 size_t lr, lp, li, lt;
1218 if (!insert || !pattern || !*pattern || !s)
1221 lt = (size_t)strlen_w(s);
1222 lp = (size_t)strlen_w(pattern);
1223 li = (size_t)strlen_w(insert);
1226 const smb_ucs2_t *st = s;
1228 while ((sp = strstr_w(st, pattern))) {
1234 r = rp = SMB_MALLOC_ARRAY(smb_ucs2_t, lt + 1);
1236 DEBUG(0, ("all_string_sub_w: out of memory!\n"));
1240 while ((sp = strstr_w(s, pattern))) {
1241 memcpy(rp, s, (sp - s));
1242 rp += ((sp - s) / sizeof(smb_ucs2_t));
1243 memcpy(rp, insert, (li * sizeof(smb_ucs2_t)));
1247 lr = ((rp - r) / sizeof(smb_ucs2_t));
1249 memcpy(rp, s, ((lt - lr) * sizeof(smb_ucs2_t)));
1257 smb_ucs2_t *all_string_sub_wa(smb_ucs2_t *s, const char *pattern,
1262 if (!insert || !pattern || !s)
1264 push_ucs2(NULL, p, pattern, sizeof(wpstring) - 1, STR_TERMINATE);
1265 push_ucs2(NULL, i, insert, sizeof(wpstring) - 1, STR_TERMINATE);
1266 return all_string_sub_w(s, p, i);
1271 Splits out the front and back at a separator.
1274 static void split_at_last_component(char *path, char *front, char sep, char *back)
1276 char *p = strrchr_m(path, sep);
1282 pstrcpy(front, path);
1296 Write an octal as a string.
1299 const char *octal_string(int i)
1301 static char ret[64];
1304 slprintf(ret, sizeof(ret)-1, "0%o", i);
1310 Truncate a string at a specified length.
1313 char *string_truncate(char *s, unsigned int length)
1315 if (s && strlen(s) > length)
1321 Strchr and strrchr_m are very hard to do on general multi-byte strings.
1322 We convert via ucs2 for now.
1325 char *strchr_m(const char *src, char c)
1332 /* characters below 0x3F are guaranteed to not appear in
1333 non-initial position in multi-byte charsets */
1334 if ((c & 0xC0) == 0) {
1335 return strchr(src, c);
1338 /* this is quite a common operation, so we want it to be
1339 fast. We optimise for the ascii case, knowing that all our
1340 supported multi-byte character sets are ascii-compatible
1341 (ie. they match for the first 128 chars) */
1343 for (s = src; *s && !(((unsigned char)s[0]) & 0x80); s++) {
1351 #ifdef BROKEN_UNICODE_COMPOSE_CHARACTERS
1352 /* With compose characters we must restart from the beginning. JRA. */
1356 push_ucs2(NULL, ws, s, sizeof(ws), STR_TERMINATE);
1357 p = strchr_w(ws, UCS2_CHAR(c));
1361 pull_ucs2_pstring(s2, ws);
1362 return (char *)(s+strlen(s2));
1365 char *strrchr_m(const char *s, char c)
1367 /* characters below 0x3F are guaranteed to not appear in
1368 non-initial position in multi-byte charsets */
1369 if ((c & 0xC0) == 0) {
1370 return strrchr(s, c);
1373 /* this is quite a common operation, so we want it to be
1374 fast. We optimise for the ascii case, knowing that all our
1375 supported multi-byte character sets are ascii-compatible
1376 (ie. they match for the first 128 chars). Also, in Samba
1377 we only search for ascii characters in 'c' and that
1378 in all mb character sets with a compound character
1379 containing c, if 'c' is not a match at position
1380 p, then p[-1] > 0x7f. JRA. */
1383 size_t len = strlen(s);
1385 BOOL got_mb = False;
1392 /* Could be a match. Part of a multibyte ? */
1393 if ((cp > s) && (((unsigned char)cp[-1]) & 0x80)) {
1394 /* Yep - go slow :-( */
1398 /* No - we have a match ! */
1401 } while (cp-- != s);
1406 /* String contained a non-ascii char. Slow path. */
1412 push_ucs2(NULL, ws, s, sizeof(ws), STR_TERMINATE);
1413 p = strrchr_w(ws, UCS2_CHAR(c));
1417 pull_ucs2_pstring(s2, ws);
1418 return (char *)(s+strlen(s2));
1422 /***********************************************************************
1423 Return the equivalent of doing strrchr 'n' times - always going
1425 ***********************************************************************/
1427 char *strnrchr_m(const char *s, char c, unsigned int n)
1433 push_ucs2(NULL, ws, s, sizeof(ws), STR_TERMINATE);
1434 p = strnrchr_w(ws, UCS2_CHAR(c), n);
1438 pull_ucs2_pstring(s2, ws);
1439 return (char *)(s+strlen(s2));
1442 /***********************************************************************
1443 strstr_m - We convert via ucs2 for now.
1444 ***********************************************************************/
1446 char *strstr_m(const char *src, const char *findstr)
1449 smb_ucs2_t *src_w, *find_w;
1454 size_t findstr_len = 0;
1456 /* for correctness */
1461 /* Samba does single character findstr calls a *lot*. */
1462 if (findstr[1] == '\0')
1463 return strchr_m(src, *findstr);
1465 /* We optimise for the ascii case, knowing that all our
1466 supported multi-byte character sets are ascii-compatible
1467 (ie. they match for the first 128 chars) */
1469 for (s = src; *s && !(((unsigned char)s[0]) & 0x80); s++) {
1470 if (*s == *findstr) {
1472 findstr_len = strlen(findstr);
1474 if (strncmp(s, findstr, findstr_len) == 0) {
1483 #if 1 /* def BROKEN_UNICODE_COMPOSE_CHARACTERS */
1484 /* 'make check' fails unless we do this */
1486 /* With compose characters we must restart from the beginning. JRA. */
1490 if (push_ucs2_allocate(&src_w, src) == (size_t)-1) {
1491 DEBUG(0,("strstr_m: src malloc fail\n"));
1495 if (push_ucs2_allocate(&find_w, findstr) == (size_t)-1) {
1497 DEBUG(0,("strstr_m: find malloc fail\n"));
1501 p = strstr_w(src_w, find_w);
1510 if (pull_ucs2_allocate(&s2, src_w) == (size_t)-1) {
1513 DEBUG(0,("strstr_m: dest malloc fail\n"));
1516 retp = (char *)(s+strlen(s2));
1524 Convert a string to lower case.
1527 void strlower_m(char *s)
1532 /* this is quite a common operation, so we want it to be
1533 fast. We optimise for the ascii case, knowing that all our
1534 supported multi-byte character sets are ascii-compatible
1535 (ie. they match for the first 128 chars) */
1537 while (*s && !(((unsigned char)s[0]) & 0x80)) {
1538 *s = tolower_ascii((unsigned char)*s);
1545 /* I assume that lowercased string takes the same number of bytes
1546 * as source string even in UTF-8 encoding. (VIV) */
1547 len = strlen(s) + 1;
1550 unix_strlower(s,len,s,len);
1551 /* Catch mb conversion errors that may not terminate. */
1558 Convert a string to upper case.
1561 void strupper_m(char *s)
1566 /* this is quite a common operation, so we want it to be
1567 fast. We optimise for the ascii case, knowing that all our
1568 supported multi-byte character sets are ascii-compatible
1569 (ie. they match for the first 128 chars) */
1571 while (*s && !(((unsigned char)s[0]) & 0x80)) {
1572 *s = toupper_ascii((unsigned char)*s);
1579 /* I assume that lowercased string takes the same number of bytes
1580 * as source string even in multibyte encoding. (VIV) */
1581 len = strlen(s) + 1;
1584 unix_strupper(s,len,s,len);
1585 /* Catch mb conversion errors that may not terminate. */
1592 Return a RFC2254 binary string representation of a buffer.
1593 Used in LDAP filters.
1597 char *binary_string_rfc2254(char *buf, int len)
1601 const char *hex = "0123456789ABCDEF";
1602 s = SMB_MALLOC(len * 3 + 1);
1605 for (j=i=0;i<len;i++) {
1607 s[j+1] = hex[((unsigned char)buf[i]) >> 4];
1608 s[j+2] = hex[((unsigned char)buf[i]) & 0xF];
1615 char *binary_string(char *buf, int len)
1619 const char *hex = "0123456789ABCDEF";
1620 s = SMB_MALLOC(len * 2 + 1);
1623 for (j=i=0;i<len;i++) {
1624 s[j] = hex[((unsigned char)buf[i]) >> 4];
1625 s[j+1] = hex[((unsigned char)buf[i]) & 0xF];
1632 Just a typesafety wrapper for snprintf into a pstring.
1635 int pstr_sprintf(pstring s, const char *fmt, ...)
1641 ret = vsnprintf(s, PSTRING_LEN, fmt, ap);
1648 Just a typesafety wrapper for snprintf into a fstring.
1651 int fstr_sprintf(fstring s, const char *fmt, ...)
1657 ret = vsnprintf(s, FSTRING_LEN, fmt, ap);
1663 #if !defined(HAVE_STRNDUP) || defined(BROKEN_STRNDUP)
1665 Some platforms don't have strndup.
1667 #if defined(PARANOID_MALLOC_CHECKER)
1671 char *strndup(const char *s, size_t n)
1676 ret = SMB_MALLOC(n+1);
1685 #if defined(PARANOID_MALLOC_CHECKER)
1686 #define strndup(s,n) __ERROR_DONT_USE_STRNDUP_DIRECTLY
1691 #if !defined(HAVE_STRNLEN) || defined(BROKEN_STRNLEN)
1693 Some platforms don't have strnlen
1696 size_t strnlen(const char *s, size_t n)
1699 for (i=0; i<n && s[i] != '\0'; i++)
1706 List of Strings manipulation functions
1709 #define S_LIST_ABS 16 /* List Allocation Block Size */
1711 static char **str_list_make_internal(TALLOC_CTX *mem_ctx, const char *string, const char *sep)
1713 char **list, **rlist;
1719 if (!string || !*string)
1722 s = talloc_strdup(mem_ctx, string);
1724 s = SMB_STRDUP(string);
1727 DEBUG(0,("str_list_make: Unable to allocate memory"));
1730 if (!sep) sep = LIST_SEP;
1736 while (next_token(&str, tok, sep, sizeof(tok))) {
1738 lsize += S_LIST_ABS;
1740 rlist = TALLOC_REALLOC_ARRAY(mem_ctx, list, char *, lsize +1);
1742 /* We need to keep the old list on error so we can free the elements
1743 if the realloc fails. */
1744 rlist = SMB_REALLOC_ARRAY_KEEP_OLD_ON_ERROR(list, char *, lsize +1);
1747 DEBUG(0,("str_list_make: Unable to allocate memory"));
1748 str_list_free(&list);
1758 memset (&list[num], 0, ((sizeof(char**)) * (S_LIST_ABS +1)));
1762 list[num] = talloc_strdup(mem_ctx, tok);
1764 list[num] = SMB_STRDUP(tok);
1768 DEBUG(0,("str_list_make: Unable to allocate memory"));
1769 str_list_free(&list);
1790 char **str_list_make_talloc(TALLOC_CTX *mem_ctx, const char *string, const char *sep)
1792 return str_list_make_internal(mem_ctx, string, sep);
1795 char **str_list_make(const char *string, const char *sep)
1797 return str_list_make_internal(NULL, string, sep);
1800 BOOL str_list_copy(char ***dest, const char **src)
1802 char **list, **rlist;
1814 lsize += S_LIST_ABS;
1815 rlist = SMB_REALLOC_ARRAY_KEEP_OLD_ON_ERROR(list, char *, lsize +1);
1817 DEBUG(0,("str_list_copy: Unable to re-allocate memory"));
1818 str_list_free(&list);
1823 memset (&list[num], 0, ((sizeof(char **)) * (S_LIST_ABS +1)));
1826 list[num] = SMB_STRDUP(src[num]);
1828 DEBUG(0,("str_list_copy: Unable to allocate memory"));
1829 str_list_free(&list);
1841 * Return true if all the elements of the list match exactly.
1843 BOOL str_list_compare(char **list1, char **list2)
1847 if (!list1 || !list2)
1848 return (list1 == list2);
1850 for (num = 0; list1[num]; num++) {
1853 if (!strcsequal(list1[num], list2[num]))
1857 return False; /* if list2 has more elements than list1 fail */
1862 static void str_list_free_internal(TALLOC_CTX *mem_ctx, char ***list)
1866 if (!list || !*list)
1869 for(; *tlist; tlist++) {
1871 TALLOC_FREE(*tlist);
1877 TALLOC_FREE(*tlist);
1883 void str_list_free_talloc(TALLOC_CTX *mem_ctx, char ***list)
1885 str_list_free_internal(mem_ctx, list);
1888 void str_list_free(char ***list)
1890 str_list_free_internal(NULL, list);
1893 /******************************************************************************
1894 *****************************************************************************/
1896 int str_list_count( const char **list )
1903 /* count the number of list members */
1905 for ( i=0; *list; i++, list++ );
1910 /******************************************************************************
1911 version of standard_sub_basic() for string lists; uses alloc_sub_basic()
1913 *****************************************************************************/
1915 BOOL str_list_sub_basic( char **list, const char *smb_name )
1921 tmpstr = alloc_sub_basic(smb_name, s);
1923 DEBUG(0,("str_list_sub_basic: alloc_sub_basic() return NULL!\n"));
1936 /******************************************************************************
1937 substritute a specific pattern in a string list
1938 *****************************************************************************/
1940 BOOL str_list_substitute(char **list, const char *pattern, const char *insert)
1943 ssize_t ls, lp, li, ld, i, d;
1952 lp = (ssize_t)strlen(pattern);
1953 li = (ssize_t)strlen(insert);
1958 ls = (ssize_t)strlen(s);
1960 while ((p = strstr_m(s, pattern))) {
1964 t = (char *) SMB_MALLOC(ls +ld +1);
1966 DEBUG(0,("str_list_substitute: Unable to allocate memory"));
1969 memcpy(t, *list, d);
1970 memcpy(t +d +li, p +lp, ls -d -lp +1);
1977 for (i = 0; i < li; i++) {
1978 switch (insert[i]) {
1990 t[d +i] = insert[i];
2003 #define IPSTR_LIST_SEP ","
2004 #define IPSTR_LIST_CHAR ','
2007 * Add ip string representation to ipstr list. Used also
2008 * as part of @function ipstr_list_make
2010 * @param ipstr_list pointer to string containing ip list;
2011 * MUST BE already allocated and IS reallocated if necessary
2012 * @param ipstr_size pointer to current size of ipstr_list (might be changed
2013 * as a result of reallocation)
2014 * @param ip IP address which is to be added to list
2015 * @return pointer to string appended with new ip and possibly
2016 * reallocated to new length
2019 char* ipstr_list_add(char** ipstr_list, const struct ip_service *service)
2021 char* new_ipstr = NULL;
2023 /* arguments checking */
2024 if (!ipstr_list || !service) return NULL;
2026 /* attempt to convert ip to a string and append colon separator to it */
2028 asprintf(&new_ipstr, "%s%s%s:%d", *ipstr_list, IPSTR_LIST_SEP,
2029 inet_ntoa(service->ip), service->port);
2030 SAFE_FREE(*ipstr_list);
2032 asprintf(&new_ipstr, "%s:%d", inet_ntoa(service->ip), service->port);
2034 *ipstr_list = new_ipstr;
2040 * Allocate and initialise an ipstr list using ip adresses
2041 * passed as arguments.
2043 * @param ipstr_list pointer to string meant to be allocated and set
2044 * @param ip_list array of ip addresses to place in the list
2045 * @param ip_count number of addresses stored in ip_list
2046 * @return pointer to allocated ip string
2049 char* ipstr_list_make(char** ipstr_list, const struct ip_service* ip_list, int ip_count)
2053 /* arguments checking */
2054 if (!ip_list && !ipstr_list) return 0;
2058 /* process ip addresses given as arguments */
2059 for (i = 0; i < ip_count; i++)
2060 *ipstr_list = ipstr_list_add(ipstr_list, &ip_list[i]);
2062 return (*ipstr_list);
2067 * Parse given ip string list into array of ip addresses
2068 * (as ip_service structures)
2069 * e.g. 192.168.1.100:389,192.168.1.78, ...
2071 * @param ipstr ip string list to be parsed
2072 * @param ip_list pointer to array of ip addresses which is
2073 * allocated by this function and must be freed by caller
2074 * @return number of succesfully parsed addresses
2077 int ipstr_list_parse(const char* ipstr_list, struct ip_service **ip_list)
2083 if (!ipstr_list || !ip_list)
2086 count = count_chars(ipstr_list, IPSTR_LIST_CHAR) + 1;
2087 if ( (*ip_list = SMB_MALLOC_ARRAY(struct ip_service, count)) == NULL ) {
2088 DEBUG(0,("ipstr_list_parse: malloc failed for %lu entries\n", (unsigned long)count));
2093 next_token(&ipstr_list, token_str, IPSTR_LIST_SEP, FSTRING_LEN) && i<count;
2096 struct in_addr addr;
2098 char *p = strchr(token_str, ':');
2105 /* convert single token to ip address */
2106 if ( (addr.s_addr = inet_addr(token_str)) == INADDR_NONE )
2109 (*ip_list)[i].ip = addr;
2110 (*ip_list)[i].port = port;
2118 * Safely free ip string list
2120 * @param ipstr_list ip string list to be freed
2123 void ipstr_list_free(char* ipstr_list)
2125 SAFE_FREE(ipstr_list);
2130 Unescape a URL encoded string, in place.
2133 void rfc1738_unescape(char *buf)
2137 while (p && *p && (p=strchr_m(p,'%'))) {
2141 if (c1 >= '0' && c1 <= '9')
2143 else if (c1 >= 'A' && c1 <= 'F')
2145 else if (c1 >= 'a' && c1 <= 'f')
2147 else {p++; continue;}
2149 if (c2 >= '0' && c2 <= '9')
2151 else if (c2 >= 'A' && c2 <= 'F')
2153 else if (c2 >= 'a' && c2 <= 'f')
2155 else {p++; continue;}
2159 memmove(p+1, p+3, strlen(p+3)+1);
2164 static const char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2167 * Decode a base64 string into a DATA_BLOB - simple and slow algorithm
2169 DATA_BLOB base64_decode_data_blob(const char *s)
2171 int bit_offset, byte_offset, idx, i, n;
2172 DATA_BLOB decoded = data_blob(s, strlen(s)+1);
2173 unsigned char *d = decoded.data;
2178 while (*s && (p=strchr_m(b64,*s))) {
2179 idx = (int)(p - b64);
2180 byte_offset = (i*6)/8;
2181 bit_offset = (i*6)%8;
2182 d[byte_offset] &= ~((1<<(8-bit_offset))-1);
2183 if (bit_offset < 3) {
2184 d[byte_offset] |= (idx << (2-bit_offset));
2187 d[byte_offset] |= (idx >> (bit_offset-2));
2188 d[byte_offset+1] = 0;
2189 d[byte_offset+1] |= (idx << (8-(bit_offset-2))) & 0xFF;
2195 if ((n > 0) && (*s == '=')) {
2205 * Decode a base64 string in-place - wrapper for the above
2207 void base64_decode_inplace(char *s)
2209 DATA_BLOB decoded = base64_decode_data_blob(s);
2211 if ( decoded.length != 0 ) {
2212 memcpy(s, decoded.data, decoded.length);
2214 /* null terminate */
2215 s[decoded.length] = '\0';
2220 data_blob_free(&decoded);
2224 * Encode a base64 string into a malloc()ed string caller to free.
2226 *From SQUID: adopted from http://ftp.sunet.se/pub2/gnu/vm/base64-encode.c with adjustments
2228 char * base64_encode_data_blob(DATA_BLOB data)
2232 size_t out_cnt, len, output_len;
2235 if (!data.length || !data.data)
2240 output_len = data.length * 2;
2241 result = SMB_MALLOC(output_len); /* get us plenty of space */
2243 while (len-- && out_cnt < (data.length * 2) - 5) {
2244 int c = (unsigned char) *(data.data++);
2247 if (char_count == 3) {
2248 result[out_cnt++] = b64[bits >> 18];
2249 result[out_cnt++] = b64[(bits >> 12) & 0x3f];
2250 result[out_cnt++] = b64[(bits >> 6) & 0x3f];
2251 result[out_cnt++] = b64[bits & 0x3f];
2258 if (char_count != 0) {
2259 bits <<= 16 - (8 * char_count);
2260 result[out_cnt++] = b64[bits >> 18];
2261 result[out_cnt++] = b64[(bits >> 12) & 0x3f];
2262 if (char_count == 1) {
2263 result[out_cnt++] = '=';
2264 result[out_cnt++] = '=';
2266 result[out_cnt++] = b64[(bits >> 6) & 0x3f];
2267 result[out_cnt++] = '=';
2270 result[out_cnt] = '\0'; /* terminate */
2274 /* read a SMB_BIG_UINT from a string */
2275 SMB_BIG_UINT STR_TO_SMB_BIG_UINT(const char *nptr, const char **entptr)
2278 SMB_BIG_UINT val = -1;
2279 const char *p = nptr;
2286 while (*p && isspace(*p))
2289 #ifdef LARGE_SMB_OFF_T
2290 sscanf(p,"%llu",&val);
2291 #else /* LARGE_SMB_OFF_T */
2292 sscanf(p,"%lu",&val);
2293 #endif /* LARGE_SMB_OFF_T */
2295 while (*p && isdigit(*p))
2303 void string_append(char **left, const char *right)
2305 int new_len = strlen(right) + 1;
2307 if (*left == NULL) {
2308 *left = SMB_MALLOC(new_len);
2311 new_len += strlen(*left);
2312 *left = SMB_REALLOC(*left, new_len);
2315 if (*left == NULL) {
2319 safe_strcat(*left, right, new_len-1);
2322 BOOL add_string_to_array(TALLOC_CTX *mem_ctx,
2323 const char *str, const char ***strings,
2326 char *dup_str = talloc_strdup(mem_ctx, str);
2328 *strings = TALLOC_REALLOC_ARRAY(mem_ctx, *strings, const char *, (*num)+1);
2330 if ((*strings == NULL) || (dup_str == NULL))
2333 (*strings)[*num] = dup_str;
2338 /* Append an sprintf'ed string. Double buffer size on demand. Usable without
2339 * error checking in between. The indiation that something weird happened is
2342 void sprintf_append(TALLOC_CTX *mem_ctx, char **string, ssize_t *len,
2343 size_t *bufsize, const char *fmt, ...)
2350 /* len<0 is an internal marker that something failed */
2354 if (*string == NULL) {
2358 if (mem_ctx != NULL)
2359 *string = TALLOC_ARRAY(mem_ctx, char, *bufsize);
2361 *string = SMB_MALLOC_ARRAY(char, *bufsize);
2363 if (*string == NULL)
2368 ret = vasprintf(&newstr, fmt, ap);
2376 while ((*len)+ret >= *bufsize) {
2379 if (*bufsize >= (1024*1024*256))
2384 if (mem_ctx != NULL) {
2385 *string = TALLOC_REALLOC_ARRAY(mem_ctx, *string, char,
2388 *string = SMB_REALLOC_ARRAY(*string, char, *bufsize);
2391 if (*string == NULL) {
2396 StrnCpy((*string)+(*len), newstr, ret);
2407 Returns the substring from src between the first occurrence of
2408 the char "front" and the first occurence of the char "back".
2409 Mallocs the return string which must be freed. Not for use
2410 with wide character strings.
2412 char *sstring_sub(const char *src, char front, char back)
2414 char *temp1, *temp2, *temp3;
2417 temp1 = strchr(src, front);
2418 if (temp1 == NULL) return NULL;
2419 temp2 = strchr(src, back);
2420 if (temp2 == NULL) return NULL;
2421 len = temp2 - temp1;
2422 if (len <= 0) return NULL;
2423 temp3 = (char*)SMB_MALLOC(len);
2424 if (temp3 == NULL) {
2425 DEBUG(1,("Malloc failure in sstring_sub\n"));
2428 memcpy(temp3, temp1+1, len-1);
2429 temp3[len-1] = '\0';
2433 /********************************************************************
2434 Check a string for any occurrences of a specified list of invalid
2436 ********************************************************************/
2438 BOOL validate_net_name( const char *name, const char *invalid_chars, int max_len )
2442 for ( i=0; i<max_len && name[i]; i++ ) {
2443 /* fail if strchr_m() finds one of the invalid characters */
2444 if ( name[i] && strchr_m( invalid_chars, name[i] ) ) {