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