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 2005
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program. If not, see <http://www.gnu.org/licenses/>.
25 #include "libcli/raw/smb.h"
26 #include "system/locale.h"
30 * @brief String utilities.
35 Trim the specified elements off the front and back of a string.
37 _PUBLIC_ bool trim_string(char *s, const char *front, const char *back)
44 /* Ignore null or empty strings. */
45 if (!s || (s[0] == '\0'))
48 front_len = front? strlen(front) : 0;
49 back_len = back? strlen(back) : 0;
54 while (len && strncmp(s, front, front_len)==0) {
55 /* Must use memmove here as src & dest can
56 * easily overlap. Found by valgrind. JRA. */
57 memmove(s, s+front_len, (len-front_len)+1);
64 while ((len >= back_len) && strncmp(s+len-back_len,back,back_len)==0) {
74 Find the number of 'c' chars in a string
76 _PUBLIC_ _PURE_ size_t count_chars(const char *s, char c)
91 Safe string copy into a known length string. maxlength does not
92 include the terminating zero.
94 _PUBLIC_ char *safe_strcpy(char *dest,const char *src, size_t maxlength)
99 DEBUG(0,("ERROR: NULL dest in safe_strcpy\n"));
104 /* We intentionally write out at the extremity of the destination
105 * string. If the destination is too short (e.g. pstrcpy into mallocd
106 * or fstring) then this should cause an error under a memory
108 dest[maxlength] = '\0';
109 if (PTR_DIFF(&len, dest) > 0) { /* check if destination is on the stack, ok if so */
110 log_suspicious_usage("safe_strcpy", src);
121 if (len > maxlength) {
122 DEBUG(0,("ERROR: string overflow by %u (%u - %u) in safe_strcpy [%.50s]\n",
123 (uint_t)(len-maxlength), (unsigned)len, (unsigned)maxlength, src));
127 memmove(dest, src, len);
133 Safe string cat into a string. maxlength does not
134 include the terminating zero.
136 _PUBLIC_ char *safe_strcat(char *dest, const char *src, size_t maxlength)
138 size_t src_len, dest_len;
141 DEBUG(0,("ERROR: NULL dest in safe_strcat\n"));
149 if (PTR_DIFF(&src_len, dest) > 0) { /* check if destination is on the stack, ok if so */
150 log_suspicious_usage("safe_strcat", src);
153 src_len = strlen(src);
154 dest_len = strlen(dest);
156 if (src_len + dest_len > maxlength) {
157 DEBUG(0,("ERROR: string overflow by %d in safe_strcat [%.50s]\n",
158 (int)(src_len + dest_len - maxlength), src));
159 if (maxlength > dest_len) {
160 memcpy(&dest[dest_len], src, maxlength - dest_len);
166 memcpy(&dest[dest_len], src, src_len);
167 dest[dest_len + src_len] = 0;
172 Routine to get hex characters and turn them into a 16 byte array.
173 the array can be variable length, and any non-hex-numeric
174 characters are skipped. "0xnn" or "0Xnn" is specially catered
177 valid examples: "0A5D15"; "0x15, 0x49, 0xa2"; "59\ta9\te3\n"
181 _PUBLIC_ size_t strhex_to_str(char *p, size_t p_len, const char *strhex, size_t strhex_len)
184 size_t num_chars = 0;
185 uint8_t lonybble, hinybble;
186 const char *hexchars = "0123456789ABCDEF";
187 char *p1 = NULL, *p2 = NULL;
189 for (i = 0; i < strhex_len && strhex[i] != 0; i++) {
190 if (strncasecmp(hexchars, "0x", 2) == 0) {
191 i++; /* skip two chars */
195 if (!(p1 = strchr(hexchars, toupper((unsigned char)strhex[i]))))
198 i++; /* next hex digit */
200 if (!(p2 = strchr(hexchars, toupper((unsigned char)strhex[i]))))
203 /* get the two nybbles */
204 hinybble = PTR_DIFF(p1, hexchars);
205 lonybble = PTR_DIFF(p2, hexchars);
207 if (num_chars >= p_len) {
211 p[num_chars] = (hinybble << 4) | lonybble;
221 * Parse a hex string and return a data blob.
223 _PUBLIC_ _PURE_ DATA_BLOB strhex_to_data_blob(TALLOC_CTX *mem_ctx, const char *strhex)
225 DATA_BLOB ret_blob = data_blob_talloc(mem_ctx, NULL, strlen(strhex)/2+1);
227 ret_blob.length = strhex_to_str((char *)ret_blob.data, ret_blob.length,
236 * Routine to print a buffer as HEX digits, into an allocated string.
238 _PUBLIC_ void hex_encode(const unsigned char *buff_in, size_t len, char **out_hex_buffer)
243 *out_hex_buffer = malloc_array_p(char, (len*2)+1);
244 hex_buffer = *out_hex_buffer;
246 for (i = 0; i < len; i++)
247 slprintf(&hex_buffer[i*2], 3, "%02X", buff_in[i]);
251 * talloc version of hex_encode()
253 _PUBLIC_ char *hex_encode_talloc(TALLOC_CTX *mem_ctx, const unsigned char *buff_in, size_t len)
258 hex_buffer = talloc_array(mem_ctx, char, (len*2)+1);
260 for (i = 0; i < len; i++)
261 slprintf(&hex_buffer[i*2], 3, "%02X", buff_in[i]);
267 Unescape a URL encoded string, in place.
270 _PUBLIC_ void rfc1738_unescape(char *buf)
274 while ((p=strchr(p,'+')))
279 while (p && *p && (p=strchr(p,'%'))) {
283 if (c1 >= '0' && c1 <= '9')
285 else if (c1 >= 'A' && c1 <= 'F')
287 else if (c1 >= 'a' && c1 <= 'f')
289 else {p++; continue;}
291 if (c2 >= '0' && c2 <= '9')
293 else if (c2 >= 'A' && c2 <= 'F')
295 else if (c2 >= 'a' && c2 <= 'f')
297 else {p++; continue;}
301 memmove(p+1, p+3, strlen(p+3)+1);
307 size_t valgrind_strlen(const char *s)
310 for(count = 0; *s++; count++)
318 format a string into length-prefixed dotted domain format, as used in NBT
319 and in some ADS structures
321 _PUBLIC_ const char *str_format_nbt_domain(TALLOC_CTX *mem_ctx, const char *s)
326 return talloc_strdup(mem_ctx, "");
328 ret = talloc_array(mem_ctx, char, strlen(s)+2);
333 memcpy(ret+1, s, strlen(s)+1);
336 for (i=0;ret[i];i++) {
338 char *p = strchr(ret+i+1, '.');
340 ret[i] = p-(ret+i+1);
342 ret[i] = strlen(ret+i+1);
351 * Add a string to an array of strings.
353 * num should be a pointer to an integer that holds the current
354 * number of elements in strings. It will be updated by this function.
356 _PUBLIC_ bool add_string_to_array(TALLOC_CTX *mem_ctx,
357 const char *str, const char ***strings, int *num)
359 char *dup_str = talloc_strdup(mem_ctx, str);
361 *strings = talloc_realloc(mem_ctx,
363 const char *, ((*num)+1));
365 if ((*strings == NULL) || (dup_str == NULL))
368 (*strings)[*num] = dup_str;
377 varient of strcmp() that handles NULL ptrs
379 _PUBLIC_ int strcmp_safe(const char *s1, const char *s2)
384 if (s1 == NULL || s2 == NULL) {
387 return strcmp(s1, s2);
392 return the number of bytes occupied by a buffer in ASCII format
393 the result includes the null termination
396 _PUBLIC_ size_t ascii_len_n(const char *src, size_t n)
400 len = strnlen(src, n);
410 Return a string representing a CIFS attribute for a file.
412 _PUBLIC_ char *attrib_string(TALLOC_CTX *mem_ctx, uint32_t attrib)
419 {'V', FILE_ATTRIBUTE_VOLUME},
420 {'D', FILE_ATTRIBUTE_DIRECTORY},
421 {'A', FILE_ATTRIBUTE_ARCHIVE},
422 {'H', FILE_ATTRIBUTE_HIDDEN},
423 {'S', FILE_ATTRIBUTE_SYSTEM},
424 {'N', FILE_ATTRIBUTE_NORMAL},
425 {'R', FILE_ATTRIBUTE_READONLY},
426 {'d', FILE_ATTRIBUTE_DEVICE},
427 {'t', FILE_ATTRIBUTE_TEMPORARY},
428 {'s', FILE_ATTRIBUTE_SPARSE},
429 {'r', FILE_ATTRIBUTE_REPARSE_POINT},
430 {'c', FILE_ATTRIBUTE_COMPRESSED},
431 {'o', FILE_ATTRIBUTE_OFFLINE},
432 {'n', FILE_ATTRIBUTE_NONINDEXED},
433 {'e', FILE_ATTRIBUTE_ENCRYPTED}
437 ret = talloc_array(mem_ctx, char, ARRAY_SIZE(attr_strs)+1);
442 for (len=i=0; i<ARRAY_SIZE(attr_strs); i++) {
443 if (attrib & attr_strs[i].attr) {
444 ret[len++] = attr_strs[i].c;
454 Set a boolean variable from the text value stored in the passed string.
455 Returns true in success, false if the passed string does not correctly
459 _PUBLIC_ bool set_boolean(const char *boolean_string, bool *boolean)
461 if (strwicmp(boolean_string, "yes") == 0 ||
462 strwicmp(boolean_string, "true") == 0 ||
463 strwicmp(boolean_string, "on") == 0 ||
464 strwicmp(boolean_string, "1") == 0) {
467 } else if (strwicmp(boolean_string, "no") == 0 ||
468 strwicmp(boolean_string, "false") == 0 ||
469 strwicmp(boolean_string, "off") == 0 ||
470 strwicmp(boolean_string, "0") == 0) {
478 * Parse a string containing a boolean value.
480 * val will be set to the read value.
482 * @retval true if a boolean value was parsed, false otherwise.
484 _PUBLIC_ bool conv_str_bool(const char * str, bool * val)
489 if (str == NULL || *str == '\0') {
493 lval = strtol(str, &end, 10 /* base */);
494 if (end == NULL || *end != '\0' || end == str) {
495 return set_boolean(str, val);
498 *val = (lval) ? true : false;
503 * Convert a size specification like 16K into an integral number of bytes.
505 _PUBLIC_ bool conv_str_size(const char * str, uint64_t * val)
508 unsigned long long lval;
510 if (str == NULL || *str == '\0') {
514 lval = strtoull(str, &end, 10 /* base */);
515 if (end == NULL || end == str) {
520 if (strwicmp(end, "K") == 0) {
522 } else if (strwicmp(end, "M") == 0) {
523 lval *= (1024ULL * 1024ULL);
524 } else if (strwicmp(end, "G") == 0) {
525 lval *= (1024ULL * 1024ULL * 1024ULL);
526 } else if (strwicmp(end, "T") == 0) {
527 lval *= (1024ULL * 1024ULL * 1024ULL * 1024ULL);
528 } else if (strwicmp(end, "P") == 0) {
529 lval *= (1024ULL * 1024ULL * 1024ULL * 1024ULL * 1024ULL);
535 *val = (uint64_t)lval;
540 * Parse a uint64_t value from a string
542 * val will be set to the value read.
544 * @retval true if parsing was successful, false otherwise
546 _PUBLIC_ bool conv_str_u64(const char * str, uint64_t * val)
549 unsigned long long lval;
551 if (str == NULL || *str == '\0') {
555 lval = strtoull(str, &end, 10 /* base */);
556 if (end == NULL || *end != '\0' || end == str) {
560 *val = (uint64_t)lval;
565 return the number of bytes occupied by a buffer in CH_UTF16 format
566 the result includes the null termination
568 _PUBLIC_ size_t utf16_len(const void *buf)
572 for (len = 0; SVAL(buf,len); len += 2) ;
578 return the number of bytes occupied by a buffer in CH_UTF16 format
579 the result includes the null termination
582 _PUBLIC_ size_t utf16_len_n(const void *src, size_t n)
586 for (len = 0; (len+2 < n) && SVAL(src, len); len += 2) ;
595 _PUBLIC_ size_t ucs2_align(const void *base_ptr, const void *p, int flags)
597 if (flags & (STR_NOALIGN|STR_ASCII))
599 return PTR_DIFF(p, base_ptr) & 1;
603 Do a case-insensitive, whitespace-ignoring string compare.
605 _PUBLIC_ int strwicmp(const char *psz1, const char *psz2)
607 /* if BOTH strings are NULL, return TRUE, if ONE is NULL return */
608 /* appropriate value. */
611 else if (psz1 == NULL)
613 else if (psz2 == NULL)
616 /* sync the strings on first non-whitespace */
618 while (isspace((int)*psz1))
620 while (isspace((int)*psz2))
622 if (toupper((unsigned char)*psz1) != toupper((unsigned char)*psz2)
629 return (*psz1 - *psz2);
635 _PUBLIC_ void string_replace(char *s, char oldc, char newc)
638 if (*s == oldc) *s = newc;
646 * @note The comparison is case-insensitive.
648 _PUBLIC_ bool strequal(const char *s1, const char *s2)
655 return strcasecmp(s1,s2) == 0;