r11567: Ldb API change patch.
[abartlet/samba.git/.git] / source4 / lib / 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    
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 */
23
24 #include "includes.h"
25 #include "system/iconv.h"
26 #include "pstring.h"
27 #include "lib/ldb/include/ldb.h"
28
29 /**
30  * @file
31  * @brief String utilities.
32  **/
33
34 /**
35  * Get the next token from a string, return False if none found.
36  * Handles double-quotes.
37  * 
38  * Based on a routine by GJC@VILLAGE.COM. 
39  * Extensively modified by Andrew.Tridgell@anu.edu.au
40  **/
41 BOOL next_token(const char **ptr,char *buff, const char *sep, size_t bufsize)
42 {
43         const char *s;
44         BOOL quoted;
45         size_t len=1;
46
47         if (!ptr)
48                 return(False);
49
50         s = *ptr;
51
52         /* default to simple separators */
53         if (!sep)
54                 sep = " \t\n\r";
55
56         /* find the first non sep char */
57         while (*s && strchr_m(sep,*s))
58                 s++;
59         
60         /* nothing left? */
61         if (! *s)
62                 return(False);
63         
64         /* copy over the token */
65         for (quoted = False; len < bufsize && *s && (quoted || !strchr_m(sep,*s)); s++) {
66                 if (*s == '\"') {
67                         quoted = !quoted;
68                 } else {
69                         len++;
70                         *buff++ = *s;
71                 }
72         }
73         
74         *ptr = (*s) ? s+1 : s;  
75         *buff = 0;
76         
77         return(True);
78 }
79
80 /**
81  Case insensitive string compararison
82 **/
83 int strcasecmp_m(const char *s1, const char *s2)
84 {
85         codepoint_t c1=0, c2=0;
86         size_t size1, size2;
87
88         while (*s1 && *s2) {
89                 c1 = next_codepoint(s1, &size1);
90                 c2 = next_codepoint(s2, &size2);
91
92                 s1 += size1;
93                 s2 += size2;
94
95                 if (c1 == c2) {
96                         continue;
97                 }
98
99                 if (c1 == INVALID_CODEPOINT ||
100                     c2 == INVALID_CODEPOINT) {
101                         /* what else can we do?? */
102                         return c1 - c2;
103                 }
104
105                 if (toupper_w(c1) != toupper_w(c2)) {
106                         return c1 - c2;
107                 }
108         }
109
110         return *s1 - *s2;
111 }
112
113 /**
114  * Compare 2 strings.
115  *
116  * @note The comparison is case-insensitive.
117  **/
118 BOOL strequal(const char *s1, const char *s2)
119 {
120         if (s1 == s2)
121                 return(True);
122         if (!s1 || !s2)
123                 return(False);
124   
125         return strcasecmp_m(s1,s2) == 0;
126 }
127
128 /**
129  Compare 2 strings (case sensitive).
130 **/
131 BOOL strcsequal(const char *s1,const char *s2)
132 {
133         if (s1 == s2)
134                 return(True);
135         if (!s1 || !s2)
136                 return(False);
137         
138         return strcmp(s1,s2) == 0;
139 }
140
141
142 /**
143 Do a case-insensitive, whitespace-ignoring string compare.
144 **/
145 int strwicmp(const char *psz1, const char *psz2)
146 {
147         /* if BOTH strings are NULL, return TRUE, if ONE is NULL return */
148         /* appropriate value. */
149         if (psz1 == psz2)
150                 return (0);
151         else if (psz1 == NULL)
152                 return (-1);
153         else if (psz2 == NULL)
154                 return (1);
155
156         /* sync the strings on first non-whitespace */
157         while (1) {
158                 while (isspace((int)*psz1))
159                         psz1++;
160                 while (isspace((int)*psz2))
161                         psz2++;
162                 if (toupper((unsigned char)*psz1) != toupper((unsigned char)*psz2) 
163                     || *psz1 == '\0'
164                     || *psz2 == '\0')
165                         break;
166                 psz1++;
167                 psz2++;
168         }
169         return (*psz1 - *psz2);
170 }
171
172 /**
173  String replace.
174  NOTE: oldc and newc must be 7 bit characters
175 **/
176 void string_replace(char *s, char oldc, char newc)
177 {
178         while (*s) {
179                 size_t size;
180                 codepoint_t c = next_codepoint(s, &size);
181                 if (c == oldc) {
182                         *s = newc;
183                 }
184                 s += size;
185         }
186 }
187
188 /**
189  Trim the specified elements off the front and back of a string.
190 **/
191 BOOL trim_string(char *s,const char *front,const char *back)
192 {
193         BOOL ret = False;
194         size_t front_len;
195         size_t back_len;
196         size_t len;
197
198         /* Ignore null or empty strings. */
199         if (!s || (s[0] == '\0'))
200                 return False;
201
202         front_len       = front? strlen(front) : 0;
203         back_len        = back? strlen(back) : 0;
204
205         len = strlen(s);
206
207         if (front_len) {
208                 while (len && strncmp(s, front, front_len)==0) {
209                         /* Must use memmove here as src & dest can
210                          * easily overlap. Found by valgrind. JRA. */
211                         memmove(s, s+front_len, (len-front_len)+1);
212                         len -= front_len;
213                         ret=True;
214                 }
215         }
216         
217         if (back_len) {
218                 while ((len >= back_len) && strncmp(s+len-back_len,back,back_len)==0) {
219                         s[len-back_len]='\0';
220                         len -= back_len;
221                         ret=True;
222                 }
223         }
224         return ret;
225 }
226
227 /**
228  Find the number of 'c' chars in a string
229 **/
230 size_t count_chars(const char *s, char c)
231 {
232         size_t count = 0;
233
234         while (*s) {
235                 size_t size;
236                 codepoint_t c2 = next_codepoint(s, &size);
237                 if (c2 == c) count++;
238                 s += size;
239         }
240
241         return count;
242 }
243
244 /**
245  Safe string copy into a known length string. maxlength does not
246  include the terminating zero.
247 **/
248 char *safe_strcpy(char *dest,const char *src, size_t maxlength)
249 {
250         size_t len;
251
252         if (!dest) {
253                 DEBUG(0,("ERROR: NULL dest in safe_strcpy\n"));
254                 return NULL;
255         }
256
257 #ifdef DEVELOPER
258         /* We intentionally write out at the extremity of the destination
259          * string.  If the destination is too short (e.g. pstrcpy into mallocd
260          * or fstring) then this should cause an error under a memory
261          * checker. */
262         dest[maxlength] = '\0';
263         if (PTR_DIFF(&len, dest) > 0) {  /* check if destination is on the stack, ok if so */
264                 log_suspicious_usage("safe_strcpy", src);
265         }
266 #endif
267
268         if (!src) {
269                 *dest = 0;
270                 return dest;
271         }  
272
273         len = strlen(src);
274
275         if (len > maxlength) {
276                 DEBUG(0,("ERROR: string overflow by %u (%u - %u) in safe_strcpy [%.50s]\n",
277                          (uint_t)(len-maxlength), (unsigned)len, (unsigned)maxlength, src));
278                 len = maxlength;
279         }
280       
281         memmove(dest, src, len);
282         dest[len] = 0;
283         return dest;
284 }  
285
286 /**
287  Safe string cat into a string. maxlength does not
288  include the terminating zero.
289 **/
290 char *safe_strcat(char *dest, const char *src, size_t maxlength)
291 {
292         size_t src_len, dest_len;
293
294         if (!dest) {
295                 DEBUG(0,("ERROR: NULL dest in safe_strcat\n"));
296                 return NULL;
297         }
298
299         if (!src)
300                 return dest;
301         
302 #ifdef DEVELOPER
303         if (PTR_DIFF(&src_len, dest) > 0) {  /* check if destination is on the stack, ok if so */
304                 log_suspicious_usage("safe_strcat", src);
305         }
306 #endif
307         src_len = strlen(src);
308         dest_len = strlen(dest);
309
310         if (src_len + dest_len > maxlength) {
311                 DEBUG(0,("ERROR: string overflow by %d in safe_strcat [%.50s]\n",
312                          (int)(src_len + dest_len - maxlength), src));
313                 if (maxlength > dest_len) {
314                         memcpy(&dest[dest_len], src, maxlength - dest_len);
315                 }
316                 dest[maxlength] = 0;
317                 return NULL;
318         }
319         
320         memcpy(&dest[dest_len], src, src_len);
321         dest[dest_len + src_len] = 0;
322         return dest;
323 }
324
325 /**
326  Paranoid strcpy into a buffer of given length (includes terminating
327  zero. Strips out all but 'a-Z0-9' and the character in other_safe_chars
328  and replaces with '_'. Deliberately does *NOT* check for multibyte
329  characters. Don't change it !
330 **/
331
332 char *alpha_strcpy(char *dest, const char *src, const char *other_safe_chars, size_t maxlength)
333 {
334         size_t len, i;
335
336         if (maxlength == 0) {
337                 /* can't fit any bytes at all! */
338                 return NULL;
339         }
340
341         if (!dest) {
342                 DEBUG(0,("ERROR: NULL dest in alpha_strcpy\n"));
343                 return NULL;
344         }
345
346         if (!src) {
347                 *dest = 0;
348                 return dest;
349         }  
350
351         len = strlen(src);
352         if (len >= maxlength)
353                 len = maxlength - 1;
354
355         if (!other_safe_chars)
356                 other_safe_chars = "";
357
358         for(i = 0; i < len; i++) {
359                 int val = (src[i] & 0xff);
360                 if (isupper(val) || islower(val) || isdigit(val) || strchr_m(other_safe_chars, val))
361                         dest[i] = src[i];
362                 else
363                         dest[i] = '_';
364         }
365
366         dest[i] = '\0';
367
368         return dest;
369 }
370
371 /**
372  Like strncpy but always null terminates. Make sure there is room!
373  The variable n should always be one less than the available size.
374 **/
375
376 char *StrnCpy(char *dest,const char *src,size_t n)
377 {
378         char *d = dest;
379         if (!dest)
380                 return(NULL);
381         if (!src) {
382                 *dest = 0;
383                 return(dest);
384         }
385         while (n-- && (*d++ = *src++))
386                 ;
387         *d = 0;
388         return(dest);
389 }
390
391
392 /**
393  Routine to get hex characters and turn them into a 16 byte array.
394  the array can be variable length, and any non-hex-numeric
395  characters are skipped.  "0xnn" or "0Xnn" is specially catered
396  for.
397
398  valid examples: "0A5D15"; "0x15, 0x49, 0xa2"; "59\ta9\te3\n"
399
400
401 **/
402 size_t strhex_to_str(char *p, size_t len, const char *strhex)
403 {
404         size_t i;
405         size_t num_chars = 0;
406         uint8_t   lonybble, hinybble;
407         const char     *hexchars = "0123456789ABCDEF";
408         char           *p1 = NULL, *p2 = NULL;
409
410         for (i = 0; i < len && strhex[i] != 0; i++) {
411                 if (strncasecmp(hexchars, "0x", 2) == 0) {
412                         i++; /* skip two chars */
413                         continue;
414                 }
415
416                 if (!(p1 = strchr_m(hexchars, toupper((unsigned char)strhex[i]))))
417                         break;
418
419                 i++; /* next hex digit */
420
421                 if (!(p2 = strchr_m(hexchars, toupper((unsigned char)strhex[i]))))
422                         break;
423
424                 /* get the two nybbles */
425                 hinybble = PTR_DIFF(p1, hexchars);
426                 lonybble = PTR_DIFF(p2, hexchars);
427
428                 p[num_chars] = (hinybble << 4) | lonybble;
429                 num_chars++;
430
431                 p1 = NULL;
432                 p2 = NULL;
433         }
434         return num_chars;
435 }
436
437 DATA_BLOB strhex_to_data_blob(const char *strhex) 
438 {
439         DATA_BLOB ret_blob = data_blob(NULL, strlen(strhex)/2+1);
440
441         ret_blob.length = strhex_to_str(ret_blob.data,  
442                                         strlen(strhex), 
443                                         strhex);
444
445         return ret_blob;
446 }
447
448
449 /**
450  * Routine to print a buffer as HEX digits, into an allocated string.
451  */
452 void hex_encode(const unsigned char *buff_in, size_t len, char **out_hex_buffer)
453 {
454         int i;
455         char *hex_buffer;
456
457         *out_hex_buffer = smb_xmalloc((len*2)+1);
458         hex_buffer = *out_hex_buffer;
459
460         for (i = 0; i < len; i++)
461                 slprintf(&hex_buffer[i*2], 3, "%02X", buff_in[i]);
462 }
463
464 /**
465  Check if a string is part of a list.
466 **/
467 BOOL in_list(const char *s, const char *list, BOOL casesensitive)
468 {
469         pstring tok;
470         const char *p=list;
471
472         if (!list)
473                 return(False);
474
475         while (next_token(&p,tok,LIST_SEP,sizeof(tok))) {
476                 if (casesensitive) {
477                         if (strcmp(tok,s) == 0)
478                                 return(True);
479                 } else {
480                         if (strcasecmp_m(tok,s) == 0)
481                                 return(True);
482                 }
483         }
484         return(False);
485 }
486
487 /**
488  Set a string value, allocing the space for the string
489 **/
490 static BOOL string_init(char **dest,const char *src)
491 {
492         if (!src) src = "";
493
494         (*dest) = strdup(src);
495         if ((*dest) == NULL) {
496                 DEBUG(0,("Out of memory in string_init\n"));
497                 return False;
498         }
499         return True;
500 }
501
502 /**
503  Free a string value.
504 **/
505 void string_free(char **s)
506 {
507         if (s) SAFE_FREE(*s);
508 }
509
510 /**
511  Set a string value, deallocating any existing space, and allocing the space
512  for the string
513 **/
514 BOOL string_set(char **dest, const char *src)
515 {
516         string_free(dest);
517         return string_init(dest,src);
518 }
519
520 /**
521  Substitute a string for a pattern in another string. Make sure there is 
522  enough room!
523
524  This routine looks for pattern in s and replaces it with 
525  insert. It may do multiple replacements.
526
527  Any of " ; ' $ or ` in the insert string are replaced with _
528  if len==0 then the string cannot be extended. This is different from the old
529  use of len==0 which was for no length checks to be done.
530 **/
531
532 void string_sub(char *s,const char *pattern, const char *insert, size_t len)
533 {
534         char *p;
535         ssize_t ls,lp,li, i;
536
537         if (!insert || !pattern || !*pattern || !s)
538                 return;
539
540         ls = (ssize_t)strlen(s);
541         lp = (ssize_t)strlen(pattern);
542         li = (ssize_t)strlen(insert);
543
544         if (len == 0)
545                 len = ls + 1; /* len is number of *bytes* */
546
547         while (lp <= ls && (p = strstr(s,pattern))) {
548                 if (ls + (li-lp) >= len) {
549                         DEBUG(0,("ERROR: string overflow by %d in string_sub(%.50s, %d)\n", 
550                                  (int)(ls + (li-lp) - len),
551                                  pattern, (int)len));
552                         break;
553                 }
554                 if (li != lp) {
555                         memmove(p+li,p+lp,strlen(p+lp)+1);
556                 }
557                 for (i=0;i<li;i++) {
558                         switch (insert[i]) {
559                         case '`':
560                         case '"':
561                         case '\'':
562                         case ';':
563                         case '$':
564                         case '%':
565                         case '\r':
566                         case '\n':
567                                 p[i] = '_';
568                                 break;
569                         default:
570                                 p[i] = insert[i];
571                         }
572                 }
573                 s = p + li;
574                 ls += (li-lp);
575         }
576 }
577
578
579 /**
580  Similar to string_sub() but allows for any character to be substituted. 
581  Use with caution!
582  if len==0 then the string cannot be extended. This is different from the old
583  use of len==0 which was for no length checks to be done.
584 **/
585
586 void all_string_sub(char *s,const char *pattern,const char *insert, size_t len)
587 {
588         char *p;
589         ssize_t ls,lp,li;
590
591         if (!insert || !pattern || !s)
592                 return;
593
594         ls = (ssize_t)strlen(s);
595         lp = (ssize_t)strlen(pattern);
596         li = (ssize_t)strlen(insert);
597
598         if (!*pattern)
599                 return;
600         
601         if (len == 0)
602                 len = ls + 1; /* len is number of *bytes* */
603         
604         while (lp <= ls && (p = strstr(s,pattern))) {
605                 if (ls + (li-lp) >= len) {
606                         DEBUG(0,("ERROR: string overflow by %d in all_string_sub(%.50s, %d)\n", 
607                                  (int)(ls + (li-lp) - len),
608                                  pattern, (int)len));
609                         break;
610                 }
611                 if (li != lp) {
612                         memmove(p+li,p+lp,strlen(p+lp)+1);
613                 }
614                 memcpy(p, insert, li);
615                 s = p + li;
616                 ls += (li-lp);
617         }
618 }
619
620
621 /**
622  Strchr and strrchr_m are a bit complex on general multi-byte strings. 
623 **/
624 char *strchr_m(const char *s, char c)
625 {
626         /* characters below 0x3F are guaranteed to not appear in
627            non-initial position in multi-byte charsets */
628         if ((c & 0xC0) == 0) {
629                 return strchr(s, c);
630         }
631
632         while (*s) {
633                 size_t size;
634                 codepoint_t c2 = next_codepoint(s, &size);
635                 if (c2 == c) {
636                         return discard_const(s);
637                 }
638                 s += size;
639         }
640
641         return NULL;
642 }
643
644 char *strrchr_m(const char *s, char c)
645 {
646         char *ret = NULL;
647
648         /* characters below 0x3F are guaranteed to not appear in
649            non-initial position in multi-byte charsets */
650         if ((c & 0xC0) == 0) {
651                 return strrchr(s, c);
652         }
653
654         while (*s) {
655                 size_t size;
656                 codepoint_t c2 = next_codepoint(s, &size);
657                 if (c2 == c) {
658                         ret = discard_const(s);
659                 }
660                 s += size;
661         }
662
663         return ret;
664 }
665
666 BOOL strhaslower(const char *string)
667 {
668         while (*string) {
669                 size_t c_size;
670                 codepoint_t s;
671                 codepoint_t t;
672
673                 s = next_codepoint(string, &c_size);
674                 string += c_size;
675
676                 t = tolower_w(s);
677
678                 if (s == t) { /* the source was alreay lower case */
679                         return True; /* that means it has lower case chars */
680                 }
681         }
682
683         return False;
684
685
686 BOOL strhasupper(const char *string)
687 {
688         while (*string) {
689                 size_t c_size;
690                 codepoint_t s;
691                 codepoint_t t;
692
693                 s = next_codepoint(string, &c_size);
694                 string += c_size;
695
696                 t = toupper_w(s);
697
698                 if (s == t) { /* the source was alreay upper case */
699                         return True; /* that means it has upper case chars */
700                 }
701         }
702
703         return False;
704
705
706 /**
707  Convert a string to lower case, allocated with talloc
708 **/
709 char *strlower_talloc(TALLOC_CTX *ctx, const char *src)
710 {
711         size_t size=0;
712         char *dest;
713
714         /* this takes advantage of the fact that upper/lower can't
715            change the length of a character by more than 1 byte */
716         dest = talloc_size(ctx, 2*(strlen(src))+1);
717         if (dest == NULL) {
718                 return NULL;
719         }
720
721         while (*src) {
722                 size_t c_size;
723                 codepoint_t c = next_codepoint(src, &c_size);
724                 src += c_size;
725
726                 c = tolower_w(c);
727
728                 c_size = push_codepoint(dest+size, c);
729                 if (c_size == -1) {
730                         talloc_free(dest);
731                         return NULL;
732                 }
733                 size += c_size;
734         }
735
736         dest[size] = 0;
737
738         return dest;
739 }
740
741 /**
742  Convert a string to UPPER case, allocated with talloc
743 **/
744 char *strupper_talloc(TALLOC_CTX *ctx, const char *src)
745 {
746         size_t size=0;
747         char *dest;
748         
749         if (!src) {
750                 return NULL;
751         }
752
753         /* this takes advantage of the fact that upper/lower can't
754            change the length of a character by more than 1 byte */
755         dest = talloc_size(ctx, 2*(strlen(src))+1);
756         if (dest == NULL) {
757                 return NULL;
758         }
759
760         while (*src) {
761                 size_t c_size;
762                 codepoint_t c = next_codepoint(src, &c_size);
763                 src += c_size;
764
765                 c = toupper_w(c);
766
767                 c_size = push_codepoint(dest+size, c);
768                 if (c_size == -1) {
769                         talloc_free(dest);
770                         return NULL;
771                 }
772                 size += c_size;
773         }
774
775         dest[size] = 0;
776
777         return dest;
778 }
779
780 /**
781  Convert a string to lower case.
782 **/
783 void strlower_m(char *s)
784 {
785         char *d;
786
787         /* this is quite a common operation, so we want it to be
788            fast. We optimise for the ascii case, knowing that all our
789            supported multi-byte character sets are ascii-compatible
790            (ie. they match for the first 128 chars) */
791         while (*s && !(((uint8_t)s[0]) & 0x7F)) {
792                 *s = tolower((uint8_t)*s);
793                 s++;
794         }
795
796         if (!*s)
797                 return;
798
799         d = s;
800
801         while (*s) {
802                 size_t c_size, c_size2;
803                 codepoint_t c = next_codepoint(s, &c_size);
804                 c_size2 = push_codepoint(d, tolower_w(c));
805                 if (c_size2 > c_size) {
806                         DEBUG(0,("FATAL: codepoint 0x%x (0x%x) expanded from %d to %d bytes in strlower_m\n",
807                                  c, tolower_w(c), (int)c_size, (int)c_size2));
808                         smb_panic("codepoint expansion in strlower_m\n");
809                 }
810                 s += c_size;
811                 d += c_size2;
812         }
813         *d = 0;
814 }
815
816 /**
817  Convert a string to UPPER case.
818 **/
819 void strupper_m(char *s)
820 {
821         char *d;
822
823         /* this is quite a common operation, so we want it to be
824            fast. We optimise for the ascii case, knowing that all our
825            supported multi-byte character sets are ascii-compatible
826            (ie. they match for the first 128 chars) */
827         while (*s && !(((uint8_t)s[0]) & 0x7F)) {
828                 *s = toupper((uint8_t)*s);
829                 s++;
830         }
831
832         if (!*s)
833                 return;
834
835         d = s;
836
837         while (*s) {
838                 size_t c_size, c_size2;
839                 codepoint_t c = next_codepoint(s, &c_size);
840                 c_size2 = push_codepoint(d, toupper_w(c));
841                 if (c_size2 > c_size) {
842                         DEBUG(0,("FATAL: codepoint 0x%x (0x%x) expanded from %d to %d bytes in strupper_m\n",
843                                  c, toupper_w(c), (int)c_size, (int)c_size2));
844                         smb_panic("codepoint expansion in strupper_m\n");
845                 }
846                 s += c_size;
847                 d += c_size2;
848         }
849         *d = 0;
850 }
851
852 /**
853  Count the number of UCS2 characters in a string. Normally this will
854  be the same as the number of bytes in a string for single byte strings,
855  but will be different for multibyte.
856 **/
857 size_t strlen_m(const char *s)
858 {
859         size_t count = 0;
860
861         if (!s) {
862                 return 0;
863         }
864
865         while (*s && !(((uint8_t)s[0]) & 0x7F)) {
866                 s++;
867                 count++;
868         }
869
870         if (!*s) {
871                 return count;
872         }
873
874         while (*s) {
875                 size_t c_size;
876                 codepoint_t c = next_codepoint(s, &c_size);
877                 if (c < 0x10000) {
878                         count += 1;
879                 } else {
880                         count += 2;
881                 }
882                 s += c_size;
883         }
884
885         return count;
886 }
887
888 /**
889    Work out the number of multibyte chars in a string, including the NULL
890    terminator.
891 **/
892 size_t strlen_m_term(const char *s)
893 {
894         if (!s) {
895                 return 0;
896         }
897
898         return strlen_m(s) + 1;
899 }
900
901 /**
902  Unescape a URL encoded string, in place.
903 **/
904
905 void rfc1738_unescape(char *buf)
906 {
907         char *p=buf;
908
909         while ((p=strchr_m(p,'+')))
910                 *p = ' ';
911
912         p = buf;
913
914         while (p && *p && (p=strchr_m(p,'%'))) {
915                 int c1 = p[1];
916                 int c2 = p[2];
917
918                 if (c1 >= '0' && c1 <= '9')
919                         c1 = c1 - '0';
920                 else if (c1 >= 'A' && c1 <= 'F')
921                         c1 = 10 + c1 - 'A';
922                 else if (c1 >= 'a' && c1 <= 'f')
923                         c1 = 10 + c1 - 'a';
924                 else {p++; continue;}
925
926                 if (c2 >= '0' && c2 <= '9')
927                         c2 = c2 - '0';
928                 else if (c2 >= 'A' && c2 <= 'F')
929                         c2 = 10 + c2 - 'A';
930                 else if (c2 >= 'a' && c2 <= 'f')
931                         c2 = 10 + c2 - 'a';
932                 else {p++; continue;}
933                         
934                 *p = (c1<<4) | c2;
935
936                 memmove(p+1, p+3, strlen(p+3)+1);
937                 p++;
938         }
939 }
940
941 /**
942  * Decode a base64 string into a DATA_BLOB - simple and slow algorithm
943  **/
944 DATA_BLOB base64_decode_data_blob(TALLOC_CTX *mem_ctx, const char *s)
945 {
946         DATA_BLOB ret = data_blob_talloc(mem_ctx, s, strlen(s)+1);
947         ret.length = ldb_base64_decode(ret.data);
948         return ret;
949 }
950
951 /**
952  * Decode a base64 string in-place - wrapper for the above
953  **/
954 void base64_decode_inplace(char *s)
955 {
956         ldb_base64_decode(s);
957 }
958
959 /**
960  * Encode a base64 string into a talloc()ed string caller to free.
961  **/
962 char *base64_encode_data_blob(TALLOC_CTX *mem_ctx, DATA_BLOB data)
963 {
964         return ldb_base64_encode(mem_ctx, data.data, data.length);
965 }
966
967 #ifdef VALGRIND
968 size_t valgrind_strlen(const char *s)
969 {
970         size_t count;
971         for(count = 0; *s++; count++)
972                 ;
973         return count;
974 }
975 #endif
976
977
978 /*
979   format a string into length-prefixed dotted domain format, as used in NBT
980   and in some ADS structures
981 */
982 const char *str_format_nbt_domain(TALLOC_CTX *mem_ctx, const char *s)
983 {
984         char *ret;
985         int i;
986         if (!s || !*s) {
987                 return talloc_strdup(mem_ctx, "");
988         }
989         ret = talloc_size(mem_ctx, strlen(s)+2);
990         if (!ret) {
991                 return ret;
992         }
993         
994         memcpy(ret+1, s, strlen(s)+1);
995         ret[0] = '.';
996
997         for (i=0;ret[i];i++) {
998                 if (ret[i] == '.') {
999                         char *p = strchr(ret+i+1, '.');
1000                         if (p) {
1001                                 ret[i] = p-(ret+i+1);
1002                         } else {
1003                                 ret[i] = strlen(ret+i+1);
1004                         }
1005                 }
1006         }
1007
1008         return ret;
1009 }
1010
1011 BOOL add_string_to_array(TALLOC_CTX *mem_ctx,
1012                          const char *str, const char ***strings, int *num)
1013 {
1014         char *dup_str = talloc_strdup(mem_ctx, str);
1015
1016         *strings = talloc_realloc(mem_ctx,
1017                                     *strings,
1018                                     const char *, ((*num)+1));
1019
1020         if ((*strings == NULL) || (dup_str == NULL))
1021                 return False;
1022
1023         (*strings)[*num] = dup_str;
1024         *num += 1;
1025
1026         return True;
1027 }
1028
1029
1030
1031 /*
1032   varient of strcmp() that handles NULL ptrs
1033 */
1034 int strcmp_safe(const char *s1, const char *s2)
1035 {
1036         if (s1 == s2) {
1037                 return 0;
1038         }
1039         if (s1 == NULL || s2 == NULL) {
1040                 return s1?-1:1;
1041         }
1042         return strcmp(s1, s2);
1043 }
1044
1045
1046 /*******************************************************************
1047 return the number of bytes occupied by a buffer in ASCII format
1048 the result includes the null termination
1049 limited by 'n' bytes
1050 ********************************************************************/
1051 size_t ascii_len_n(const char *src, size_t n)
1052 {
1053         size_t len;
1054
1055         len = strnlen(src, n);
1056         if (len+1 <= n) {
1057                 len += 1;
1058         }
1059
1060         return len;
1061 }
1062
1063
1064 /*******************************************************************
1065  Return a string representing a CIFS attribute for a file.
1066 ********************************************************************/
1067 char *attrib_string(TALLOC_CTX *mem_ctx, uint32_t attrib)
1068 {
1069         int i, len;
1070         const struct {
1071                 char c;
1072                 uint16_t attr;
1073         } attr_strs[] = {
1074                 {'V', FILE_ATTRIBUTE_VOLUME},
1075                 {'D', FILE_ATTRIBUTE_DIRECTORY},
1076                 {'A', FILE_ATTRIBUTE_ARCHIVE},
1077                 {'H', FILE_ATTRIBUTE_HIDDEN},
1078                 {'S', FILE_ATTRIBUTE_SYSTEM},
1079                 {'N', FILE_ATTRIBUTE_NORMAL},
1080                 {'R', FILE_ATTRIBUTE_READONLY},
1081                 {'d', FILE_ATTRIBUTE_DEVICE},
1082                 {'t', FILE_ATTRIBUTE_TEMPORARY},
1083                 {'s', FILE_ATTRIBUTE_SPARSE},
1084                 {'r', FILE_ATTRIBUTE_REPARSE_POINT},
1085                 {'c', FILE_ATTRIBUTE_COMPRESSED},
1086                 {'o', FILE_ATTRIBUTE_OFFLINE},
1087                 {'n', FILE_ATTRIBUTE_NONINDEXED},
1088                 {'e', FILE_ATTRIBUTE_ENCRYPTED}
1089         };
1090         char *ret;
1091
1092         ret = talloc_size(mem_ctx, ARRAY_SIZE(attr_strs)+1);
1093         if (!ret) {
1094                 return NULL;
1095         }
1096
1097         for (len=i=0; i<ARRAY_SIZE(attr_strs); i++) {
1098                 if (attrib & attr_strs[i].attr) {
1099                         ret[len++] = attr_strs[i].c;
1100                 }
1101         }
1102
1103         ret[len] = 0;
1104
1105         return ret;
1106 }
1107