Provide malloc_array() in Samba 4.
[ab/samba.git/.git] / source4 / 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 len, const char *strhex)
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 < 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                 p[num_chars] = (hinybble << 4) | lonybble;
208                 num_chars++;
209
210                 p1 = NULL;
211                 p2 = NULL;
212         }
213         return num_chars;
214 }
215
216 /** 
217  * Parse a hex string and return a data blob. 
218  */
219 _PUBLIC_ _PURE_ DATA_BLOB strhex_to_data_blob(const char *strhex) 
220 {
221         DATA_BLOB ret_blob = data_blob(NULL, strlen(strhex)/2+1);
222
223         ret_blob.length = strhex_to_str((char *)ret_blob.data,  
224                                         strlen(strhex), 
225                                         strhex);
226
227         return ret_blob;
228 }
229
230
231 /**
232  * Routine to print a buffer as HEX digits, into an allocated string.
233  */
234 _PUBLIC_ void hex_encode(const unsigned char *buff_in, size_t len, char **out_hex_buffer)
235 {
236         int i;
237         char *hex_buffer;
238
239         *out_hex_buffer = malloc_array_p(char, (len*2)+1);
240         hex_buffer = *out_hex_buffer;
241
242         for (i = 0; i < len; i++)
243                 slprintf(&hex_buffer[i*2], 3, "%02X", buff_in[i]);
244 }
245
246 /**
247  * talloc version of hex_encode()
248  */
249 _PUBLIC_ char *hex_encode_talloc(TALLOC_CTX *mem_ctx, const unsigned char *buff_in, size_t len)
250 {
251         int i;
252         char *hex_buffer;
253
254         hex_buffer = talloc_array(mem_ctx, char, (len*2)+1);
255
256         for (i = 0; i < len; i++)
257                 slprintf(&hex_buffer[i*2], 3, "%02X", buff_in[i]);
258
259         return hex_buffer;
260 }
261
262 /**
263  Substitute a string for a pattern in another string. Make sure there is 
264  enough room!
265
266  This routine looks for pattern in s and replaces it with 
267  insert. It may do multiple replacements.
268
269  Any of " ; ' $ or ` in the insert string are replaced with _
270  if len==0 then the string cannot be extended. This is different from the old
271  use of len==0 which was for no length checks to be done.
272 **/
273
274 _PUBLIC_ void string_sub(char *s, const char *pattern, const char *insert, size_t len)
275 {
276         char *p;
277         ssize_t ls, lp, li, i;
278
279         if (!insert || !pattern || !*pattern || !s)
280                 return;
281
282         ls = (ssize_t)strlen(s);
283         lp = (ssize_t)strlen(pattern);
284         li = (ssize_t)strlen(insert);
285
286         if (len == 0)
287                 len = ls + 1; /* len is number of *bytes* */
288
289         while (lp <= ls && (p = strstr(s, pattern))) {
290                 if (ls + (li-lp) >= len) {
291                         DEBUG(0,("ERROR: string overflow by %d in string_sub(%.50s, %d)\n", 
292                                  (int)(ls + (li-lp) - len),
293                                  pattern, (int)len));
294                         break;
295                 }
296                 if (li != lp) {
297                         memmove(p+li,p+lp,strlen(p+lp)+1);
298                 }
299                 for (i=0;i<li;i++) {
300                         switch (insert[i]) {
301                         case '`':
302                         case '"':
303                         case '\'':
304                         case ';':
305                         case '$':
306                         case '%':
307                         case '\r':
308                         case '\n':
309                                 p[i] = '_';
310                                 break;
311                         default:
312                                 p[i] = insert[i];
313                         }
314                 }
315                 s = p + li;
316                 ls += (li-lp);
317         }
318 }
319
320 /**
321  * Talloc'ed version of string_sub
322  */
323 _PUBLIC_ char *string_sub_talloc(TALLOC_CTX *mem_ctx, const char *s, 
324                                 const char *pattern, const char *insert)
325 {
326         const char *p;
327         char *ret;
328         size_t len, alloc_len;
329
330         if (insert == NULL || pattern == NULL || !*pattern || s == NULL)
331                 return NULL;
332
333         /* determine length needed */
334         len = strlen(s);
335         
336         for (p = strstr(s, pattern); p != NULL; 
337              p = strstr(p+strlen(pattern), pattern)) {
338                 len += strlen(insert) - strlen(pattern);
339         }
340
341         alloc_len = MAX(len, strlen(s))+1;
342         ret = talloc_array(mem_ctx, char, alloc_len);
343         if (ret == NULL)
344                 return NULL;
345         strncpy(ret, s, alloc_len);
346         string_sub(ret, pattern, insert, alloc_len);
347
348         ret = talloc_realloc(mem_ctx, ret, char, len+1);
349         if (ret == NULL)
350                 return NULL;
351
352         SMB_ASSERT(ret[len] == '\0');
353
354         return ret;
355 }
356
357 /**
358  Similar to string_sub() but allows for any character to be substituted. 
359  Use with caution!
360  if len==0 then the string cannot be extended. This is different from the old
361  use of len==0 which was for no length checks to be done.
362 **/
363
364 _PUBLIC_ void all_string_sub(char *s,const char *pattern,const char *insert, size_t len)
365 {
366         char *p;
367         ssize_t ls,lp,li;
368
369         if (!insert || !pattern || !s)
370                 return;
371
372         ls = (ssize_t)strlen(s);
373         lp = (ssize_t)strlen(pattern);
374         li = (ssize_t)strlen(insert);
375
376         if (!*pattern)
377                 return;
378         
379         if (len == 0)
380                 len = ls + 1; /* len is number of *bytes* */
381         
382         while (lp <= ls && (p = strstr(s,pattern))) {
383                 if (ls + (li-lp) >= len) {
384                         DEBUG(0,("ERROR: string overflow by %d in all_string_sub(%.50s, %d)\n", 
385                                  (int)(ls + (li-lp) - len),
386                                  pattern, (int)len));
387                         break;
388                 }
389                 if (li != lp) {
390                         memmove(p+li,p+lp,strlen(p+lp)+1);
391                 }
392                 memcpy(p, insert, li);
393                 s = p + li;
394                 ls += (li-lp);
395         }
396 }
397
398
399
400 /**
401  Unescape a URL encoded string, in place.
402 **/
403
404 _PUBLIC_ void rfc1738_unescape(char *buf)
405 {
406         char *p=buf;
407
408         while ((p=strchr(p,'+')))
409                 *p = ' ';
410
411         p = buf;
412
413         while (p && *p && (p=strchr(p,'%'))) {
414                 int c1 = p[1];
415                 int c2 = p[2];
416
417                 if (c1 >= '0' && c1 <= '9')
418                         c1 = c1 - '0';
419                 else if (c1 >= 'A' && c1 <= 'F')
420                         c1 = 10 + c1 - 'A';
421                 else if (c1 >= 'a' && c1 <= 'f')
422                         c1 = 10 + c1 - 'a';
423                 else {p++; continue;}
424
425                 if (c2 >= '0' && c2 <= '9')
426                         c2 = c2 - '0';
427                 else if (c2 >= 'A' && c2 <= 'F')
428                         c2 = 10 + c2 - 'A';
429                 else if (c2 >= 'a' && c2 <= 'f')
430                         c2 = 10 + c2 - 'a';
431                 else {p++; continue;}
432                         
433                 *p = (c1<<4) | c2;
434
435                 memmove(p+1, p+3, strlen(p+3)+1);
436                 p++;
437         }
438 }
439
440 #ifdef VALGRIND
441 size_t valgrind_strlen(const char *s)
442 {
443         size_t count;
444         for(count = 0; *s++; count++)
445                 ;
446         return count;
447 }
448 #endif
449
450
451 /**
452   format a string into length-prefixed dotted domain format, as used in NBT
453   and in some ADS structures
454 **/
455 _PUBLIC_ const char *str_format_nbt_domain(TALLOC_CTX *mem_ctx, const char *s)
456 {
457         char *ret;
458         int i;
459         if (!s || !*s) {
460                 return talloc_strdup(mem_ctx, "");
461         }
462         ret = talloc_array(mem_ctx, char, strlen(s)+2);
463         if (!ret) {
464                 return ret;
465         }
466         
467         memcpy(ret+1, s, strlen(s)+1);
468         ret[0] = '.';
469
470         for (i=0;ret[i];i++) {
471                 if (ret[i] == '.') {
472                         char *p = strchr(ret+i+1, '.');
473                         if (p) {
474                                 ret[i] = p-(ret+i+1);
475                         } else {
476                                 ret[i] = strlen(ret+i+1);
477                         }
478                 }
479         }
480
481         return ret;
482 }
483
484 /**
485  * Add a string to an array of strings.
486  *
487  * num should be a pointer to an integer that holds the current 
488  * number of elements in strings. It will be updated by this function.
489  */
490 _PUBLIC_ bool add_string_to_array(TALLOC_CTX *mem_ctx,
491                          const char *str, const char ***strings, int *num)
492 {
493         char *dup_str = talloc_strdup(mem_ctx, str);
494
495         *strings = talloc_realloc(mem_ctx,
496                                     *strings,
497                                     const char *, ((*num)+1));
498
499         if ((*strings == NULL) || (dup_str == NULL))
500                 return false;
501
502         (*strings)[*num] = dup_str;
503         *num += 1;
504
505         return true;
506 }
507
508
509
510 /**
511   varient of strcmp() that handles NULL ptrs
512 **/
513 _PUBLIC_ int strcmp_safe(const char *s1, const char *s2)
514 {
515         if (s1 == s2) {
516                 return 0;
517         }
518         if (s1 == NULL || s2 == NULL) {
519                 return s1?-1:1;
520         }
521         return strcmp(s1, s2);
522 }
523
524
525 /**
526 return the number of bytes occupied by a buffer in ASCII format
527 the result includes the null termination
528 limited by 'n' bytes
529 **/
530 _PUBLIC_ size_t ascii_len_n(const char *src, size_t n)
531 {
532         size_t len;
533
534         len = strnlen(src, n);
535         if (len+1 <= n) {
536                 len += 1;
537         }
538
539         return len;
540 }
541
542
543 /**
544  Return a string representing a CIFS attribute for a file.
545 **/
546 _PUBLIC_ char *attrib_string(TALLOC_CTX *mem_ctx, uint32_t attrib)
547 {
548         int i, len;
549         const struct {
550                 char c;
551                 uint16_t attr;
552         } attr_strs[] = {
553                 {'V', FILE_ATTRIBUTE_VOLUME},
554                 {'D', FILE_ATTRIBUTE_DIRECTORY},
555                 {'A', FILE_ATTRIBUTE_ARCHIVE},
556                 {'H', FILE_ATTRIBUTE_HIDDEN},
557                 {'S', FILE_ATTRIBUTE_SYSTEM},
558                 {'N', FILE_ATTRIBUTE_NORMAL},
559                 {'R', FILE_ATTRIBUTE_READONLY},
560                 {'d', FILE_ATTRIBUTE_DEVICE},
561                 {'t', FILE_ATTRIBUTE_TEMPORARY},
562                 {'s', FILE_ATTRIBUTE_SPARSE},
563                 {'r', FILE_ATTRIBUTE_REPARSE_POINT},
564                 {'c', FILE_ATTRIBUTE_COMPRESSED},
565                 {'o', FILE_ATTRIBUTE_OFFLINE},
566                 {'n', FILE_ATTRIBUTE_NONINDEXED},
567                 {'e', FILE_ATTRIBUTE_ENCRYPTED}
568         };
569         char *ret;
570
571         ret = talloc_array(mem_ctx, char, ARRAY_SIZE(attr_strs)+1);
572         if (!ret) {
573                 return NULL;
574         }
575
576         for (len=i=0; i<ARRAY_SIZE(attr_strs); i++) {
577                 if (attrib & attr_strs[i].attr) {
578                         ret[len++] = attr_strs[i].c;
579                 }
580         }
581
582         ret[len] = 0;
583
584         return ret;
585 }
586
587 /**
588  Set a boolean variable from the text value stored in the passed string.
589  Returns true in success, false if the passed string does not correctly 
590  represent a boolean.
591 **/
592
593 _PUBLIC_ bool set_boolean(const char *boolean_string, bool *boolean)
594 {
595         if (strwicmp(boolean_string, "yes") == 0 ||
596             strwicmp(boolean_string, "true") == 0 ||
597             strwicmp(boolean_string, "on") == 0 ||
598             strwicmp(boolean_string, "1") == 0) {
599                 *boolean = true;
600                 return true;
601         } else if (strwicmp(boolean_string, "no") == 0 ||
602                    strwicmp(boolean_string, "false") == 0 ||
603                    strwicmp(boolean_string, "off") == 0 ||
604                    strwicmp(boolean_string, "0") == 0) {
605                 *boolean = false;
606                 return true;
607         }
608         return false;
609 }
610
611 /**
612  * Parse a string containing a boolean value.
613  *
614  * val will be set to the read value.
615  *
616  * @retval true if a boolean value was parsed, false otherwise.
617  */
618 _PUBLIC_ bool conv_str_bool(const char * str, bool * val)
619 {
620         char *  end = NULL;
621         long    lval;
622
623         if (str == NULL || *str == '\0') {
624                 return false;
625         }
626
627         lval = strtol(str, &end, 10 /* base */);
628         if (end == NULL || *end != '\0' || end == str) {
629                 return set_boolean(str, val);
630         }
631
632         *val = (lval) ? true : false;
633         return true;
634 }
635
636 /**
637  * Convert a size specification like 16K into an integral number of bytes. 
638  **/
639 _PUBLIC_ bool conv_str_size(const char * str, uint64_t * val)
640 {
641         char *              end = NULL;
642         unsigned long long  lval;
643
644         if (str == NULL || *str == '\0') {
645                 return false;
646         }
647
648         lval = strtoull(str, &end, 10 /* base */);
649         if (end == NULL || end == str) {
650                 return false;
651         }
652
653         if (*end) {
654                 if (strwicmp(end, "K") == 0) {
655                         lval *= 1024ULL;
656                 } else if (strwicmp(end, "M") == 0) {
657                         lval *= (1024ULL * 1024ULL);
658                 } else if (strwicmp(end, "G") == 0) {
659                         lval *= (1024ULL * 1024ULL * 1024ULL);
660                 } else if (strwicmp(end, "T") == 0) {
661                         lval *= (1024ULL * 1024ULL * 1024ULL * 1024ULL);
662                 } else if (strwicmp(end, "P") == 0) {
663                         lval *= (1024ULL * 1024ULL * 1024ULL * 1024ULL * 1024ULL);
664                 } else {
665                         return false;
666                 }
667         }
668
669         *val = (uint64_t)lval;
670         return true;
671 }
672
673 /**
674  * Parse a uint64_t value from a string
675  *
676  * val will be set to the value read.
677  *
678  * @retval true if parsing was successful, false otherwise
679  */
680 _PUBLIC_ bool conv_str_u64(const char * str, uint64_t * val)
681 {
682         char *              end = NULL;
683         unsigned long long  lval;
684
685         if (str == NULL || *str == '\0') {
686                 return false;
687         }
688
689         lval = strtoull(str, &end, 10 /* base */);
690         if (end == NULL || *end != '\0' || end == str) {
691                 return false;
692         }
693
694         *val = (uint64_t)lval;
695         return true;
696 }
697
698 /**
699 return the number of bytes occupied by a buffer in CH_UTF16 format
700 the result includes the null termination
701 **/
702 _PUBLIC_ size_t utf16_len(const void *buf)
703 {
704         size_t len;
705
706         for (len = 0; SVAL(buf,len); len += 2) ;
707
708         return len + 2;
709 }
710
711 /**
712 return the number of bytes occupied by a buffer in CH_UTF16 format
713 the result includes the null termination
714 limited by 'n' bytes
715 **/
716 _PUBLIC_ size_t utf16_len_n(const void *src, size_t n)
717 {
718         size_t len;
719
720         for (len = 0; (len+2 < n) && SVAL(src, len); len += 2) ;
721
722         if (len+2 <= n) {
723                 len += 2;
724         }
725
726         return len;
727 }
728
729 _PUBLIC_ size_t ucs2_align(const void *base_ptr, const void *p, int flags)
730 {
731         if (flags & (STR_NOALIGN|STR_ASCII))
732                 return 0;
733         return PTR_DIFF(p, base_ptr) & 1;
734 }
735
736 /**
737 Do a case-insensitive, whitespace-ignoring string compare.
738 **/
739 _PUBLIC_ int strwicmp(const char *psz1, const char *psz2)
740 {
741         /* if BOTH strings are NULL, return TRUE, if ONE is NULL return */
742         /* appropriate value. */
743         if (psz1 == psz2)
744                 return (0);
745         else if (psz1 == NULL)
746                 return (-1);
747         else if (psz2 == NULL)
748                 return (1);
749
750         /* sync the strings on first non-whitespace */
751         while (1) {
752                 while (isspace((int)*psz1))
753                         psz1++;
754                 while (isspace((int)*psz2))
755                         psz2++;
756                 if (toupper((unsigned char)*psz1) != toupper((unsigned char)*psz2) 
757                     || *psz1 == '\0'
758                     || *psz2 == '\0')
759                         break;
760                 psz1++;
761                 psz2++;
762         }
763         return (*psz1 - *psz2);
764 }
765
766 /**
767  String replace.
768 **/
769 _PUBLIC_ void string_replace(char *s, char oldc, char newc)
770 {
771         while (*s) {
772                 if (*s == oldc) *s = newc;
773                 s++;
774         }
775 }
776
777 /**
778  * Compare 2 strings.
779  *
780  * @note The comparison is case-insensitive.
781  **/
782 _PUBLIC_ bool strequal(const char *s1, const char *s2)
783 {
784         if (s1 == s2)
785                 return true;
786         if (!s1 || !s2)
787                 return false;
788   
789         return strcasecmp(s1,s2) == 0;
790 }