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/>.
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
40 * Compare 2 strings up to and including the nth char.
42 * @note The comparison is case-insensitive.
44 bool strnequal(const char *s1,const char *s2,size_t n)
51 return(strncasecmp_m(s1,s2,n)==0);
55 Convert a string to "normal" form.
58 bool strnorm(char *s, int case_default)
60 if (case_default == CASE_UPPER)
67 Skip past a string in a buffer. Buffer may not be
68 null terminated. end_ptr points to the first byte after
69 then end of the buffer.
72 char *skip_string(const char *base, size_t len, char *buf)
74 const char *end_ptr = base + len;
76 if (end_ptr < base || !base || !buf || buf >= end_ptr) {
93 Count the number of characters in a string. Normally this will
94 be the same as the number of bytes in a string for single byte strings,
95 but will be different for multibyte.
98 size_t str_charnum(const char *s)
100 size_t ret, converted_size;
101 smb_ucs2_t *tmpbuf2 = NULL;
102 if (!push_ucs2_talloc(talloc_tos(), &tmpbuf2, s, &converted_size)) {
105 ret = strlen_w(tmpbuf2);
106 TALLOC_FREE(tmpbuf2);
110 bool trim_char(char *s,char cfront,char cback)
116 /* Ignore null or empty strings. */
117 if (!s || (s[0] == '\0'))
121 while (*fp && *fp == cfront)
124 /* We ate the string. */
132 ep = fp + strlen(fp) - 1;
134 /* Attempt ascii only. Bail for mb strings. */
135 while ((ep >= fp) && (*ep == cback)) {
137 if ((ep > fp) && (((unsigned char)ep[-1]) & 0x80)) {
138 /* Could be mb... bail back to tim_string. */
146 return trim_string(s, cfront ? fs : NULL, bs);
152 /* We ate the string. */
159 memmove(s, fp, ep-fp+2);
164 Check if a string is part of a list.
167 bool in_list(const char *s, const char *list, bool casesensitive)
177 frame = talloc_stackframe();
178 while (next_token_talloc(frame, &list, &tok,LIST_SEP)) {
180 if (strcmp(tok,s) == 0) {
185 if (strcasecmp_m(tok,s) == 0) {
196 * Internal guts of talloc_string_sub and talloc_all_string_sub.
197 * talloc version of string_sub2.
200 char *talloc_string_sub2(TALLOC_CTX *mem_ctx, const char *src,
203 bool remove_unsafe_characters,
205 bool allow_trailing_dollar)
210 ssize_t ls,lp,li,ld, i;
212 if (!insert || !pattern || !*pattern || !src) {
216 string = talloc_strdup(mem_ctx, src);
217 if (string == NULL) {
218 DEBUG(0, ("talloc_string_sub2: "
219 "talloc_strdup failed\n"));
225 in = talloc_strdup(mem_ctx, insert);
227 DEBUG(0, ("talloc_string_sub2: ENOMEM\n"));
230 ls = (ssize_t)strlen(s);
231 lp = (ssize_t)strlen(pattern);
232 li = (ssize_t)strlen(insert);
238 /* allow a trailing $
239 * (as in machine accounts) */
240 if (allow_trailing_dollar && (i == li - 1 )) {
252 if (remove_unsafe_characters) {
264 while ((p = strstr_m(s,pattern))) {
266 int offset = PTR_DIFF(s,string);
267 string = (char *)TALLOC_REALLOC(mem_ctx, string,
270 DEBUG(0, ("talloc_string_sub: out of "
275 p = string + offset + (p - s);
278 memmove(p+li,p+lp,strlen(p+lp)+1);
292 /* Same as string_sub, but returns a talloc'ed string */
294 char *talloc_string_sub(TALLOC_CTX *mem_ctx,
299 return talloc_string_sub2(mem_ctx, src, pattern, insert,
303 char *talloc_all_string_sub(TALLOC_CTX *ctx,
308 return talloc_string_sub2(ctx, src, pattern, insert,
309 false, false, false);
313 Write an octal as a string.
316 char *octal_string(int i)
320 result = talloc_strdup(talloc_tos(), "-1");
323 result = talloc_asprintf(talloc_tos(), "0%o", i);
325 SMB_ASSERT(result != NULL);
331 Truncate a string at a specified length.
334 char *string_truncate(char *s, unsigned int length)
336 if (s && strlen(s) > length)
342 /***********************************************************************
343 Return the equivalent of doing strrchr 'n' times - always going
345 ***********************************************************************/
347 char *strnrchr_m(const char *s, char c, unsigned int n)
349 smb_ucs2_t *ws = NULL;
353 size_t converted_size;
355 if (!push_ucs2_talloc(talloc_tos(), &ws, s, &converted_size)) {
356 /* Too hard to try and get right. */
359 p = strnrchr_w(ws, UCS2_CHAR(c), n);
365 if (!pull_ucs2_talloc(talloc_tos(), &s2, ws, &converted_size)) {
367 /* Too hard to try and get right. */
370 ret = discard_const_p(char, (s+strlen(s2)));
376 static bool unix_strlower(const char *src, size_t srclen, char *dest, size_t destlen)
379 smb_ucs2_t *buffer = NULL;
382 if (!convert_string_talloc(talloc_tos(), CH_UNIX, CH_UTF16LE, src, srclen,
383 (void **)(void *)&buffer, &size))
387 if (!strlower_w(buffer) && (dest == src)) {
391 ret = convert_string(CH_UTF16LE, CH_UNIX, buffer, size, dest, destlen, &size);
396 #if 0 /* Alternate function that avoid talloc calls for ASCII and non ASCII */
399 Convert a string to lower case.
401 _PUBLIC_ void strlower_m(char *s)
404 struct smb_iconv_handle *iconv_handle;
406 iconv_handle = get_iconv_handle();
411 size_t c_size, c_size2;
412 codepoint_t c = next_codepoint_handle(iconv_handle, s, &c_size);
413 c_size2 = push_codepoint_handle(iconv_handle, d, tolower_m(c));
414 if (c_size2 > c_size) {
415 DEBUG(0,("FATAL: codepoint 0x%x (0x%x) expanded from %d to %d bytes in strlower_m\n",
416 c, tolower_m(c), (int)c_size, (int)c_size2));
417 smb_panic("codepoint expansion in strlower_m\n");
428 Convert a string to lower case.
431 bool strlower_m(char *s)
437 /* this is quite a common operation, so we want it to be
438 fast. We optimise for the ascii case, knowing that all our
439 supported multi-byte character sets are ascii-compatible
440 (ie. they match for the first 128 chars) */
442 while (*s && !(((unsigned char)s[0]) & 0x80)) {
443 *s = tolower_m((unsigned char)*s);
450 /* I assume that lowercased string takes the same number of bytes
451 * as source string even in UTF-8 encoding. (VIV) */
455 ret = unix_strlower(s,len,s,len);
456 /* Catch mb conversion errors that may not terminate. */
464 static bool unix_strupper(const char *src, size_t srclen, char *dest, size_t destlen)
470 if (!push_ucs2_talloc(talloc_tos(), &buffer, src, &size)) {
474 if (!strupper_w(buffer) && (dest == src)) {
479 ret = convert_string(CH_UTF16LE, CH_UNIX, buffer, size, dest, destlen, &size);
484 #if 0 /* Alternate function that avoid talloc calls for ASCII and non ASCII */
487 Convert a string to UPPER case.
489 _PUBLIC_ void strupper_m(char *s)
492 struct smb_iconv_handle *iconv_handle;
494 iconv_handle = get_iconv_handle();
499 size_t c_size, c_size2;
500 codepoint_t c = next_codepoint_handle(iconv_handle, s, &c_size);
501 c_size2 = push_codepoint_handle(iconv_handle, d, toupper_m(c));
502 if (c_size2 > c_size) {
503 DEBUG(0,("FATAL: codepoint 0x%x (0x%x) expanded from %d to %d bytes in strupper_m\n",
504 c, toupper_m(c), (int)c_size, (int)c_size2));
505 smb_panic("codepoint expansion in strupper_m\n");
516 Convert a string to upper case.
519 bool strupper_m(char *s)
524 /* this is quite a common operation, so we want it to be
525 fast. We optimise for the ascii case, knowing that all our
526 supported multi-byte character sets are ascii-compatible
527 (ie. they match for the first 128 chars) */
529 while (*s && !(((unsigned char)s[0]) & 0x80)) {
530 *s = toupper_ascii_fast_table[(unsigned char)s[0]];
537 /* I assume that uppercased string takes the same number of bytes
538 * as source string even in multibyte encoding. (VIV) */
540 ret = unix_strupper(s,len,s,len);
541 /* Catch mb conversion errors that may not terminate. */
549 Just a typesafety wrapper for snprintf into a fstring.
552 int fstr_sprintf(fstring s, const char *fmt, ...)
558 ret = vsnprintf(s, FSTRING_LEN, fmt, ap);
563 #define IPSTR_LIST_SEP ","
564 #define IPSTR_LIST_CHAR ','
567 * Add ip string representation to ipstr list. Used also
568 * as part of @function ipstr_list_make
570 * @param ipstr_list pointer to string containing ip list;
571 * MUST BE already allocated and IS reallocated if necessary
572 * @param ipstr_size pointer to current size of ipstr_list (might be changed
573 * as a result of reallocation)
574 * @param ip IP address which is to be added to list
575 * @return pointer to string appended with new ip and possibly
576 * reallocated to new length
579 static char *ipstr_list_add(char **ipstr_list, const struct ip_service *service)
581 char *new_ipstr = NULL;
582 char addr_buf[INET6_ADDRSTRLEN];
585 /* arguments checking */
586 if (!ipstr_list || !service) {
590 print_sockaddr(addr_buf,
594 /* attempt to convert ip to a string and append colon separator to it */
596 if (service->ss.ss_family == AF_INET) {
598 ret = asprintf(&new_ipstr, "%s%s%s:%d", *ipstr_list,
599 IPSTR_LIST_SEP, addr_buf,
603 ret = asprintf(&new_ipstr, "%s%s[%s]:%d", *ipstr_list,
604 IPSTR_LIST_SEP, addr_buf,
607 SAFE_FREE(*ipstr_list);
609 if (service->ss.ss_family == AF_INET) {
611 ret = asprintf(&new_ipstr, "%s:%d", addr_buf,
615 ret = asprintf(&new_ipstr, "[%s]:%d", addr_buf,
622 *ipstr_list = new_ipstr;
627 * Allocate and initialise an ipstr list using ip adresses
628 * passed as arguments.
630 * @param ipstr_list pointer to string meant to be allocated and set
631 * @param ip_list array of ip addresses to place in the list
632 * @param ip_count number of addresses stored in ip_list
633 * @return pointer to allocated ip string
636 char *ipstr_list_make(char **ipstr_list,
637 const struct ip_service *ip_list,
642 /* arguments checking */
643 if (!ip_list || !ipstr_list) {
649 /* process ip addresses given as arguments */
650 for (i = 0; i < ip_count; i++) {
651 *ipstr_list = ipstr_list_add(ipstr_list, &ip_list[i]);
654 return (*ipstr_list);
659 * Parse given ip string list into array of ip addresses
660 * (as ip_service structures)
661 * e.g. [IPv6]:port,192.168.1.100:389,192.168.1.78, ...
663 * @param ipstr ip string list to be parsed
664 * @param ip_list pointer to array of ip addresses which is
665 * allocated by this function and must be freed by caller
666 * @return number of successfully parsed addresses
669 int ipstr_list_parse(const char *ipstr_list, struct ip_service **ip_list)
672 char *token_str = NULL;
675 if (!ipstr_list || !ip_list)
678 count = count_chars(ipstr_list, IPSTR_LIST_CHAR) + 1;
679 if ( (*ip_list = SMB_MALLOC_ARRAY(struct ip_service, count)) == NULL ) {
680 DEBUG(0,("ipstr_list_parse: malloc failed for %lu entries\n",
681 (unsigned long)count));
685 frame = talloc_stackframe();
686 for ( i=0; next_token_talloc(frame, &ipstr_list, &token_str,
687 IPSTR_LIST_SEP) && i<count; i++ ) {
689 char *p = strrchr(token_str, ':');
693 (*ip_list)[i].port = atoi(p+1);
696 /* convert single token to ip address */
697 if (token_str[0] == '[') {
700 p = strchr(token_str, ']');
706 if (!interpret_string_addr(&(*ip_list)[i].ss,
717 * Safely free ip string list
719 * @param ipstr_list ip string list to be freed
722 void ipstr_list_free(char* ipstr_list)
724 SAFE_FREE(ipstr_list);
727 /* read a SMB_BIG_UINT from a string */
728 uint64_t STR_TO_SMB_BIG_UINT(const char *nptr, const char **entptr)
731 uint64_t val = (uint64_t)-1;
732 const char *p = nptr;
741 while (*p && isspace(*p))
744 sscanf(p,"%"SCNu64,&val);
746 while (*p && isdigit(*p))
754 /* Convert a size specification to a count of bytes. We accept the following
756 * bytes if there is no suffix
761 * pP whatever the ISO name for petabytes is
763 * Returns 0 if the string can't be converted.
765 uint64_t conv_str_size(const char * str)
771 if (str == NULL || *str == '\0') {
775 lval = smb_strtoull(str, &end, 10, &error, SMB_STR_STANDARD);
785 if (strwicmp(end, "K") == 0) {
787 } else if (strwicmp(end, "M") == 0) {
788 lval *= (1024ULL * 1024ULL);
789 } else if (strwicmp(end, "G") == 0) {
790 lval *= (1024ULL * 1024ULL *
792 } else if (strwicmp(end, "T") == 0) {
793 lval *= (1024ULL * 1024ULL *
795 } else if (strwicmp(end, "P") == 0) {
796 lval *= (1024ULL * 1024ULL *
807 * asprintf into a string and strupper_m it after that.
810 int asprintf_strupper_m(char **strp, const char *fmt, ...)
817 ret = vasprintf(&result, fmt, ap);
823 if (!strupper_m(result)) {
832 char *talloc_asprintf_strupper_m(TALLOC_CTX *t, const char *fmt, ...)
838 ret = talloc_vasprintf(t, fmt, ap);
844 if (!strupper_m(ret)) {
851 char *talloc_asprintf_strlower_m(TALLOC_CTX *t, const char *fmt, ...)
857 ret = talloc_vasprintf(t, fmt, ap);
863 if (!strlower_m(ret)) {
871 /********************************************************************
872 Check a string for any occurrences of a specified list of invalid
874 ********************************************************************/
876 bool validate_net_name( const char *name,
877 const char *invalid_chars,
886 for ( i=0; i<max_len && name[i]; i++ ) {
887 /* fail if strchr_m() finds one of the invalid characters */
888 if ( name[i] && strchr_m( invalid_chars, name[i] ) ) {
897 /*******************************************************************
898 Add a shell escape character '\' to any character not in a known list
899 of characters. UNIX charset format.
900 *******************************************************************/
902 #define INCLUDE_LIST "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_/ \t.,"
903 #define INSIDE_DQUOTE_LIST "$`\n\"\\"
905 char *escape_shell_string(const char *src)
907 size_t srclen = strlen(src);
908 char *ret = SMB_MALLOC_ARRAY(char, (srclen * 2) + 1);
910 bool in_s_quote = false;
911 bool in_d_quote = false;
912 bool next_escaped = false;
920 codepoint_t c = next_codepoint(src, &c_size);
922 if (c == INVALID_CODEPOINT) {
928 memcpy(dest, src, c_size);
931 next_escaped = false;
936 * Deal with backslash escaped state.
937 * This only lasts for one character.
942 next_escaped = false;
947 * Deal with single quote state. The
948 * only thing we care about is exiting
961 * Deal with double quote state. The most
962 * complex state. We must cope with \, meaning
963 * possibly escape next char (depending what it
964 * is), ", meaning exit this state, and possibly
965 * add an \ escape to any unprotected character
966 * (listed in INSIDE_DQUOTE_LIST).
972 * Next character might be escaped.
973 * We have to peek. Inside double
974 * quotes only INSIDE_DQUOTE_LIST
975 * characters are escaped by a \.
980 c = next_codepoint(&src[1], &c_size);
981 if (c == INVALID_CODEPOINT) {
987 * Don't escape the next char.
996 if (nextchar && strchr(INSIDE_DQUOTE_LIST,
1005 /* Exit double quote state. */
1012 * We know the character isn't \ or ",
1013 * so escape it if it's any of the other
1014 * possible unprotected characters.
1017 if (strchr(INSIDE_DQUOTE_LIST, (int)*src)) {
1025 * From here to the end of the loop we're
1026 * not in the single or double quote state.
1030 /* Next character must be escaped. */
1031 next_escaped = true;
1037 /* Go into single quote state. */
1044 /* Go into double quote state. */
1050 /* Check if we need to escape the character. */
1052 if (!strchr(INCLUDE_LIST, (int)*src)) {
1062 * This routine improves performance for operations temporarily acting on a
1063 * full path. It is equivalent to the much more expensive
1065 * talloc_asprintf(talloc_tos(), "%s/%s", dir, name)
1067 * This actually does make a difference in metadata-heavy workloads (i.e. the
1068 * "standard" client.txt nbench run.
1071 ssize_t full_path_tos(const char *dir, const char *name,
1072 char *tmpbuf, size_t tmpbuf_len,
1073 char **pdst, char **to_free)
1075 size_t dirlen, namelen, len;
1078 dirlen = strlen(dir);
1079 namelen = strlen(name);
1080 len = dirlen + namelen + 1;
1082 if (len < tmpbuf_len) {
1086 dst = talloc_array(talloc_tos(), char, len+1);
1093 memcpy(dst, dir, dirlen);
1095 memcpy(dst+dirlen+1, name, namelen+1);