python/samba: Another object.next() to next(object) py2/py3 converstion
[Samba.git] / source3 / lib / util_str.c
blobeb36478d8a21abb3139d183c68fa4558424538f0
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 static 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 bool strnorm(char *s, int case_default)
60 if (case_default == CASE_UPPER)
61 return strupper_m(s);
62 else
63 return 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;
280 FALL_THROUGH;
281 case '`':
282 case '"':
283 case '\'':
284 case ';':
285 case '%':
286 case '\r':
287 case '\n':
288 if (remove_unsafe_characters) {
289 in[i] = '_';
290 break;
293 FALL_THROUGH;
294 default:
295 /* ok */
296 break;
300 while ((p = strstr_m(s,pattern))) {
301 if (ld > 0) {
302 int offset = PTR_DIFF(s,string);
303 string = (char *)TALLOC_REALLOC(mem_ctx, string,
304 ls + ld + 1);
305 if (!string) {
306 DEBUG(0, ("talloc_string_sub: out of "
307 "memory!\n"));
308 TALLOC_FREE(in);
309 return NULL;
311 p = string + offset + (p - s);
313 if (li != lp) {
314 memmove(p+li,p+lp,strlen(p+lp)+1);
316 memcpy(p, in, li);
317 s = p + li;
318 ls += ld;
320 if (replace_once) {
321 break;
324 TALLOC_FREE(in);
325 return string;
328 /* Same as string_sub, but returns a talloc'ed string */
330 char *talloc_string_sub(TALLOC_CTX *mem_ctx,
331 const char *src,
332 const char *pattern,
333 const char *insert)
335 return talloc_string_sub2(mem_ctx, src, pattern, insert,
336 true, false, false);
339 char *talloc_all_string_sub(TALLOC_CTX *ctx,
340 const char *src,
341 const char *pattern,
342 const char *insert)
344 return talloc_string_sub2(ctx, src, pattern, insert,
345 false, false, false);
349 Write an octal as a string.
352 char *octal_string(int i)
354 char *result;
355 if (i == -1) {
356 result = talloc_strdup(talloc_tos(), "-1");
358 else {
359 result = talloc_asprintf(talloc_tos(), "0%o", i);
361 SMB_ASSERT(result != NULL);
362 return result;
367 Truncate a string at a specified length.
370 char *string_truncate(char *s, unsigned int length)
372 if (s && strlen(s) > length)
373 s[length] = 0;
374 return s;
378 /***********************************************************************
379 Return the equivalent of doing strrchr 'n' times - always going
380 backwards.
381 ***********************************************************************/
383 char *strnrchr_m(const char *s, char c, unsigned int n)
385 smb_ucs2_t *ws = NULL;
386 char *s2 = NULL;
387 smb_ucs2_t *p;
388 char *ret;
389 size_t converted_size;
391 if (!push_ucs2_talloc(talloc_tos(), &ws, s, &converted_size)) {
392 /* Too hard to try and get right. */
393 return NULL;
395 p = strnrchr_w(ws, UCS2_CHAR(c), n);
396 if (!p) {
397 TALLOC_FREE(ws);
398 return NULL;
400 *p = 0;
401 if (!pull_ucs2_talloc(talloc_tos(), &s2, ws, &converted_size)) {
402 TALLOC_FREE(ws);
403 /* Too hard to try and get right. */
404 return NULL;
406 ret = discard_const_p(char, (s+strlen(s2)));
407 TALLOC_FREE(ws);
408 TALLOC_FREE(s2);
409 return ret;
412 static bool unix_strlower(const char *src, size_t srclen, char *dest, size_t destlen)
414 size_t size;
415 smb_ucs2_t *buffer = NULL;
416 bool ret;
418 if (!convert_string_talloc(talloc_tos(), CH_UNIX, CH_UTF16LE, src, srclen,
419 (void **)(void *)&buffer, &size))
421 return false;
423 if (!strlower_w(buffer) && (dest == src)) {
424 TALLOC_FREE(buffer);
425 return true;
427 ret = convert_string(CH_UTF16LE, CH_UNIX, buffer, size, dest, destlen, &size);
428 TALLOC_FREE(buffer);
429 return ret;
432 #if 0 /* Alternate function that avoid talloc calls for ASCII and non ASCII */
435 Convert a string to lower case.
437 _PUBLIC_ void strlower_m(char *s)
439 char *d;
440 struct smb_iconv_handle *iconv_handle;
442 iconv_handle = get_iconv_handle();
444 d = s;
446 while (*s) {
447 size_t c_size, c_size2;
448 codepoint_t c = next_codepoint_handle(iconv_handle, s, &c_size);
449 c_size2 = push_codepoint_handle(iconv_handle, d, tolower_m(c));
450 if (c_size2 > c_size) {
451 DEBUG(0,("FATAL: codepoint 0x%x (0x%x) expanded from %d to %d bytes in strlower_m\n",
452 c, tolower_m(c), (int)c_size, (int)c_size2));
453 smb_panic("codepoint expansion in strlower_m\n");
455 s += c_size;
456 d += c_size2;
458 *d = 0;
461 #endif
464 Convert a string to lower case.
467 bool strlower_m(char *s)
469 size_t len;
470 int errno_save;
471 bool ret = false;
473 /* this is quite a common operation, so we want it to be
474 fast. We optimise for the ascii case, knowing that all our
475 supported multi-byte character sets are ascii-compatible
476 (ie. they match for the first 128 chars) */
478 while (*s && !(((unsigned char)s[0]) & 0x80)) {
479 *s = tolower_m((unsigned char)*s);
480 s++;
483 if (!*s)
484 return true;
486 /* I assume that lowercased string takes the same number of bytes
487 * as source string even in UTF-8 encoding. (VIV) */
488 len = strlen(s) + 1;
489 errno_save = errno;
490 errno = 0;
491 ret = unix_strlower(s,len,s,len);
492 /* Catch mb conversion errors that may not terminate. */
493 if (errno) {
494 s[len-1] = '\0';
496 errno = errno_save;
497 return ret;
500 static bool unix_strupper(const char *src, size_t srclen, char *dest, size_t destlen)
502 size_t size;
503 smb_ucs2_t *buffer;
504 bool ret;
506 if (!push_ucs2_talloc(talloc_tos(), &buffer, src, &size)) {
507 return false;
510 if (!strupper_w(buffer) && (dest == src)) {
511 TALLOC_FREE(buffer);
512 return true;
515 ret = convert_string(CH_UTF16LE, CH_UNIX, buffer, size, dest, destlen, &size);
516 TALLOC_FREE(buffer);
517 return ret;
520 #if 0 /* Alternate function that avoid talloc calls for ASCII and non ASCII */
523 Convert a string to UPPER case.
525 _PUBLIC_ void strupper_m(char *s)
527 char *d;
528 struct smb_iconv_handle *iconv_handle;
530 iconv_handle = get_iconv_handle();
532 d = s;
534 while (*s) {
535 size_t c_size, c_size2;
536 codepoint_t c = next_codepoint_handle(iconv_handle, s, &c_size);
537 c_size2 = push_codepoint_handle(iconv_handle, d, toupper_m(c));
538 if (c_size2 > c_size) {
539 DEBUG(0,("FATAL: codepoint 0x%x (0x%x) expanded from %d to %d bytes in strupper_m\n",
540 c, toupper_m(c), (int)c_size, (int)c_size2));
541 smb_panic("codepoint expansion in strupper_m\n");
543 s += c_size;
544 d += c_size2;
546 *d = 0;
549 #endif
552 Convert a string to upper case.
555 bool strupper_m(char *s)
557 size_t len;
558 bool ret = false;
560 /* this is quite a common operation, so we want it to be
561 fast. We optimise for the ascii case, knowing that all our
562 supported multi-byte character sets are ascii-compatible
563 (ie. they match for the first 128 chars) */
565 while (*s && !(((unsigned char)s[0]) & 0x80)) {
566 *s = toupper_ascii_fast_table[(unsigned char)s[0]];
567 s++;
570 if (!*s)
571 return true;
573 /* I assume that uppercased string takes the same number of bytes
574 * as source string even in multibyte encoding. (VIV) */
575 len = strlen(s) + 1;
576 ret = unix_strupper(s,len,s,len);
577 /* Catch mb conversion errors that may not terminate. */
578 if (!ret) {
579 s[len-1] = '\0';
581 return ret;
585 Just a typesafety wrapper for snprintf into a fstring.
588 int fstr_sprintf(fstring s, const char *fmt, ...)
590 va_list ap;
591 int ret;
593 va_start(ap, fmt);
594 ret = vsnprintf(s, FSTRING_LEN, fmt, ap);
595 va_end(ap);
596 return ret;
600 List of Strings manipulation functions
603 #define S_LIST_ABS 16 /* List Allocation Block Size */
605 /******************************************************************************
606 substitute a specific pattern in a string list
607 *****************************************************************************/
609 bool str_list_substitute(char **list, const char *pattern, const char *insert)
611 TALLOC_CTX *ctx = list;
612 char *p, *s, *t;
613 ssize_t ls, lp, li, ld, i, d;
615 if (!list)
616 return false;
617 if (!pattern)
618 return false;
619 if (!insert)
620 return false;
622 lp = (ssize_t)strlen(pattern);
623 li = (ssize_t)strlen(insert);
624 ld = li -lp;
626 while (*list) {
627 s = *list;
628 ls = (ssize_t)strlen(s);
630 while ((p = strstr_m(s, pattern))) {
631 t = *list;
632 d = p -t;
633 if (ld) {
634 t = talloc_array(ctx, char, ls +ld +1);
635 if (!t) {
636 DEBUG(0,("str_list_substitute: "
637 "Unable to allocate memory"));
638 return false;
640 memcpy(t, *list, d);
641 memcpy(t +d +li, p +lp, ls -d -lp +1);
642 TALLOC_FREE(*list);
643 *list = t;
644 ls += ld;
645 s = t +d +li;
648 for (i = 0; i < li; i++) {
649 switch (insert[i]) {
650 case '`':
651 case '"':
652 case '\'':
653 case ';':
654 case '$':
655 case '%':
656 case '\r':
657 case '\n':
658 t[d +i] = '_';
659 break;
660 default:
661 t[d +i] = insert[i];
666 list++;
669 return true;
673 #define IPSTR_LIST_SEP ","
674 #define IPSTR_LIST_CHAR ','
677 * Add ip string representation to ipstr list. Used also
678 * as part of @function ipstr_list_make
680 * @param ipstr_list pointer to string containing ip list;
681 * MUST BE already allocated and IS reallocated if necessary
682 * @param ipstr_size pointer to current size of ipstr_list (might be changed
683 * as a result of reallocation)
684 * @param ip IP address which is to be added to list
685 * @return pointer to string appended with new ip and possibly
686 * reallocated to new length
689 static char *ipstr_list_add(char **ipstr_list, const struct ip_service *service)
691 char *new_ipstr = NULL;
692 char addr_buf[INET6_ADDRSTRLEN];
693 int ret;
695 /* arguments checking */
696 if (!ipstr_list || !service) {
697 return NULL;
700 print_sockaddr(addr_buf,
701 sizeof(addr_buf),
702 &service->ss);
704 /* attempt to convert ip to a string and append colon separator to it */
705 if (*ipstr_list) {
706 if (service->ss.ss_family == AF_INET) {
707 /* IPv4 */
708 ret = asprintf(&new_ipstr, "%s%s%s:%d", *ipstr_list,
709 IPSTR_LIST_SEP, addr_buf,
710 service->port);
711 } else {
712 /* IPv6 */
713 ret = asprintf(&new_ipstr, "%s%s[%s]:%d", *ipstr_list,
714 IPSTR_LIST_SEP, addr_buf,
715 service->port);
717 SAFE_FREE(*ipstr_list);
718 } else {
719 if (service->ss.ss_family == AF_INET) {
720 /* IPv4 */
721 ret = asprintf(&new_ipstr, "%s:%d", addr_buf,
722 service->port);
723 } else {
724 /* IPv6 */
725 ret = asprintf(&new_ipstr, "[%s]:%d", addr_buf,
726 service->port);
729 if (ret == -1) {
730 return NULL;
732 *ipstr_list = new_ipstr;
733 return *ipstr_list;
737 * Allocate and initialise an ipstr list using ip adresses
738 * passed as arguments.
740 * @param ipstr_list pointer to string meant to be allocated and set
741 * @param ip_list array of ip addresses to place in the list
742 * @param ip_count number of addresses stored in ip_list
743 * @return pointer to allocated ip string
746 char *ipstr_list_make(char **ipstr_list,
747 const struct ip_service *ip_list,
748 int ip_count)
750 int i;
752 /* arguments checking */
753 if (!ip_list || !ipstr_list) {
754 return 0;
757 *ipstr_list = NULL;
759 /* process ip addresses given as arguments */
760 for (i = 0; i < ip_count; i++) {
761 *ipstr_list = ipstr_list_add(ipstr_list, &ip_list[i]);
764 return (*ipstr_list);
769 * Parse given ip string list into array of ip addresses
770 * (as ip_service structures)
771 * e.g. [IPv6]:port,192.168.1.100:389,192.168.1.78, ...
773 * @param ipstr ip string list to be parsed
774 * @param ip_list pointer to array of ip addresses which is
775 * allocated by this function and must be freed by caller
776 * @return number of successfully parsed addresses
779 int ipstr_list_parse(const char *ipstr_list, struct ip_service **ip_list)
781 TALLOC_CTX *frame;
782 char *token_str = NULL;
783 size_t count;
784 int i;
786 if (!ipstr_list || !ip_list)
787 return 0;
789 count = count_chars(ipstr_list, IPSTR_LIST_CHAR) + 1;
790 if ( (*ip_list = SMB_MALLOC_ARRAY(struct ip_service, count)) == NULL ) {
791 DEBUG(0,("ipstr_list_parse: malloc failed for %lu entries\n",
792 (unsigned long)count));
793 return 0;
796 frame = talloc_stackframe();
797 for ( i=0; next_token_talloc(frame, &ipstr_list, &token_str,
798 IPSTR_LIST_SEP) && i<count; i++ ) {
799 char *s = token_str;
800 char *p = strrchr(token_str, ':');
802 if (p) {
803 *p = 0;
804 (*ip_list)[i].port = atoi(p+1);
807 /* convert single token to ip address */
808 if (token_str[0] == '[') {
809 /* IPv6 address. */
810 s++;
811 p = strchr(token_str, ']');
812 if (!p) {
813 continue;
815 *p = '\0';
817 if (!interpret_string_addr(&(*ip_list)[i].ss,
819 AI_NUMERICHOST)) {
820 continue;
823 TALLOC_FREE(frame);
824 return count;
828 * Safely free ip string list
830 * @param ipstr_list ip string list to be freed
833 void ipstr_list_free(char* ipstr_list)
835 SAFE_FREE(ipstr_list);
838 /* read a SMB_BIG_UINT from a string */
839 uint64_t STR_TO_SMB_BIG_UINT(const char *nptr, const char **entptr)
842 uint64_t val = (uint64_t)-1;
843 const char *p = nptr;
845 if (!p) {
846 if (entptr) {
847 *entptr = p;
849 return val;
852 while (*p && isspace(*p))
853 p++;
855 sscanf(p,"%"SCNu64,&val);
856 if (entptr) {
857 while (*p && isdigit(*p))
858 p++;
859 *entptr = p;
862 return val;
865 /* Convert a size specification to a count of bytes. We accept the following
866 * suffixes:
867 * bytes if there is no suffix
868 * kK kibibytes
869 * mM mebibytes
870 * gG gibibytes
871 * tT tibibytes
872 * pP whatever the ISO name for petabytes is
874 * Returns 0 if the string can't be converted.
876 uint64_t conv_str_size(const char * str)
878 uint64_t lval;
879 char * end;
881 if (str == NULL || *str == '\0') {
882 return 0;
885 lval = strtoull(str, &end, 10 /* base */);
887 if (end == NULL || end == str) {
888 return 0;
891 if (*end == '\0') {
892 return lval;
895 if (strwicmp(end, "K") == 0) {
896 lval *= 1024ULL;
897 } else if (strwicmp(end, "M") == 0) {
898 lval *= (1024ULL * 1024ULL);
899 } else if (strwicmp(end, "G") == 0) {
900 lval *= (1024ULL * 1024ULL *
901 1024ULL);
902 } else if (strwicmp(end, "T") == 0) {
903 lval *= (1024ULL * 1024ULL *
904 1024ULL * 1024ULL);
905 } else if (strwicmp(end, "P") == 0) {
906 lval *= (1024ULL * 1024ULL *
907 1024ULL * 1024ULL *
908 1024ULL);
909 } else {
910 return 0;
913 return lval;
917 * asprintf into a string and strupper_m it after that.
920 int asprintf_strupper_m(char **strp, const char *fmt, ...)
922 va_list ap;
923 char *result;
924 int ret;
926 va_start(ap, fmt);
927 ret = vasprintf(&result, fmt, ap);
928 va_end(ap);
930 if (ret == -1)
931 return -1;
933 if (!strupper_m(result)) {
934 SAFE_FREE(result);
935 return -1;
938 *strp = result;
939 return ret;
942 char *talloc_asprintf_strupper_m(TALLOC_CTX *t, const char *fmt, ...)
944 va_list ap;
945 char *ret;
947 va_start(ap, fmt);
948 ret = talloc_vasprintf(t, fmt, ap);
949 va_end(ap);
951 if (ret == NULL) {
952 return NULL;
954 if (!strupper_m(ret)) {
955 TALLOC_FREE(ret);
956 return NULL;
958 return ret;
961 char *talloc_asprintf_strlower_m(TALLOC_CTX *t, const char *fmt, ...)
963 va_list ap;
964 char *ret;
966 va_start(ap, fmt);
967 ret = talloc_vasprintf(t, fmt, ap);
968 va_end(ap);
970 if (ret == NULL) {
971 return NULL;
973 if (!strlower_m(ret)) {
974 TALLOC_FREE(ret);
975 return NULL;
977 return ret;
981 /********************************************************************
982 Check a string for any occurrences of a specified list of invalid
983 characters.
984 ********************************************************************/
986 bool validate_net_name( const char *name,
987 const char *invalid_chars,
988 int max_len)
990 int i;
992 if (!name) {
993 return false;
996 for ( i=0; i<max_len && name[i]; i++ ) {
997 /* fail if strchr_m() finds one of the invalid characters */
998 if ( name[i] && strchr_m( invalid_chars, name[i] ) ) {
999 return false;
1003 return true;
1007 /*******************************************************************
1008 Add a shell escape character '\' to any character not in a known list
1009 of characters. UNIX charset format.
1010 *******************************************************************/
1012 #define INCLUDE_LIST "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_/ \t.,"
1013 #define INSIDE_DQUOTE_LIST "$`\n\"\\"
1015 char *escape_shell_string(const char *src)
1017 size_t srclen = strlen(src);
1018 char *ret = SMB_MALLOC_ARRAY(char, (srclen * 2) + 1);
1019 char *dest = ret;
1020 bool in_s_quote = false;
1021 bool in_d_quote = false;
1022 bool next_escaped = false;
1024 if (!ret) {
1025 return NULL;
1028 while (*src) {
1029 size_t c_size;
1030 codepoint_t c = next_codepoint(src, &c_size);
1032 if (c == INVALID_CODEPOINT) {
1033 SAFE_FREE(ret);
1034 return NULL;
1037 if (c_size > 1) {
1038 memcpy(dest, src, c_size);
1039 src += c_size;
1040 dest += c_size;
1041 next_escaped = false;
1042 continue;
1046 * Deal with backslash escaped state.
1047 * This only lasts for one character.
1050 if (next_escaped) {
1051 *dest++ = *src++;
1052 next_escaped = false;
1053 continue;
1057 * Deal with single quote state. The
1058 * only thing we care about is exiting
1059 * this state.
1062 if (in_s_quote) {
1063 if (*src == '\'') {
1064 in_s_quote = false;
1066 *dest++ = *src++;
1067 continue;
1071 * Deal with double quote state. The most
1072 * complex state. We must cope with \, meaning
1073 * possibly escape next char (depending what it
1074 * is), ", meaning exit this state, and possibly
1075 * add an \ escape to any unprotected character
1076 * (listed in INSIDE_DQUOTE_LIST).
1079 if (in_d_quote) {
1080 if (*src == '\\') {
1082 * Next character might be escaped.
1083 * We have to peek. Inside double
1084 * quotes only INSIDE_DQUOTE_LIST
1085 * characters are escaped by a \.
1088 char nextchar;
1090 c = next_codepoint(&src[1], &c_size);
1091 if (c == INVALID_CODEPOINT) {
1092 SAFE_FREE(ret);
1093 return NULL;
1095 if (c_size > 1) {
1097 * Don't escape the next char.
1098 * Just copy the \.
1100 *dest++ = *src++;
1101 continue;
1104 nextchar = src[1];
1106 if (nextchar && strchr(INSIDE_DQUOTE_LIST,
1107 (int)nextchar)) {
1108 next_escaped = true;
1110 *dest++ = *src++;
1111 continue;
1114 if (*src == '\"') {
1115 /* Exit double quote state. */
1116 in_d_quote = false;
1117 *dest++ = *src++;
1118 continue;
1122 * We know the character isn't \ or ",
1123 * so escape it if it's any of the other
1124 * possible unprotected characters.
1127 if (strchr(INSIDE_DQUOTE_LIST, (int)*src)) {
1128 *dest++ = '\\';
1130 *dest++ = *src++;
1131 continue;
1135 * From here to the end of the loop we're
1136 * not in the single or double quote state.
1139 if (*src == '\\') {
1140 /* Next character must be escaped. */
1141 next_escaped = true;
1142 *dest++ = *src++;
1143 continue;
1146 if (*src == '\'') {
1147 /* Go into single quote state. */
1148 in_s_quote = true;
1149 *dest++ = *src++;
1150 continue;
1153 if (*src == '\"') {
1154 /* Go into double quote state. */
1155 in_d_quote = true;
1156 *dest++ = *src++;
1157 continue;
1160 /* Check if we need to escape the character. */
1162 if (!strchr(INCLUDE_LIST, (int)*src)) {
1163 *dest++ = '\\';
1165 *dest++ = *src++;
1167 *dest++ = '\0';
1168 return ret;
1172 * This routine improves performance for operations temporarily acting on a
1173 * full path. It is equivalent to the much more expensive
1175 * talloc_asprintf(talloc_tos(), "%s/%s", dir, name)
1177 * This actually does make a difference in metadata-heavy workloads (i.e. the
1178 * "standard" client.txt nbench run.
1181 ssize_t full_path_tos(const char *dir, const char *name,
1182 char *tmpbuf, size_t tmpbuf_len,
1183 char **pdst, char **to_free)
1185 size_t dirlen, namelen, len;
1186 char *dst;
1188 dirlen = strlen(dir);
1189 namelen = strlen(name);
1190 len = dirlen + namelen + 1;
1192 if (len < tmpbuf_len) {
1193 dst = tmpbuf;
1194 *to_free = NULL;
1195 } else {
1196 dst = talloc_array(talloc_tos(), char, len+1);
1197 if (dst == NULL) {
1198 return -1;
1200 *to_free = dst;
1203 memcpy(dst, dir, dirlen);
1204 dst[dirlen] = '/';
1205 memcpy(dst+dirlen+1, name, namelen+1);
1206 *pdst = dst;
1207 return len;