lib/util: fix strhex_to_data_blob to use data_blob_talloc.
[samba.git] / lib / util / util_str.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Samba utility functions
4    
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
9    
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.
14    
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.
19    
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/>.
22 */
23
24 #include "includes.h"
25 #include "libcli/raw/smb.h"
26 #include "system/locale.h"
27
28 /**
29  * @file
30  * @brief String utilities.
31  **/
32
33
34 /**
35  Trim the specified elements off the front and back of a string.
36 **/
37 _PUBLIC_ bool trim_string(char *s, const char *front, const char *back)
38 {
39         bool ret = false;
40         size_t front_len;
41         size_t back_len;
42         size_t len;
43
44         /* Ignore null or empty strings. */
45         if (!s || (s[0] == '\0'))
46                 return false;
47
48         front_len       = front? strlen(front) : 0;
49         back_len        = back? strlen(back) : 0;
50
51         len = strlen(s);
52
53         if (front_len) {
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);
58                         len -= front_len;
59                         ret=true;
60                 }
61         }
62         
63         if (back_len) {
64                 while ((len >= back_len) && strncmp(s+len-back_len,back,back_len)==0) {
65                         s[len-back_len]='\0';
66                         len -= back_len;
67                         ret=true;
68                 }
69         }
70         return ret;
71 }
72
73 /**
74  Find the number of 'c' chars in a string
75 **/
76 _PUBLIC_ _PURE_ size_t count_chars(const char *s, char c)
77 {
78         size_t count = 0;
79
80         while (*s) {
81                 if (*s == c) count++;
82                 s ++;
83         }
84
85         return count;
86 }
87
88
89
90 /**
91  Safe string copy into a known length string. maxlength does not
92  include the terminating zero.
93 **/
94 _PUBLIC_ char *safe_strcpy(char *dest,const char *src, size_t maxlength)
95 {
96         size_t len;
97
98         if (!dest) {
99                 DEBUG(0,("ERROR: NULL dest in safe_strcpy\n"));
100                 return NULL;
101         }
102
103 #ifdef DEVELOPER
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
107          * checker. */
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);
111         }
112 #endif
113
114         if (!src) {
115                 *dest = 0;
116                 return dest;
117         }  
118
119         len = strlen(src);
120
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));
124                 len = maxlength;
125         }
126       
127         memmove(dest, src, len);
128         dest[len] = 0;
129         return dest;
130 }  
131
132 /**
133  Safe string cat into a string. maxlength does not
134  include the terminating zero.
135 **/
136 _PUBLIC_ char *safe_strcat(char *dest, const char *src, size_t maxlength)
137 {
138         size_t src_len, dest_len;
139
140         if (!dest) {
141                 DEBUG(0,("ERROR: NULL dest in safe_strcat\n"));
142                 return NULL;
143         }
144
145         if (!src)
146                 return dest;
147         
148 #ifdef DEVELOPER
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);
151         }
152 #endif
153         src_len = strlen(src);
154         dest_len = strlen(dest);
155
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);
161                 }
162                 dest[maxlength] = 0;
163                 return NULL;
164         }
165         
166         memcpy(&dest[dest_len], src, src_len);
167         dest[dest_len + src_len] = 0;
168         return dest;
169 }
170
171 /**
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
175  for.
176
177  valid examples: "0A5D15"; "0x15, 0x49, 0xa2"; "59\ta9\te3\n"
178
179
180 **/
181 _PUBLIC_ size_t strhex_to_str(char *p, size_t p_len, const char *strhex, size_t strhex_len)
182 {
183         size_t i;
184         size_t num_chars = 0;
185         uint8_t   lonybble, hinybble;
186         const char     *hexchars = "0123456789ABCDEF";
187         char           *p1 = NULL, *p2 = NULL;
188
189         for (i = 0; i < strhex_len && strhex[i] != 0; i++) {
190                 if (strncasecmp(hexchars, "0x", 2) == 0) {
191                         i++; /* skip two chars */
192                         continue;
193                 }
194
195                 if (!(p1 = strchr(hexchars, toupper((unsigned char)strhex[i]))))
196                         break;
197
198                 i++; /* next hex digit */
199
200                 if (!(p2 = strchr(hexchars, toupper((unsigned char)strhex[i]))))
201                         break;
202
203                 /* get the two nybbles */
204                 hinybble = PTR_DIFF(p1, hexchars);
205                 lonybble = PTR_DIFF(p2, hexchars);
206
207                 if (num_chars >= p_len) {
208                         break;
209                 }
210
211                 p[num_chars] = (hinybble << 4) | lonybble;
212                 num_chars++;
213
214                 p1 = NULL;
215                 p2 = NULL;
216         }
217         return num_chars;
218 }
219
220 /** 
221  * Parse a hex string and return a data blob. 
222  */
223 _PUBLIC_ _PURE_ DATA_BLOB strhex_to_data_blob(TALLOC_CTX *mem_ctx, const char *strhex) 
224 {
225         DATA_BLOB ret_blob = data_blob_talloc(mem_ctx, NULL, strlen(strhex)/2+1);
226
227         ret_blob.length = strhex_to_str((char *)ret_blob.data, ret_blob.length,
228                                         strhex,
229                                         strlen(strhex));
230
231         return ret_blob;
232 }
233
234
235 /**
236  * Routine to print a buffer as HEX digits, into an allocated string.
237  */
238 _PUBLIC_ void hex_encode(const unsigned char *buff_in, size_t len, char **out_hex_buffer)
239 {
240         int i;
241         char *hex_buffer;
242
243         *out_hex_buffer = malloc_array_p(char, (len*2)+1);
244         hex_buffer = *out_hex_buffer;
245
246         for (i = 0; i < len; i++)
247                 slprintf(&hex_buffer[i*2], 3, "%02X", buff_in[i]);
248 }
249
250 /**
251  * talloc version of hex_encode()
252  */
253 _PUBLIC_ char *hex_encode_talloc(TALLOC_CTX *mem_ctx, const unsigned char *buff_in, size_t len)
254 {
255         int i;
256         char *hex_buffer;
257
258         hex_buffer = talloc_array(mem_ctx, char, (len*2)+1);
259
260         for (i = 0; i < len; i++)
261                 slprintf(&hex_buffer[i*2], 3, "%02X", buff_in[i]);
262
263         return hex_buffer;
264 }
265
266 /**
267  Unescape a URL encoded string, in place.
268 **/
269
270 _PUBLIC_ void rfc1738_unescape(char *buf)
271 {
272         char *p=buf;
273
274         while ((p=strchr(p,'+')))
275                 *p = ' ';
276
277         p = buf;
278
279         while (p && *p && (p=strchr(p,'%'))) {
280                 int c1 = p[1];
281                 int c2 = p[2];
282
283                 if (c1 >= '0' && c1 <= '9')
284                         c1 = c1 - '0';
285                 else if (c1 >= 'A' && c1 <= 'F')
286                         c1 = 10 + c1 - 'A';
287                 else if (c1 >= 'a' && c1 <= 'f')
288                         c1 = 10 + c1 - 'a';
289                 else {p++; continue;}
290
291                 if (c2 >= '0' && c2 <= '9')
292                         c2 = c2 - '0';
293                 else if (c2 >= 'A' && c2 <= 'F')
294                         c2 = 10 + c2 - 'A';
295                 else if (c2 >= 'a' && c2 <= 'f')
296                         c2 = 10 + c2 - 'a';
297                 else {p++; continue;}
298                         
299                 *p = (c1<<4) | c2;
300
301                 memmove(p+1, p+3, strlen(p+3)+1);
302                 p++;
303         }
304 }
305
306 #ifdef VALGRIND
307 size_t valgrind_strlen(const char *s)
308 {
309         size_t count;
310         for(count = 0; *s++; count++)
311                 ;
312         return count;
313 }
314 #endif
315
316
317 /**
318   format a string into length-prefixed dotted domain format, as used in NBT
319   and in some ADS structures
320 **/
321 _PUBLIC_ const char *str_format_nbt_domain(TALLOC_CTX *mem_ctx, const char *s)
322 {
323         char *ret;
324         int i;
325         if (!s || !*s) {
326                 return talloc_strdup(mem_ctx, "");
327         }
328         ret = talloc_array(mem_ctx, char, strlen(s)+2);
329         if (!ret) {
330                 return ret;
331         }
332         
333         memcpy(ret+1, s, strlen(s)+1);
334         ret[0] = '.';
335
336         for (i=0;ret[i];i++) {
337                 if (ret[i] == '.') {
338                         char *p = strchr(ret+i+1, '.');
339                         if (p) {
340                                 ret[i] = p-(ret+i+1);
341                         } else {
342                                 ret[i] = strlen(ret+i+1);
343                         }
344                 }
345         }
346
347         return ret;
348 }
349
350 /**
351  * Add a string to an array of strings.
352  *
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.
355  */
356 _PUBLIC_ bool add_string_to_array(TALLOC_CTX *mem_ctx,
357                          const char *str, const char ***strings, int *num)
358 {
359         char *dup_str = talloc_strdup(mem_ctx, str);
360
361         *strings = talloc_realloc(mem_ctx,
362                                     *strings,
363                                     const char *, ((*num)+1));
364
365         if ((*strings == NULL) || (dup_str == NULL))
366                 return false;
367
368         (*strings)[*num] = dup_str;
369         *num += 1;
370
371         return true;
372 }
373
374
375
376 /**
377   varient of strcmp() that handles NULL ptrs
378 **/
379 _PUBLIC_ int strcmp_safe(const char *s1, const char *s2)
380 {
381         if (s1 == s2) {
382                 return 0;
383         }
384         if (s1 == NULL || s2 == NULL) {
385                 return s1?-1:1;
386         }
387         return strcmp(s1, s2);
388 }
389
390
391 /**
392 return the number of bytes occupied by a buffer in ASCII format
393 the result includes the null termination
394 limited by 'n' bytes
395 **/
396 _PUBLIC_ size_t ascii_len_n(const char *src, size_t n)
397 {
398         size_t len;
399
400         len = strnlen(src, n);
401         if (len+1 <= n) {
402                 len += 1;
403         }
404
405         return len;
406 }
407
408
409 /**
410  Return a string representing a CIFS attribute for a file.
411 **/
412 _PUBLIC_ char *attrib_string(TALLOC_CTX *mem_ctx, uint32_t attrib)
413 {
414         int i, len;
415         const struct {
416                 char c;
417                 uint16_t attr;
418         } attr_strs[] = {
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}
434         };
435         char *ret;
436
437         ret = talloc_array(mem_ctx, char, ARRAY_SIZE(attr_strs)+1);
438         if (!ret) {
439                 return NULL;
440         }
441
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;
445                 }
446         }
447
448         ret[len] = 0;
449
450         return ret;
451 }
452
453 /**
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 
456  represent a boolean.
457 **/
458
459 _PUBLIC_ bool set_boolean(const char *boolean_string, bool *boolean)
460 {
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) {
465                 *boolean = true;
466                 return true;
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) {
471                 *boolean = false;
472                 return true;
473         }
474         return false;
475 }
476
477 /**
478  * Parse a string containing a boolean value.
479  *
480  * val will be set to the read value.
481  *
482  * @retval true if a boolean value was parsed, false otherwise.
483  */
484 _PUBLIC_ bool conv_str_bool(const char * str, bool * val)
485 {
486         char *  end = NULL;
487         long    lval;
488
489         if (str == NULL || *str == '\0') {
490                 return false;
491         }
492
493         lval = strtol(str, &end, 10 /* base */);
494         if (end == NULL || *end != '\0' || end == str) {
495                 return set_boolean(str, val);
496         }
497
498         *val = (lval) ? true : false;
499         return true;
500 }
501
502 /**
503  * Convert a size specification like 16K into an integral number of bytes. 
504  **/
505 _PUBLIC_ bool conv_str_size(const char * str, uint64_t * val)
506 {
507         char *              end = NULL;
508         unsigned long long  lval;
509
510         if (str == NULL || *str == '\0') {
511                 return false;
512         }
513
514         lval = strtoull(str, &end, 10 /* base */);
515         if (end == NULL || end == str) {
516                 return false;
517         }
518
519         if (*end) {
520                 if (strwicmp(end, "K") == 0) {
521                         lval *= 1024ULL;
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);
530                 } else {
531                         return false;
532                 }
533         }
534
535         *val = (uint64_t)lval;
536         return true;
537 }
538
539 /**
540  * Parse a uint64_t value from a string
541  *
542  * val will be set to the value read.
543  *
544  * @retval true if parsing was successful, false otherwise
545  */
546 _PUBLIC_ bool conv_str_u64(const char * str, uint64_t * val)
547 {
548         char *              end = NULL;
549         unsigned long long  lval;
550
551         if (str == NULL || *str == '\0') {
552                 return false;
553         }
554
555         lval = strtoull(str, &end, 10 /* base */);
556         if (end == NULL || *end != '\0' || end == str) {
557                 return false;
558         }
559
560         *val = (uint64_t)lval;
561         return true;
562 }
563
564 /**
565 return the number of bytes occupied by a buffer in CH_UTF16 format
566 the result includes the null termination
567 **/
568 _PUBLIC_ size_t utf16_len(const void *buf)
569 {
570         size_t len;
571
572         for (len = 0; SVAL(buf,len); len += 2) ;
573
574         return len + 2;
575 }
576
577 /**
578 return the number of bytes occupied by a buffer in CH_UTF16 format
579 the result includes the null termination
580 limited by 'n' bytes
581 **/
582 _PUBLIC_ size_t utf16_len_n(const void *src, size_t n)
583 {
584         size_t len;
585
586         for (len = 0; (len+2 < n) && SVAL(src, len); len += 2) ;
587
588         if (len+2 <= n) {
589                 len += 2;
590         }
591
592         return len;
593 }
594
595 _PUBLIC_ size_t ucs2_align(const void *base_ptr, const void *p, int flags)
596 {
597         if (flags & (STR_NOALIGN|STR_ASCII))
598                 return 0;
599         return PTR_DIFF(p, base_ptr) & 1;
600 }
601
602 /**
603 Do a case-insensitive, whitespace-ignoring string compare.
604 **/
605 _PUBLIC_ int strwicmp(const char *psz1, const char *psz2)
606 {
607         /* if BOTH strings are NULL, return TRUE, if ONE is NULL return */
608         /* appropriate value. */
609         if (psz1 == psz2)
610                 return (0);
611         else if (psz1 == NULL)
612                 return (-1);
613         else if (psz2 == NULL)
614                 return (1);
615
616         /* sync the strings on first non-whitespace */
617         while (1) {
618                 while (isspace((int)*psz1))
619                         psz1++;
620                 while (isspace((int)*psz2))
621                         psz2++;
622                 if (toupper((unsigned char)*psz1) != toupper((unsigned char)*psz2) 
623                     || *psz1 == '\0'
624                     || *psz2 == '\0')
625                         break;
626                 psz1++;
627                 psz2++;
628         }
629         return (*psz1 - *psz2);
630 }
631
632 /**
633  String replace.
634 **/
635 _PUBLIC_ void string_replace(char *s, char oldc, char newc)
636 {
637         while (*s) {
638                 if (*s == oldc) *s = newc;
639                 s++;
640         }
641 }
642
643 /**
644  * Compare 2 strings.
645  *
646  * @note The comparison is case-insensitive.
647  **/
648 _PUBLIC_ bool strequal(const char *s1, const char *s2)
649 {
650         if (s1 == s2)
651                 return true;
652         if (!s1 || !s2)
653                 return false;
654   
655         return strcasecmp(s1,s2) == 0;
656 }