Prepare to remove smb_panic() from unix_strlower().
[Samba/gebeck_regimport.git] / source3 / lib / util_str.c
blob901d5ae9f193a1d9de8fb9142ebe3ea5cb7ffd90
1 /*
2 Unix SMB/CIFS implementation.
3 Samba utility functions
5 Copyright (C) Andrew Tridgell 1992-2001
6 Copyright (C) Simo Sorce 2001-2002
7 Copyright (C) Martin Pool 2003
8 Copyright (C) James Peach 2006
9 Copyright (C) Jeremy Allison 1992-2007
11 This program is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 3 of the License, or
14 (at your option) any later version.
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
21 You should have received a copy of the GNU General Public License
22 along with this program. If not, see <http://www.gnu.org/licenses/>.
25 #include "includes.h"
26 #include "lib/param/loadparm.h"
28 const char toupper_ascii_fast_table[128] = {
29 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf,
30 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
31 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
32 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
33 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
34 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f,
35 0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
36 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f
39 /**
40 * Compare 2 strings up to and including the nth char.
42 * @note The comparison is case-insensitive.
43 **/
44 bool strnequal(const char *s1,const char *s2,size_t n)
46 if (s1 == s2)
47 return(true);
48 if (!s1 || !s2 || !n)
49 return(false);
51 return(strncasecmp_m(s1,s2,n)==0);
54 /**
55 Convert a string to "normal" form.
56 **/
58 void strnorm(char *s, int case_default)
60 if (case_default == CASE_UPPER)
61 strupper_m(s);
62 else
63 strlower_m(s);
66 /**
67 * Skip past some strings in a buffer - old version - no checks.
68 * **/
70 char *push_skip_string(char *buf)
72 buf += strlen(buf) + 1;
73 return(buf);
76 /**
77 Skip past a string in a buffer. Buffer may not be
78 null terminated. end_ptr points to the first byte after
79 then end of the buffer.
80 **/
82 char *skip_string(const char *base, size_t len, char *buf)
84 const char *end_ptr = base + len;
86 if (end_ptr < base || !base || !buf || buf >= end_ptr) {
87 return NULL;
90 /* Skip the string */
91 while (*buf) {
92 buf++;
93 if (buf >= end_ptr) {
94 return NULL;
97 /* Skip the '\0' */
98 buf++;
99 return buf;
103 Count the number of characters in a string. Normally this will
104 be the same as the number of bytes in a string for single byte strings,
105 but will be different for multibyte.
108 size_t str_charnum(const char *s)
110 size_t ret, converted_size;
111 smb_ucs2_t *tmpbuf2 = NULL;
112 if (!push_ucs2_talloc(talloc_tos(), &tmpbuf2, s, &converted_size)) {
113 return 0;
115 ret = strlen_w(tmpbuf2);
116 TALLOC_FREE(tmpbuf2);
117 return ret;
120 bool trim_char(char *s,char cfront,char cback)
122 bool ret = false;
123 char *ep;
124 char *fp = s;
126 /* Ignore null or empty strings. */
127 if (!s || (s[0] == '\0'))
128 return false;
130 if (cfront) {
131 while (*fp && *fp == cfront)
132 fp++;
133 if (!*fp) {
134 /* We ate the string. */
135 s[0] = '\0';
136 return true;
138 if (fp != s)
139 ret = true;
142 ep = fp + strlen(fp) - 1;
143 if (cback) {
144 /* Attempt ascii only. Bail for mb strings. */
145 while ((ep >= fp) && (*ep == cback)) {
146 ret = true;
147 if ((ep > fp) && (((unsigned char)ep[-1]) & 0x80)) {
148 /* Could be mb... bail back to tim_string. */
149 char fs[2], bs[2];
150 if (cfront) {
151 fs[0] = cfront;
152 fs[1] = '\0';
154 bs[0] = cback;
155 bs[1] = '\0';
156 return trim_string(s, cfront ? fs : NULL, bs);
157 } else {
158 ep--;
161 if (ep < fp) {
162 /* We ate the string. */
163 s[0] = '\0';
164 return true;
168 ep[1] = '\0';
169 memmove(s, fp, ep-fp+2);
170 return ret;
174 Like strncpy but always null terminates. Make sure there is room!
175 The variable n should always be one less than the available size.
177 char *StrnCpy(char *dest,const char *src,size_t n)
179 char *d = dest;
181 if (!dest) {
182 smb_panic("ERROR: NULL dest in StrnCpy");
185 if (!src) {
186 *dest = 0;
187 return(dest);
190 while (n-- && (*d = *src)) {
191 d++;
192 src++;
195 *d = 0;
196 return(dest);
200 Check if a string is part of a list.
203 bool in_list(const char *s, const char *list, bool casesensitive)
205 char *tok = NULL;
206 bool ret = false;
207 TALLOC_CTX *frame;
209 if (!list) {
210 return false;
213 frame = talloc_stackframe();
214 while (next_token_talloc(frame, &list, &tok,LIST_SEP)) {
215 if (casesensitive) {
216 if (strcmp(tok,s) == 0) {
217 ret = true;
218 break;
220 } else {
221 if (strcasecmp_m(tok,s) == 0) {
222 ret = true;
223 break;
227 TALLOC_FREE(frame);
228 return ret;
232 * Internal guts of talloc_string_sub and talloc_all_string_sub.
233 * talloc version of string_sub2.
236 char *talloc_string_sub2(TALLOC_CTX *mem_ctx, const char *src,
237 const char *pattern,
238 const char *insert,
239 bool remove_unsafe_characters,
240 bool replace_once,
241 bool allow_trailing_dollar)
243 char *p, *in;
244 char *s;
245 char *string;
246 ssize_t ls,lp,li,ld, i;
248 if (!insert || !pattern || !*pattern || !src) {
249 return NULL;
252 string = talloc_strdup(mem_ctx, src);
253 if (string == NULL) {
254 DEBUG(0, ("talloc_string_sub2: "
255 "talloc_strdup failed\n"));
256 return NULL;
259 s = string;
261 in = talloc_strdup(mem_ctx, insert);
262 if (!in) {
263 DEBUG(0, ("talloc_string_sub2: ENOMEM\n"));
264 return NULL;
266 ls = (ssize_t)strlen(s);
267 lp = (ssize_t)strlen(pattern);
268 li = (ssize_t)strlen(insert);
269 ld = li - lp;
271 for (i=0;i<li;i++) {
272 switch (in[i]) {
273 case '$':
274 /* allow a trailing $
275 * (as in machine accounts) */
276 if (allow_trailing_dollar && (i == li - 1 )) {
277 break;
279 case '`':
280 case '"':
281 case '\'':
282 case ';':
283 case '%':
284 case '\r':
285 case '\n':
286 if (remove_unsafe_characters) {
287 in[i] = '_';
288 break;
290 default:
291 /* ok */
292 break;
296 while ((p = strstr_m(s,pattern))) {
297 if (ld > 0) {
298 int offset = PTR_DIFF(s,string);
299 string = (char *)TALLOC_REALLOC(mem_ctx, string,
300 ls + ld + 1);
301 if (!string) {
302 DEBUG(0, ("talloc_string_sub: out of "
303 "memory!\n"));
304 TALLOC_FREE(in);
305 return NULL;
307 p = string + offset + (p - s);
309 if (li != lp) {
310 memmove(p+li,p+lp,strlen(p+lp)+1);
312 memcpy(p, in, li);
313 s = p + li;
314 ls += ld;
316 if (replace_once) {
317 break;
320 TALLOC_FREE(in);
321 return string;
324 /* Same as string_sub, but returns a talloc'ed string */
326 char *talloc_string_sub(TALLOC_CTX *mem_ctx,
327 const char *src,
328 const char *pattern,
329 const char *insert)
331 return talloc_string_sub2(mem_ctx, src, pattern, insert,
332 true, false, false);
335 char *talloc_all_string_sub(TALLOC_CTX *ctx,
336 const char *src,
337 const char *pattern,
338 const char *insert)
340 return talloc_string_sub2(ctx, src, pattern, insert,
341 false, false, false);
345 Write an octal as a string.
348 char *octal_string(int i)
350 char *result;
351 if (i == -1) {
352 result = talloc_strdup(talloc_tos(), "-1");
354 else {
355 result = talloc_asprintf(talloc_tos(), "0%o", i);
357 SMB_ASSERT(result != NULL);
358 return result;
363 Truncate a string at a specified length.
366 char *string_truncate(char *s, unsigned int length)
368 if (s && strlen(s) > length)
369 s[length] = 0;
370 return s;
374 /***********************************************************************
375 Return the equivalent of doing strrchr 'n' times - always going
376 backwards.
377 ***********************************************************************/
379 char *strnrchr_m(const char *s, char c, unsigned int n)
381 smb_ucs2_t *ws = NULL;
382 char *s2 = NULL;
383 smb_ucs2_t *p;
384 char *ret;
385 size_t converted_size;
387 if (!push_ucs2_talloc(talloc_tos(), &ws, s, &converted_size)) {
388 /* Too hard to try and get right. */
389 return NULL;
391 p = strnrchr_w(ws, UCS2_CHAR(c), n);
392 if (!p) {
393 TALLOC_FREE(ws);
394 return NULL;
396 *p = 0;
397 if (!pull_ucs2_talloc(talloc_tos(), &s2, ws, &converted_size)) {
398 TALLOC_FREE(ws);
399 /* Too hard to try and get right. */
400 return NULL;
402 ret = discard_const_p(char, (s+strlen(s2)));
403 TALLOC_FREE(ws);
404 TALLOC_FREE(s2);
405 return ret;
408 static bool unix_strlower(const char *src, size_t srclen, char *dest, size_t destlen)
410 size_t size;
411 smb_ucs2_t *buffer = NULL;
412 bool ret;
414 if (!convert_string_talloc(talloc_tos(), CH_UNIX, CH_UTF16LE, src, srclen,
415 (void **)(void *)&buffer, &size))
417 smb_panic("failed to create UCS2 buffer");
418 /* NOTREACHED. Yet. */
419 return false;
421 if (!strlower_w(buffer) && (dest == src)) {
422 TALLOC_FREE(buffer);
423 return true;
425 ret = convert_string(CH_UTF16LE, CH_UNIX, buffer, size, dest, destlen, &size);
426 TALLOC_FREE(buffer);
427 return ret;
430 #if 0 /* Alternate function that avoid talloc calls for ASCII and non ASCII */
433 Convert a string to lower case.
435 _PUBLIC_ void strlower_m(char *s)
437 char *d;
438 struct smb_iconv_handle *iconv_handle;
440 iconv_handle = get_iconv_handle();
442 d = s;
444 while (*s) {
445 size_t c_size, c_size2;
446 codepoint_t c = next_codepoint_handle(iconv_handle, s, &c_size);
447 c_size2 = push_codepoint_handle(iconv_handle, d, tolower_m(c));
448 if (c_size2 > c_size) {
449 DEBUG(0,("FATAL: codepoint 0x%x (0x%x) expanded from %d to %d bytes in strlower_m\n",
450 c, tolower_m(c), (int)c_size, (int)c_size2));
451 smb_panic("codepoint expansion in strlower_m\n");
453 s += c_size;
454 d += c_size2;
456 *d = 0;
459 #endif
462 Convert a string to lower case.
465 void strlower_m(char *s)
467 size_t len;
468 int errno_save;
470 /* this is quite a common operation, so we want it to be
471 fast. We optimise for the ascii case, knowing that all our
472 supported multi-byte character sets are ascii-compatible
473 (ie. they match for the first 128 chars) */
475 while (*s && !(((unsigned char)s[0]) & 0x80)) {
476 *s = tolower_m((unsigned char)*s);
477 s++;
480 if (!*s)
481 return;
483 /* I assume that lowercased string takes the same number of bytes
484 * as source string even in UTF-8 encoding. (VIV) */
485 len = strlen(s) + 1;
486 errno_save = errno;
487 errno = 0;
488 unix_strlower(s,len,s,len);
489 /* Catch mb conversion errors that may not terminate. */
490 if (errno)
491 s[len-1] = '\0';
492 errno = errno_save;
495 static bool unix_strupper(const char *src, size_t srclen, char *dest, size_t destlen)
497 size_t size;
498 smb_ucs2_t *buffer;
499 bool ret;
501 if (!push_ucs2_talloc(talloc_tos(), &buffer, src, &size)) {
502 return (size_t)-1;
505 if (!strupper_w(buffer) && (dest == src)) {
506 TALLOC_FREE(buffer);
507 return true;
510 ret = convert_string(CH_UTF16LE, CH_UNIX, buffer, size, dest, destlen, &size);
511 TALLOC_FREE(buffer);
512 return ret;
515 #if 0 /* Alternate function that avoid talloc calls for ASCII and non ASCII */
518 Convert a string to UPPER case.
520 _PUBLIC_ void strupper_m(char *s)
522 char *d;
523 struct smb_iconv_handle *iconv_handle;
525 iconv_handle = get_iconv_handle();
527 d = s;
529 while (*s) {
530 size_t c_size, c_size2;
531 codepoint_t c = next_codepoint_handle(iconv_handle, s, &c_size);
532 c_size2 = push_codepoint_handle(iconv_handle, d, toupper_m(c));
533 if (c_size2 > c_size) {
534 DEBUG(0,("FATAL: codepoint 0x%x (0x%x) expanded from %d to %d bytes in strupper_m\n",
535 c, toupper_m(c), (int)c_size, (int)c_size2));
536 smb_panic("codepoint expansion in strupper_m\n");
538 s += c_size;
539 d += c_size2;
541 *d = 0;
544 #endif
547 Convert a string to upper case.
550 void strupper_m(char *s)
552 size_t len;
553 int errno_save;
555 /* this is quite a common operation, so we want it to be
556 fast. We optimise for the ascii case, knowing that all our
557 supported multi-byte character sets are ascii-compatible
558 (ie. they match for the first 128 chars) */
560 while (*s && !(((unsigned char)s[0]) & 0x80)) {
561 *s = toupper_ascii_fast((unsigned char)*s);
562 s++;
565 if (!*s)
566 return;
568 /* I assume that lowercased string takes the same number of bytes
569 * as source string even in multibyte encoding. (VIV) */
570 len = strlen(s) + 1;
571 errno_save = errno;
572 errno = 0;
573 unix_strupper(s,len,s,len);
574 /* Catch mb conversion errors that may not terminate. */
575 if (errno)
576 s[len-1] = '\0';
577 errno = errno_save;
581 Just a typesafety wrapper for snprintf into a fstring.
584 int fstr_sprintf(fstring s, const char *fmt, ...)
586 va_list ap;
587 int ret;
589 va_start(ap, fmt);
590 ret = vsnprintf(s, FSTRING_LEN, fmt, ap);
591 va_end(ap);
592 return ret;
596 List of Strings manipulation functions
599 #define S_LIST_ABS 16 /* List Allocation Block Size */
601 /******************************************************************************
602 substitute a specific pattern in a string list
603 *****************************************************************************/
605 bool str_list_substitute(char **list, const char *pattern, const char *insert)
607 TALLOC_CTX *ctx = list;
608 char *p, *s, *t;
609 ssize_t ls, lp, li, ld, i, d;
611 if (!list)
612 return false;
613 if (!pattern)
614 return false;
615 if (!insert)
616 return false;
618 lp = (ssize_t)strlen(pattern);
619 li = (ssize_t)strlen(insert);
620 ld = li -lp;
622 while (*list) {
623 s = *list;
624 ls = (ssize_t)strlen(s);
626 while ((p = strstr_m(s, pattern))) {
627 t = *list;
628 d = p -t;
629 if (ld) {
630 t = talloc_array(ctx, char, ls +ld +1);
631 if (!t) {
632 DEBUG(0,("str_list_substitute: "
633 "Unable to allocate memory"));
634 return false;
636 memcpy(t, *list, d);
637 memcpy(t +d +li, p +lp, ls -d -lp +1);
638 TALLOC_FREE(*list);
639 *list = t;
640 ls += ld;
641 s = t +d +li;
644 for (i = 0; i < li; i++) {
645 switch (insert[i]) {
646 case '`':
647 case '"':
648 case '\'':
649 case ';':
650 case '$':
651 case '%':
652 case '\r':
653 case '\n':
654 t[d +i] = '_';
655 break;
656 default:
657 t[d +i] = insert[i];
662 list++;
665 return true;
669 #define IPSTR_LIST_SEP ","
670 #define IPSTR_LIST_CHAR ','
673 * Add ip string representation to ipstr list. Used also
674 * as part of @function ipstr_list_make
676 * @param ipstr_list pointer to string containing ip list;
677 * MUST BE already allocated and IS reallocated if necessary
678 * @param ipstr_size pointer to current size of ipstr_list (might be changed
679 * as a result of reallocation)
680 * @param ip IP address which is to be added to list
681 * @return pointer to string appended with new ip and possibly
682 * reallocated to new length
685 static char *ipstr_list_add(char **ipstr_list, const struct ip_service *service)
687 char *new_ipstr = NULL;
688 char addr_buf[INET6_ADDRSTRLEN];
689 int ret;
691 /* arguments checking */
692 if (!ipstr_list || !service) {
693 return NULL;
696 print_sockaddr(addr_buf,
697 sizeof(addr_buf),
698 &service->ss);
700 /* attempt to convert ip to a string and append colon separator to it */
701 if (*ipstr_list) {
702 if (service->ss.ss_family == AF_INET) {
703 /* IPv4 */
704 ret = asprintf(&new_ipstr, "%s%s%s:%d", *ipstr_list,
705 IPSTR_LIST_SEP, addr_buf,
706 service->port);
707 } else {
708 /* IPv6 */
709 ret = asprintf(&new_ipstr, "%s%s[%s]:%d", *ipstr_list,
710 IPSTR_LIST_SEP, addr_buf,
711 service->port);
713 SAFE_FREE(*ipstr_list);
714 } else {
715 if (service->ss.ss_family == AF_INET) {
716 /* IPv4 */
717 ret = asprintf(&new_ipstr, "%s:%d", addr_buf,
718 service->port);
719 } else {
720 /* IPv6 */
721 ret = asprintf(&new_ipstr, "[%s]:%d", addr_buf,
722 service->port);
725 if (ret == -1) {
726 return NULL;
728 *ipstr_list = new_ipstr;
729 return *ipstr_list;
733 * Allocate and initialise an ipstr list using ip adresses
734 * passed as arguments.
736 * @param ipstr_list pointer to string meant to be allocated and set
737 * @param ip_list array of ip addresses to place in the list
738 * @param ip_count number of addresses stored in ip_list
739 * @return pointer to allocated ip string
742 char *ipstr_list_make(char **ipstr_list,
743 const struct ip_service *ip_list,
744 int ip_count)
746 int i;
748 /* arguments checking */
749 if (!ip_list || !ipstr_list) {
750 return 0;
753 *ipstr_list = NULL;
755 /* process ip addresses given as arguments */
756 for (i = 0; i < ip_count; i++) {
757 *ipstr_list = ipstr_list_add(ipstr_list, &ip_list[i]);
760 return (*ipstr_list);
765 * Parse given ip string list into array of ip addresses
766 * (as ip_service structures)
767 * e.g. [IPv6]:port,192.168.1.100:389,192.168.1.78, ...
769 * @param ipstr ip string list to be parsed
770 * @param ip_list pointer to array of ip addresses which is
771 * allocated by this function and must be freed by caller
772 * @return number of successfully parsed addresses
775 int ipstr_list_parse(const char *ipstr_list, struct ip_service **ip_list)
777 TALLOC_CTX *frame;
778 char *token_str = NULL;
779 size_t count;
780 int i;
782 if (!ipstr_list || !ip_list)
783 return 0;
785 count = count_chars(ipstr_list, IPSTR_LIST_CHAR) + 1;
786 if ( (*ip_list = SMB_MALLOC_ARRAY(struct ip_service, count)) == NULL ) {
787 DEBUG(0,("ipstr_list_parse: malloc failed for %lu entries\n",
788 (unsigned long)count));
789 return 0;
792 frame = talloc_stackframe();
793 for ( i=0; next_token_talloc(frame, &ipstr_list, &token_str,
794 IPSTR_LIST_SEP) && i<count; i++ ) {
795 char *s = token_str;
796 char *p = strrchr(token_str, ':');
798 if (p) {
799 *p = 0;
800 (*ip_list)[i].port = atoi(p+1);
803 /* convert single token to ip address */
804 if (token_str[0] == '[') {
805 /* IPv6 address. */
806 s++;
807 p = strchr(token_str, ']');
808 if (!p) {
809 continue;
811 *p = '\0';
813 if (!interpret_string_addr(&(*ip_list)[i].ss,
815 AI_NUMERICHOST)) {
816 continue;
819 TALLOC_FREE(frame);
820 return count;
824 * Safely free ip string list
826 * @param ipstr_list ip string list to be freed
829 void ipstr_list_free(char* ipstr_list)
831 SAFE_FREE(ipstr_list);
834 /* read a SMB_BIG_UINT from a string */
835 uint64_t STR_TO_SMB_BIG_UINT(const char *nptr, const char **entptr)
838 uint64_t val = (uint64_t)-1;
839 const char *p = nptr;
841 if (!p) {
842 if (entptr) {
843 *entptr = p;
845 return val;
848 while (*p && isspace(*p))
849 p++;
851 sscanf(p,"%"PRIu64,&val);
852 if (entptr) {
853 while (*p && isdigit(*p))
854 p++;
855 *entptr = p;
858 return val;
861 /* Convert a size specification to a count of bytes. We accept the following
862 * suffixes:
863 * bytes if there is no suffix
864 * kK kibibytes
865 * mM mebibytes
866 * gG gibibytes
867 * tT tibibytes
868 * pP whatever the ISO name for petabytes is
870 * Returns 0 if the string can't be converted.
872 uint64_t conv_str_size(const char * str)
874 uint64_t lval;
875 char * end;
877 if (str == NULL || *str == '\0') {
878 return 0;
881 lval = strtoull(str, &end, 10 /* base */);
883 if (end == NULL || end == str) {
884 return 0;
887 if (*end == '\0') {
888 return lval;
891 if (strwicmp(end, "K") == 0) {
892 lval *= 1024ULL;
893 } else if (strwicmp(end, "M") == 0) {
894 lval *= (1024ULL * 1024ULL);
895 } else if (strwicmp(end, "G") == 0) {
896 lval *= (1024ULL * 1024ULL *
897 1024ULL);
898 } else if (strwicmp(end, "T") == 0) {
899 lval *= (1024ULL * 1024ULL *
900 1024ULL * 1024ULL);
901 } else if (strwicmp(end, "P") == 0) {
902 lval *= (1024ULL * 1024ULL *
903 1024ULL * 1024ULL *
904 1024ULL);
905 } else {
906 return 0;
909 return lval;
912 /* Append an sprintf'ed string. Double buffer size on demand. Usable without
913 * error checking in between. The indiation that something weird happened is
914 * string==NULL */
916 void sprintf_append(TALLOC_CTX *mem_ctx, char **string, ssize_t *len,
917 size_t *bufsize, const char *fmt, ...)
919 va_list ap;
920 char *newstr;
921 int ret;
922 bool increased;
924 /* len<0 is an internal marker that something failed */
925 if (*len < 0)
926 goto error;
928 if (*string == NULL) {
929 if (*bufsize == 0)
930 *bufsize = 128;
932 *string = talloc_array(mem_ctx, char, *bufsize);
933 if (*string == NULL)
934 goto error;
937 va_start(ap, fmt);
938 ret = vasprintf(&newstr, fmt, ap);
939 va_end(ap);
941 if (ret < 0)
942 goto error;
944 increased = false;
946 while ((*len)+ret >= *bufsize) {
947 increased = true;
948 *bufsize *= 2;
949 if (*bufsize >= (1024*1024*256))
950 goto error;
953 if (increased) {
954 *string = talloc_realloc(mem_ctx, *string, char,
955 *bufsize);
956 if (*string == NULL) {
957 goto error;
961 StrnCpy((*string)+(*len), newstr, ret);
962 (*len) += ret;
963 free(newstr);
964 return;
966 error:
967 *len = -1;
968 *string = NULL;
972 * asprintf into a string and strupper_m it after that.
975 int asprintf_strupper_m(char **strp, const char *fmt, ...)
977 va_list ap;
978 char *result;
979 int ret;
981 va_start(ap, fmt);
982 ret = vasprintf(&result, fmt, ap);
983 va_end(ap);
985 if (ret == -1)
986 return -1;
988 strupper_m(result);
989 *strp = result;
990 return ret;
993 char *talloc_asprintf_strupper_m(TALLOC_CTX *t, const char *fmt, ...)
995 va_list ap;
996 char *ret;
998 va_start(ap, fmt);
999 ret = talloc_vasprintf(t, fmt, ap);
1000 va_end(ap);
1002 if (ret == NULL) {
1003 return NULL;
1005 strupper_m(ret);
1006 return ret;
1009 char *talloc_asprintf_strlower_m(TALLOC_CTX *t, const char *fmt, ...)
1011 va_list ap;
1012 char *ret;
1014 va_start(ap, fmt);
1015 ret = talloc_vasprintf(t, fmt, ap);
1016 va_end(ap);
1018 if (ret == NULL) {
1019 return NULL;
1021 strlower_m(ret);
1022 return ret;
1026 /********************************************************************
1027 Check a string for any occurrences of a specified list of invalid
1028 characters.
1029 ********************************************************************/
1031 bool validate_net_name( const char *name,
1032 const char *invalid_chars,
1033 int max_len)
1035 int i;
1037 if (!name) {
1038 return false;
1041 for ( i=0; i<max_len && name[i]; i++ ) {
1042 /* fail if strchr_m() finds one of the invalid characters */
1043 if ( name[i] && strchr_m( invalid_chars, name[i] ) ) {
1044 return false;
1048 return true;
1052 /*******************************************************************
1053 Add a shell escape character '\' to any character not in a known list
1054 of characters. UNIX charset format.
1055 *******************************************************************/
1057 #define INCLUDE_LIST "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_/ \t.,"
1058 #define INSIDE_DQUOTE_LIST "$`\n\"\\"
1060 char *escape_shell_string(const char *src)
1062 size_t srclen = strlen(src);
1063 char *ret = SMB_MALLOC_ARRAY(char, (srclen * 2) + 1);
1064 char *dest = ret;
1065 bool in_s_quote = false;
1066 bool in_d_quote = false;
1067 bool next_escaped = false;
1069 if (!ret) {
1070 return NULL;
1073 while (*src) {
1074 size_t c_size;
1075 codepoint_t c = next_codepoint(src, &c_size);
1077 if (c == INVALID_CODEPOINT) {
1078 SAFE_FREE(ret);
1079 return NULL;
1082 if (c_size > 1) {
1083 memcpy(dest, src, c_size);
1084 src += c_size;
1085 dest += c_size;
1086 next_escaped = false;
1087 continue;
1091 * Deal with backslash escaped state.
1092 * This only lasts for one character.
1095 if (next_escaped) {
1096 *dest++ = *src++;
1097 next_escaped = false;
1098 continue;
1102 * Deal with single quote state. The
1103 * only thing we care about is exiting
1104 * this state.
1107 if (in_s_quote) {
1108 if (*src == '\'') {
1109 in_s_quote = false;
1111 *dest++ = *src++;
1112 continue;
1116 * Deal with double quote state. The most
1117 * complex state. We must cope with \, meaning
1118 * possibly escape next char (depending what it
1119 * is), ", meaning exit this state, and possibly
1120 * add an \ escape to any unprotected character
1121 * (listed in INSIDE_DQUOTE_LIST).
1124 if (in_d_quote) {
1125 if (*src == '\\') {
1127 * Next character might be escaped.
1128 * We have to peek. Inside double
1129 * quotes only INSIDE_DQUOTE_LIST
1130 * characters are escaped by a \.
1133 char nextchar;
1135 c = next_codepoint(&src[1], &c_size);
1136 if (c == INVALID_CODEPOINT) {
1137 SAFE_FREE(ret);
1138 return NULL;
1140 if (c_size > 1) {
1142 * Don't escape the next char.
1143 * Just copy the \.
1145 *dest++ = *src++;
1146 continue;
1149 nextchar = src[1];
1151 if (nextchar && strchr(INSIDE_DQUOTE_LIST,
1152 (int)nextchar)) {
1153 next_escaped = true;
1155 *dest++ = *src++;
1156 continue;
1159 if (*src == '\"') {
1160 /* Exit double quote state. */
1161 in_d_quote = false;
1162 *dest++ = *src++;
1163 continue;
1167 * We know the character isn't \ or ",
1168 * so escape it if it's any of the other
1169 * possible unprotected characters.
1172 if (strchr(INSIDE_DQUOTE_LIST, (int)*src)) {
1173 *dest++ = '\\';
1175 *dest++ = *src++;
1176 continue;
1180 * From here to the end of the loop we're
1181 * not in the single or double quote state.
1184 if (*src == '\\') {
1185 /* Next character must be escaped. */
1186 next_escaped = true;
1187 *dest++ = *src++;
1188 continue;
1191 if (*src == '\'') {
1192 /* Go into single quote state. */
1193 in_s_quote = true;
1194 *dest++ = *src++;
1195 continue;
1198 if (*src == '\"') {
1199 /* Go into double quote state. */
1200 in_d_quote = true;
1201 *dest++ = *src++;
1202 continue;
1205 /* Check if we need to escape the character. */
1207 if (!strchr(INCLUDE_LIST, (int)*src)) {
1208 *dest++ = '\\';
1210 *dest++ = *src++;
1212 *dest++ = '\0';
1213 return ret;
1216 /***************************************************
1217 str_list_make, v3 version. The v4 version does not
1218 look at quoted strings with embedded blanks, so
1219 do NOT merge this function please!
1220 ***************************************************/
1222 #define S_LIST_ABS 16 /* List Allocation Block Size */
1224 char **str_list_make_v3(TALLOC_CTX *mem_ctx, const char *string,
1225 const char *sep)
1227 char **list;
1228 const char *str;
1229 char *s, *tok;
1230 int num, lsize;
1232 if (!string || !*string)
1233 return NULL;
1235 list = talloc_array(mem_ctx, char *, S_LIST_ABS+1);
1236 if (list == NULL) {
1237 return NULL;
1239 lsize = S_LIST_ABS;
1241 s = talloc_strdup(list, string);
1242 if (s == NULL) {
1243 DEBUG(0,("str_list_make: Unable to allocate memory"));
1244 TALLOC_FREE(list);
1245 return NULL;
1247 if (!sep) sep = LIST_SEP;
1249 num = 0;
1250 str = s;
1252 while (next_token_talloc(list, &str, &tok, sep)) {
1254 if (num == lsize) {
1255 char **tmp;
1257 lsize += S_LIST_ABS;
1259 tmp = talloc_realloc(mem_ctx, list, char *,
1260 lsize + 1);
1261 if (tmp == NULL) {
1262 DEBUG(0,("str_list_make: "
1263 "Unable to allocate memory"));
1264 TALLOC_FREE(list);
1265 return NULL;
1268 list = tmp;
1270 memset (&list[num], 0,
1271 ((sizeof(char**)) * (S_LIST_ABS +1)));
1274 list[num] = tok;
1275 num += 1;
1278 list[num] = NULL;
1280 TALLOC_FREE(s);
1281 return list;