r1983: a completely new implementation of talloc
[bbaumbach/samba-autobuild/.git] / source4 / lib / util_str.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Samba utility functions
4    Copyright (C) Andrew Tridgell 1992-2001
5    Copyright (C) Simo Sorce      2001-2002
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 #include "includes.h"
23
24 /**
25  * Get the next token from a string, return False if none found.
26  * Handles double-quotes.
27  * 
28  * Based on a routine by GJC@VILLAGE.COM. 
29  * Extensively modified by Andrew.Tridgell@anu.edu.au
30  **/
31 BOOL next_token(const char **ptr,char *buff, const char *sep, size_t bufsize)
32 {
33         const char *s;
34         BOOL quoted;
35         size_t len=1;
36
37         if (!ptr)
38                 return(False);
39
40         s = *ptr;
41
42         /* default to simple separators */
43         if (!sep)
44                 sep = " \t\n\r";
45
46         /* find the first non sep char */
47         while (*s && strchr_m(sep,*s))
48                 s++;
49         
50         /* nothing left? */
51         if (! *s)
52                 return(False);
53         
54         /* copy over the token */
55         for (quoted = False; len < bufsize && *s && (quoted || !strchr_m(sep,*s)); s++) {
56                 if (*s == '\"') {
57                         quoted = !quoted;
58                 } else {
59                         len++;
60                         *buff++ = *s;
61                 }
62         }
63         
64         *ptr = (*s) ? s+1 : s;  
65         *buff = 0;
66         
67         return(True);
68 }
69
70 /**
71 This is like next_token but is not re-entrant and "remembers" the first 
72 parameter so you can pass NULL. This is useful for user interface code
73 but beware the fact that it is not re-entrant!
74 **/
75
76 static char *last_ptr=NULL;
77
78 BOOL next_token_nr(const char **ptr, char *buff, const char *sep, size_t bufsize)
79 {
80         BOOL ret;
81         if (!ptr)
82                 ptr = (const char **)&last_ptr;
83
84         ret = next_token(ptr, buff, sep, bufsize);
85         last_ptr = *ptr;
86         return ret;     
87 }
88
89 static uint16_t tmpbuf[sizeof(pstring)];
90
91 /**
92  Convert list of tokens to array; dependent on above routine.
93  Uses last_ptr from above - bit of a hack.
94 **/
95
96 char **toktocliplist(int *ctok, const char *sep)
97 {
98         char *s=last_ptr;
99         int ictok=0;
100         char **ret, **iret;
101
102         if (!sep)
103                 sep = " \t\n\r";
104
105         while(*s && strchr_m(sep,*s))
106                 s++;
107
108         /* nothing left? */
109         if (!*s)
110                 return(NULL);
111
112         do {
113                 ictok++;
114                 while(*s && (!strchr_m(sep,*s)))
115                         s++;
116                 while(*s && strchr_m(sep,*s))
117                         *s++=0;
118         } while(*s);
119         
120         *ctok=ictok;
121         s=last_ptr;
122         
123         if (!(ret=iret=malloc(ictok*sizeof(char *))))
124                 return NULL;
125         
126         while(ictok--) {    
127                 *iret++=s;
128                 while(*s++)
129                         ;
130                 while(!*s)
131                         s++;
132         }
133
134         return ret;
135 }
136
137 /**
138  Case insensitive string compararison.
139 **/
140
141 int StrCaseCmp(const char *s, const char *t)
142 {
143         pstring buf1, buf2;
144         unix_strupper(s, strlen(s)+1, buf1, sizeof(buf1));
145         unix_strupper(t, strlen(t)+1, buf2, sizeof(buf2));
146         return strcmp(buf1,buf2);
147 }
148
149 /**
150  Case insensitive string compararison, length limited.
151 **/
152
153 int StrnCaseCmp(const char *s, const char *t, size_t n)
154 {
155         pstring buf1, buf2;
156         unix_strupper(s, strlen(s)+1, buf1, sizeof(buf1));
157         unix_strupper(t, strlen(t)+1, buf2, sizeof(buf2));
158         return strncmp(buf1,buf2,n);
159 }
160
161 /**
162  * Compare 2 strings.
163  *
164  * @note The comparison is case-insensitive.
165  **/
166 BOOL strequal(const char *s1, const char *s2)
167 {
168         if (s1 == s2)
169                 return(True);
170         if (!s1 || !s2)
171                 return(False);
172   
173         return(StrCaseCmp(s1,s2)==0);
174 }
175
176 /**
177  * Compare 2 strings up to and including the nth char.
178  *
179  * @note The comparison is case-insensitive.
180  **/
181 BOOL strnequal(const char *s1,const char *s2,size_t n)
182 {
183   if (s1 == s2)
184           return(True);
185   if (!s1 || !s2 || !n)
186           return(False);
187   
188   return(StrnCaseCmp(s1,s2,n)==0);
189 }
190
191 /**
192  Compare 2 strings (case sensitive).
193 **/
194
195 BOOL strcsequal(const char *s1,const char *s2)
196 {
197   if (s1 == s2)
198           return(True);
199   if (!s1 || !s2)
200           return(False);
201   
202   return(strcmp(s1,s2)==0);
203 }
204
205 /**
206 Do a case-insensitive, whitespace-ignoring string compare.
207 **/
208
209 int strwicmp(const char *psz1, const char *psz2)
210 {
211         /* if BOTH strings are NULL, return TRUE, if ONE is NULL return */
212         /* appropriate value. */
213         if (psz1 == psz2)
214                 return (0);
215         else if (psz1 == NULL)
216                 return (-1);
217         else if (psz2 == NULL)
218                 return (1);
219
220         /* sync the strings on first non-whitespace */
221         while (1) {
222                 while (isspace((int)*psz1))
223                         psz1++;
224                 while (isspace((int)*psz2))
225                         psz2++;
226                 if (toupper(*psz1) != toupper(*psz2) || *psz1 == '\0'
227                     || *psz2 == '\0')
228                         break;
229                 psz1++;
230                 psz2++;
231         }
232         return (*psz1 - *psz2);
233 }
234
235 /**
236  Convert a string to upper case, but don't modify it.
237 **/
238
239 char *strupper_talloc(TALLOC_CTX *mem_ctx, const char *s)
240 {
241         char *str;
242
243         str = talloc_strdup(mem_ctx, s);
244         strupper(str);
245
246         return str;
247 }
248
249
250 /**
251  String replace.
252  NOTE: oldc and newc must be 7 bit characters
253 **/
254
255 void string_replace(char *s,char oldc,char newc)
256 {
257         if (strchr(s, oldc)) {
258                 push_ucs2(NULL, tmpbuf,s, sizeof(tmpbuf), STR_TERMINATE);
259                 string_replace_w(tmpbuf, UCS2_CHAR(oldc), UCS2_CHAR(newc));
260                 pull_ucs2(NULL, s, tmpbuf, strlen(s)+1, sizeof(tmpbuf), STR_TERMINATE);
261         }
262 }
263
264 /**
265  Count the number of characters in a string. Normally this will
266  be the same as the number of bytes in a string for single byte strings,
267  but will be different for multibyte.
268 **/
269
270 size_t str_charnum(const char *s)
271 {
272         uint16_t tmpbuf2[sizeof(pstring)];
273         push_ucs2(NULL, tmpbuf2,s, sizeof(tmpbuf2), STR_TERMINATE);
274         return strlen_w(tmpbuf2);
275 }
276
277 /**
278  Count the number of characters in a string. Normally this will
279  be the same as the number of bytes in a string for single byte strings,
280  but will be different for multibyte.
281 **/
282
283 size_t str_ascii_charnum(const char *s)
284 {
285         pstring tmpbuf2;
286         push_ascii(tmpbuf2, s, sizeof(tmpbuf2), STR_TERMINATE);
287         return strlen(tmpbuf2);
288 }
289
290 /**
291  Trim the specified elements off the front and back of a string.
292 **/
293
294 BOOL trim_string(char *s,const char *front,const char *back)
295 {
296         BOOL ret = False;
297         size_t front_len;
298         size_t back_len;
299         size_t len;
300
301         /* Ignore null or empty strings. */
302         if (!s || (s[0] == '\0'))
303                 return False;
304
305         front_len       = front? strlen(front) : 0;
306         back_len        = back? strlen(back) : 0;
307
308         len = strlen(s);
309
310         if (front_len) {
311                 while (len && strncmp(s, front, front_len)==0) {
312                         memcpy(s, s+front_len, (len-front_len)+1);
313                         len -= front_len;
314                         ret=True;
315                 }
316         }
317         
318         if (back_len) {
319                 while ((len >= back_len) && strncmp(s+len-back_len,back,back_len)==0) {
320                         s[len-back_len]='\0';
321                         len -= back_len;
322                         ret=True;
323                 }
324         }
325         return ret;
326 }
327
328 /**
329  Does a string have any uppercase chars in it?
330 **/
331
332 BOOL strhasupper(const char *s)
333 {
334         smb_ucs2_t *ptr;
335         push_ucs2(NULL, tmpbuf,s, sizeof(tmpbuf), STR_TERMINATE);
336         for(ptr=tmpbuf;*ptr;ptr++)
337                 if(isupper_w(*ptr))
338                         return True;
339         return(False);
340 }
341
342 /**
343  Does a string have any lowercase chars in it?
344 **/
345
346 BOOL strhaslower(const char *s)
347 {
348         smb_ucs2_t *ptr;
349         push_ucs2(NULL, tmpbuf,s, sizeof(tmpbuf), STR_TERMINATE);
350         for(ptr=tmpbuf;*ptr;ptr++)
351                 if(islower_w(*ptr))
352                         return True;
353         return(False);
354 }
355
356 /**
357  Find the number of 'c' chars in a string
358 **/
359
360 size_t count_chars(const char *s,char c)
361 {
362         smb_ucs2_t *ptr;
363         int count;
364         push_ucs2(NULL, tmpbuf,s, sizeof(tmpbuf), STR_TERMINATE);
365         for(count=0,ptr=tmpbuf;*ptr;ptr++)
366                 if(*ptr==UCS2_CHAR(c))
367                         count++;
368         return(count);
369 }
370
371 /**
372  Safe string copy into a known length string. maxlength does not
373  include the terminating zero.
374 **/
375
376 char *safe_strcpy(char *dest,const char *src, size_t maxlength)
377 {
378         size_t len;
379
380         if (!dest) {
381                 DEBUG(0,("ERROR: NULL dest in safe_strcpy\n"));
382                 return NULL;
383         }
384
385 #ifdef DEVELOPER
386         /* We intentionally write out at the extremity of the destination
387          * string.  If the destination is too short (e.g. pstrcpy into mallocd
388          * or fstring) then this should cause an error under a memory
389          * checker. */
390         dest[maxlength] = '\0';
391         if (PTR_DIFF(&len, dest) > 0) {  /* check if destination is on the stack, ok if so */
392                 log_suspicious_usage("safe_strcpy", src);
393         }
394 #endif
395
396         if (!src) {
397                 *dest = 0;
398                 return dest;
399         }  
400
401         len = strlen(src);
402
403         if (len > maxlength) {
404                 DEBUG(0,("ERROR: string overflow by %u (%u - %u) in safe_strcpy [%.50s]\n",
405                          (uint_t)(len-maxlength), len, maxlength, src));
406                 len = maxlength;
407         }
408       
409         memmove(dest, src, len);
410         dest[len] = 0;
411         return dest;
412 }  
413
414 /**
415  Safe string cat into a string. maxlength does not
416  include the terminating zero.
417 **/
418
419 char *safe_strcat(char *dest, const char *src, size_t maxlength)
420 {
421         size_t src_len, dest_len;
422
423         if (!dest) {
424                 DEBUG(0,("ERROR: NULL dest in safe_strcat\n"));
425                 return NULL;
426         }
427
428         if (!src)
429                 return dest;
430         
431 #ifdef DEVELOPER
432         if (PTR_DIFF(&src_len, dest) > 0) {  /* check if destination is on the stack, ok if so */
433                 log_suspicious_usage("safe_strcat", src);
434         }
435 #endif
436         src_len = strlen(src);
437         dest_len = strlen(dest);
438
439         if (src_len + dest_len > maxlength) {
440                 DEBUG(0,("ERROR: string overflow by %d in safe_strcat [%.50s]\n",
441                          (int)(src_len + dest_len - maxlength), src));
442                 if (maxlength > dest_len) {
443                         memcpy(&dest[dest_len], src, maxlength - dest_len);
444                 }
445                 dest[maxlength] = 0;
446                 return NULL;
447         }
448         
449         memcpy(&dest[dest_len], src, src_len);
450         dest[dest_len + src_len] = 0;
451         return dest;
452 }
453
454 /**
455  Paranoid strcpy into a buffer of given length (includes terminating
456  zero. Strips out all but 'a-Z0-9' and the character in other_safe_chars
457  and replaces with '_'. Deliberately does *NOT* check for multibyte
458  characters. Don't change it !
459 **/
460
461 char *alpha_strcpy(char *dest, const char *src, const char *other_safe_chars, size_t maxlength)
462 {
463         size_t len, i;
464
465         if (maxlength == 0) {
466                 /* can't fit any bytes at all! */
467                 return NULL;
468         }
469
470         if (!dest) {
471                 DEBUG(0,("ERROR: NULL dest in alpha_strcpy\n"));
472                 return NULL;
473         }
474
475         if (!src) {
476                 *dest = 0;
477                 return dest;
478         }  
479
480         len = strlen(src);
481         if (len >= maxlength)
482                 len = maxlength - 1;
483
484         if (!other_safe_chars)
485                 other_safe_chars = "";
486
487         for(i = 0; i < len; i++) {
488                 int val = (src[i] & 0xff);
489                 if (isupper(val) || islower(val) || isdigit(val) || strchr_m(other_safe_chars, val))
490                         dest[i] = src[i];
491                 else
492                         dest[i] = '_';
493         }
494
495         dest[i] = '\0';
496
497         return dest;
498 }
499
500 /**
501  Like strncpy but always null terminates. Make sure there is room!
502  The variable n should always be one less than the available size.
503 **/
504
505 char *StrnCpy(char *dest,const char *src,size_t n)
506 {
507         char *d = dest;
508         if (!dest)
509                 return(NULL);
510         if (!src) {
511                 *dest = 0;
512                 return(dest);
513         }
514         while (n-- && (*d++ = *src++))
515                 ;
516         *d = 0;
517         return(dest);
518 }
519
520
521 /**
522  Check if a string is part of a list.
523 **/
524
525 BOOL in_list(const char *s, const char *list, BOOL casesensitive)
526 {
527         pstring tok;
528         const char *p=list;
529
530         if (!list)
531                 return(False);
532
533         while (next_token(&p,tok,LIST_SEP,sizeof(tok))) {
534                 if (casesensitive) {
535                         if (strcmp(tok,s) == 0)
536                                 return(True);
537                 } else {
538                         if (StrCaseCmp(tok,s) == 0)
539                                 return(True);
540                 }
541         }
542         return(False);
543 }
544
545 /**
546  Set a string value, allocing the space for the string
547 **/
548 static BOOL string_init(char **dest,const char *src)
549 {
550         if (!src) src = "";
551
552         (*dest) = strdup(src);
553         if ((*dest) == NULL) {
554                 DEBUG(0,("Out of memory in string_init\n"));
555                 return False;
556         }
557         return True;
558 }
559
560 /**
561  Free a string value.
562 **/
563 void string_free(char **s)
564 {
565         if (s) SAFE_FREE(*s);
566 }
567
568 /**
569  Set a string value, deallocating any existing space, and allocing the space
570  for the string
571 **/
572 BOOL string_set(char **dest, const char *src)
573 {
574         string_free(dest);
575         return string_init(dest,src);
576 }
577
578 /**
579  Substitute a string for a pattern in another string. Make sure there is 
580  enough room!
581
582  This routine looks for pattern in s and replaces it with 
583  insert. It may do multiple replacements.
584
585  Any of " ; ' $ or ` in the insert string are replaced with _
586  if len==0 then the string cannot be extended. This is different from the old
587  use of len==0 which was for no length checks to be done.
588 **/
589
590 void string_sub(char *s,const char *pattern, const char *insert, size_t len)
591 {
592         char *p;
593         ssize_t ls,lp,li, i;
594
595         if (!insert || !pattern || !*pattern || !s)
596                 return;
597
598         ls = (ssize_t)strlen(s);
599         lp = (ssize_t)strlen(pattern);
600         li = (ssize_t)strlen(insert);
601
602         if (len == 0)
603                 len = ls + 1; /* len is number of *bytes* */
604
605         while (lp <= ls && (p = strstr(s,pattern))) {
606                 if (ls + (li-lp) >= len) {
607                         DEBUG(0,("ERROR: string overflow by %d in string_sub(%.50s, %d)\n", 
608                                  (int)(ls + (li-lp) - len),
609                                  pattern, (int)len));
610                         break;
611                 }
612                 if (li != lp) {
613                         memmove(p+li,p+lp,strlen(p+lp)+1);
614                 }
615                 for (i=0;i<li;i++) {
616                         switch (insert[i]) {
617                         case '`':
618                         case '"':
619                         case '\'':
620                         case ';':
621                         case '$':
622                         case '%':
623                         case '\r':
624                         case '\n':
625                                 p[i] = '_';
626                                 break;
627                         default:
628                                 p[i] = insert[i];
629                         }
630                 }
631                 s = p + li;
632                 ls += (li-lp);
633         }
634 }
635
636
637 /**
638  Similar to string_sub() but allows for any character to be substituted. 
639  Use with caution!
640  if len==0 then the string cannot be extended. This is different from the old
641  use of len==0 which was for no length checks to be done.
642 **/
643
644 void all_string_sub(char *s,const char *pattern,const char *insert, size_t len)
645 {
646         char *p;
647         ssize_t ls,lp,li;
648
649         if (!insert || !pattern || !s)
650                 return;
651
652         ls = (ssize_t)strlen(s);
653         lp = (ssize_t)strlen(pattern);
654         li = (ssize_t)strlen(insert);
655
656         if (!*pattern)
657                 return;
658         
659         if (len == 0)
660                 len = ls + 1; /* len is number of *bytes* */
661         
662         while (lp <= ls && (p = strstr(s,pattern))) {
663                 if (ls + (li-lp) >= len) {
664                         DEBUG(0,("ERROR: string overflow by %d in all_string_sub(%.50s, %d)\n", 
665                                  (int)(ls + (li-lp) - len),
666                                  pattern, (int)len));
667                         break;
668                 }
669                 if (li != lp) {
670                         memmove(p+li,p+lp,strlen(p+lp)+1);
671                 }
672                 memcpy(p, insert, li);
673                 s = p + li;
674                 ls += (li-lp);
675         }
676 }
677
678 /**
679  Write an octal as a string.
680 **/
681
682 const char *octal_string(int i)
683 {
684         static char ret[64];
685         if (i == -1)
686                 return "-1";
687         slprintf(ret, sizeof(ret)-1, "0%o", i);
688         return ret;
689 }
690
691
692 /**
693  Strchr and strrchr_m are very hard to do on general multi-byte strings. 
694  We convert via ucs2 for now.
695 **/
696
697 char *strchr_m(const char *s, char c)
698 {
699         wpstring ws;
700         pstring s2;
701         smb_ucs2_t *p;
702
703         push_ucs2(NULL, ws, s, sizeof(ws), STR_TERMINATE);
704         p = strchr_w(ws, UCS2_CHAR(c));
705         if (!p)
706                 return NULL;
707         *p = 0;
708         pull_ucs2_pstring(s2, ws);
709         return (char *)(s+strlen(s2));
710 }
711
712 char *strrchr_m(const char *s, char c)
713 {
714         wpstring ws;
715         pstring s2;
716         smb_ucs2_t *p;
717
718         push_ucs2(NULL, ws, s, sizeof(ws), STR_TERMINATE);
719         p = strrchr_w(ws, UCS2_CHAR(c));
720         if (!p)
721                 return NULL;
722         *p = 0;
723         pull_ucs2_pstring(s2, ws);
724         return (char *)(s+strlen(s2));
725 }
726
727 /**
728  Convert a string to lower case.
729 **/
730
731 void strlower_m(char *s)
732 {
733         /* this is quite a common operation, so we want it to be
734            fast. We optimise for the ascii case, knowing that all our
735            supported multi-byte character sets are ascii-compatible
736            (ie. they match for the first 128 chars) */
737
738         while (*s && !(((uint8_t)s[0]) & 0x7F)) {
739                 *s = tolower((uint8_t)*s);
740                 s++;
741         }
742
743         if (!*s)
744                 return;
745
746         /* I assume that lowercased string takes the same number of bytes
747          * as source string even in UTF-8 encoding. (VIV) */
748         unix_strlower(s,strlen(s)+1,s,strlen(s)+1);     
749 }
750
751 /**
752  Convert a string to upper case.
753 **/
754
755 void strupper_m(char *s)
756 {
757         /* this is quite a common operation, so we want it to be
758            fast. We optimise for the ascii case, knowing that all our
759            supported multi-byte character sets are ascii-compatible
760            (ie. they match for the first 128 chars) */
761
762         while (*s && !(((uint8_t)s[0]) & 0x7F)) {
763                 *s = toupper((uint8_t)*s);
764                 s++;
765         }
766
767         if (!*s)
768                 return;
769
770         /* I assume that lowercased string takes the same number of bytes
771          * as source string even in multibyte encoding. (VIV) */
772         unix_strupper(s,strlen(s)+1,s,strlen(s)+1);     
773 }
774
775
776 /**
777    work out the number of multibyte chars in a string
778 **/
779 size_t strlen_m(const char *s)
780 {
781         size_t count = 0;
782
783         if (!s) {
784                 return 0;
785         }
786
787         while (*s && !(((uint8_t)s[0]) & 0x7F)) {
788                 s++;
789                 count++;
790         }
791
792         if (!*s) {
793                 return count;
794         }
795
796         push_ucs2(NULL,tmpbuf,s, sizeof(tmpbuf), STR_TERMINATE);
797         return count + strlen_w(tmpbuf);
798 }
799
800 /**
801    Work out the number of multibyte chars in a string, including the NULL
802    terminator.
803 **/
804 size_t strlen_m_term(const char *s)
805 {
806         if (!s) {
807                 return 0;
808         }
809
810         return strlen_m(s) + 1;
811 }
812
813 /**
814  Convert a string to upper case.
815 **/
816
817 char *strdup_upper(const char *s)
818 {
819         char *t = strdup(s);
820         if (t == NULL) {
821                 DEBUG(0, ("strdup_upper: Out of memory!\n"));
822                 return NULL;
823         }
824         strupper_m(t);
825         return t;
826 }
827
828 /**
829  Return a RFC2254 binary string representation of a buffer.
830  Used in LDAP filters.
831  Caller must free.
832 **/
833
834 char *binary_string(char *buf, int len)
835 {
836         char *s;
837         int i, j;
838         const char *hex = "0123456789ABCDEF";
839         s = malloc(len * 3 + 1);
840         if (!s)
841                 return NULL;
842         for (j=i=0;i<len;i++) {
843                 s[j] = '\\';
844                 s[j+1] = hex[((uint8_t)buf[i]) >> 4];
845                 s[j+2] = hex[((uint8_t)buf[i]) & 0xF];
846                 j += 3;
847         }
848         s[j] = 0;
849         return s;
850 }
851
852 /**
853  Just a typesafety wrapper for snprintf into a pstring.
854 **/
855
856  int pstr_sprintf(pstring s, const char *fmt, ...)
857 {
858         va_list ap;
859         int ret;
860
861         va_start(ap, fmt);
862         ret = vsnprintf(s, PSTRING_LEN, fmt, ap);
863         va_end(ap);
864         return ret;
865 }
866
867 #ifndef HAVE_STRNDUP
868 /**
869  Some platforms don't have strndup.
870 **/
871  char *strndup(const char *s, size_t n)
872 {
873         char *ret;
874         
875         n = strnlen(s, n);
876         ret = malloc(n+1);
877         if (!ret)
878                 return NULL;
879         memcpy(ret, s, n);
880         ret[n] = 0;
881
882         return ret;
883 }
884 #endif
885
886 #ifndef HAVE_STRNLEN
887 /**
888  Some platforms don't have strnlen
889 **/
890  size_t strnlen(const char *s, size_t n)
891 {
892         int i;
893         for (i=0; s[i] && i<n; i++)
894                 /* noop */ ;
895         return i;
896 }
897 #endif
898
899 /**
900  List of Strings manipulation functions
901 **/
902
903 #define S_LIST_ABS 16 /* List Allocation Block Size */
904
905 char **str_list_make(const char *string, const char *sep)
906 {
907         char **list, **rlist;
908         const char *str;
909         char *s;
910         int num, lsize;
911         pstring tok;
912         
913         if (!string || !*string)
914                 return NULL;
915         s = strdup(string);
916         if (!s) {
917                 DEBUG(0,("str_list_make: Unable to allocate memory"));
918                 return NULL;
919         }
920         if (!sep) sep = LIST_SEP;
921         
922         num = lsize = 0;
923         list = NULL;
924         
925         str = s;
926         while (next_token(&str, tok, sep, sizeof(tok))) {               
927                 if (num == lsize) {
928                         lsize += S_LIST_ABS;
929                         rlist = (char **)Realloc(list, ((sizeof(char **)) * (lsize +1)));
930                         if (!rlist) {
931                                 DEBUG(0,("str_list_make: Unable to allocate memory"));
932                                 str_list_free(&list);
933                                 SAFE_FREE(s);
934                                 return NULL;
935                         } else
936                                 list = rlist;
937                         memset (&list[num], 0, ((sizeof(char**)) * (S_LIST_ABS +1)));
938                 }
939                 
940                 list[num] = strdup(tok);
941                 if (!list[num]) {
942                         DEBUG(0,("str_list_make: Unable to allocate memory"));
943                         str_list_free(&list);
944                         SAFE_FREE(s);
945                         return NULL;
946                 }
947         
948                 num++;  
949         }
950         
951         SAFE_FREE(s);
952         return list;
953 }
954
955 BOOL str_list_copy(char ***dest, const char **src)
956 {
957         char **list, **rlist;
958         int num, lsize;
959         
960         *dest = NULL;
961         if (!src)
962                 return False;
963         
964         num = lsize = 0;
965         list = NULL;
966                 
967         while (src[num]) {
968                 if (num == lsize) {
969                         lsize += S_LIST_ABS;
970                         rlist = (char **)Realloc(list, ((sizeof(char **)) * (lsize +1)));
971                         if (!rlist) {
972                                 DEBUG(0,("str_list_copy: Unable to re-allocate memory"));
973                                 str_list_free(&list);
974                                 return False;
975                         } else
976                                 list = rlist;
977                         memset (&list[num], 0, ((sizeof(char **)) * (S_LIST_ABS +1)));
978                 }
979                 
980                 list[num] = strdup(src[num]);
981                 if (!list[num]) {
982                         DEBUG(0,("str_list_copy: Unable to allocate memory"));
983                         str_list_free(&list);
984                         return False;
985                 }
986
987                 num++;
988         }
989         
990         *dest = list;
991         return True;    
992 }
993
994 /**
995  * Return true if all the elements of the list match exactly.
996  **/
997 BOOL str_list_compare(char **list1, char **list2)
998 {
999         int num;
1000         
1001         if (!list1 || !list2)
1002                 return (list1 == list2); 
1003         
1004         for (num = 0; list1[num]; num++) {
1005                 if (!list2[num])
1006                         return False;
1007                 if (!strcsequal(list1[num], list2[num]))
1008                         return False;
1009         }
1010         if (list2[num])
1011                 return False; /* if list2 has more elements than list1 fail */
1012         
1013         return True;
1014 }
1015
1016 void str_list_free(char ***list)
1017 {
1018         char **tlist;
1019         
1020         if (!list || !*list)
1021                 return;
1022         tlist = *list;
1023         for(; *tlist; tlist++)
1024                 SAFE_FREE(*tlist);
1025         SAFE_FREE(*list);
1026 }
1027
1028 BOOL str_list_substitute(char **list, const char *pattern, const char *insert)
1029 {
1030         char *p, *s, *t;
1031         ssize_t ls, lp, li, ld, i, d;
1032
1033         if (!list)
1034                 return False;
1035         if (!pattern)
1036                 return False;
1037         if (!insert)
1038                 return False;
1039
1040         lp = (ssize_t)strlen(pattern);
1041         li = (ssize_t)strlen(insert);
1042         ld = li -lp;
1043                         
1044         while (*list) {
1045                 s = *list;
1046                 ls = (ssize_t)strlen(s);
1047
1048                 while ((p = strstr(s, pattern))) {
1049                         t = *list;
1050                         d = p -t;
1051                         if (ld) {
1052                                 t = (char *) malloc(ls +ld +1);
1053                                 if (!t) {
1054                                         DEBUG(0,("str_list_substitute: Unable to allocate memory"));
1055                                         return False;
1056                                 }
1057                                 memcpy(t, *list, d);
1058                                 memcpy(t +d +li, p +lp, ls -d -lp +1);
1059                                 SAFE_FREE(*list);
1060                                 *list = t;
1061                                 ls += ld;
1062                                 s = t +d +li;
1063                         }
1064                         
1065                         for (i = 0; i < li; i++) {
1066                                 switch (insert[i]) {
1067                                         case '`':
1068                                         case '"':
1069                                         case '\'':
1070                                         case ';':
1071                                         case '$':
1072                                         case '%':
1073                                         case '\r':
1074                                         case '\n':
1075                                                 t[d +i] = '_';
1076                                                 break;
1077                                         default:
1078                                                 t[d +i] = insert[i];
1079                                 }
1080                         }       
1081                 }
1082                 
1083                 list++;
1084         }
1085         
1086         return True;
1087 }
1088
1089
1090 #define IPSTR_LIST_SEP  ","
1091
1092 /**
1093  * Add ip string representation to ipstr list. Used also
1094  * as part of @function ipstr_list_make
1095  *
1096  * @param ipstr_list pointer to string containing ip list;
1097  *        MUST BE already allocated and IS reallocated if necessary
1098  * @param ipstr_size pointer to current size of ipstr_list (might be changed
1099  *        as a result of reallocation)
1100  * @param ip IP address which is to be added to list
1101  * @return pointer to string appended with new ip and possibly
1102  *         reallocated to new length
1103  **/
1104
1105 char* ipstr_list_add(char** ipstr_list, const struct in_addr *ip)
1106 {
1107         char* new_ipstr = NULL;
1108         
1109         /* arguments checking */
1110         if (!ipstr_list || !ip) return NULL;
1111
1112         /* attempt to convert ip to a string and append colon separator to it */
1113         if (*ipstr_list) {
1114                 asprintf(&new_ipstr, "%s%s%s", *ipstr_list, IPSTR_LIST_SEP,inet_ntoa(*ip));
1115                 SAFE_FREE(*ipstr_list);
1116         } else {
1117                 asprintf(&new_ipstr, "%s", inet_ntoa(*ip));
1118         }
1119         *ipstr_list = new_ipstr;
1120         return *ipstr_list;
1121 }
1122
1123 /**
1124  * Allocate and initialise an ipstr list using ip adresses
1125  * passed as arguments.
1126  *
1127  * @param ipstr_list pointer to string meant to be allocated and set
1128  * @param ip_list array of ip addresses to place in the list
1129  * @param ip_count number of addresses stored in ip_list
1130  * @return pointer to allocated ip string
1131  **/
1132  
1133 char* ipstr_list_make(char** ipstr_list, const struct in_addr* ip_list, int ip_count)
1134 {
1135         int i;
1136         
1137         /* arguments checking */
1138         if (!ip_list && !ipstr_list) return 0;
1139
1140         *ipstr_list = NULL;
1141         
1142         /* process ip addresses given as arguments */
1143         for (i = 0; i < ip_count; i++)
1144                 *ipstr_list = ipstr_list_add(ipstr_list, &ip_list[i]);
1145         
1146         return (*ipstr_list);
1147 }
1148
1149
1150 /**
1151  * Parse given ip string list into array of ip addresses
1152  * (as in_addr structures)
1153  *
1154  * @param ipstr ip string list to be parsed 
1155  * @param ip_list pointer to array of ip addresses which is
1156  *        allocated by this function and must be freed by caller
1157  * @return number of succesfully parsed addresses
1158  **/
1159  
1160 int ipstr_list_parse(const char* ipstr_list, struct in_addr** ip_list)
1161 {
1162         fstring token_str;
1163         int count;
1164
1165         if (!ipstr_list || !ip_list) return 0;
1166         
1167         for (*ip_list = NULL, count = 0;
1168              next_token(&ipstr_list, token_str, IPSTR_LIST_SEP, FSTRING_LEN);
1169              count++) {
1170              
1171                 struct in_addr addr;
1172
1173                 /* convert single token to ip address */
1174                 if ( (addr.s_addr = inet_addr(token_str)) == INADDR_NONE )
1175                         break;
1176                 
1177                 /* prepare place for another in_addr structure */
1178                 *ip_list = Realloc(*ip_list, (count + 1) * sizeof(struct in_addr));
1179                 if (!*ip_list) return -1;
1180                 
1181                 (*ip_list)[count] = addr;
1182         }
1183         
1184         return count;
1185 }
1186
1187
1188 /**
1189  * Safely free ip string list
1190  *
1191  * @param ipstr_list ip string list to be freed
1192  **/
1193
1194 void ipstr_list_free(char* ipstr_list)
1195 {
1196         SAFE_FREE(ipstr_list);
1197 }
1198
1199 /**
1200  Routine to get hex characters and turn them into a 16 byte array.
1201  the array can be variable length, and any non-hex-numeric
1202  characters are skipped.  "0xnn" or "0Xnn" is specially catered
1203  for.
1204
1205  valid examples: "0A5D15"; "0x15, 0x49, 0xa2"; "59\ta9\te3\n"
1206
1207 **/
1208
1209 size_t strhex_to_str(char *p, size_t len, const char *strhex)
1210 {
1211         size_t i;
1212         size_t num_chars = 0;
1213         uint8_t   lonybble, hinybble;
1214         const char     *hexchars = "0123456789ABCDEF";
1215         char           *p1 = NULL, *p2 = NULL;
1216
1217         for (i = 0; i < len && strhex[i] != 0; i++) {
1218                 if (strnequal(hexchars, "0x", 2)) {
1219                         i++; /* skip two chars */
1220                         continue;
1221                 }
1222
1223                 if (!(p1 = strchr_m(hexchars, toupper(strhex[i]))))
1224                         break;
1225
1226                 i++; /* next hex digit */
1227
1228                 if (!(p2 = strchr_m(hexchars, toupper(strhex[i]))))
1229                         break;
1230
1231                 /* get the two nybbles */
1232                 hinybble = PTR_DIFF(p1, hexchars);
1233                 lonybble = PTR_DIFF(p2, hexchars);
1234
1235                 p[num_chars] = (hinybble << 4) | lonybble;
1236                 num_chars++;
1237
1238                 p1 = NULL;
1239                 p2 = NULL;
1240         }
1241         return num_chars;
1242 }
1243
1244 DATA_BLOB strhex_to_data_blob(const char *strhex) 
1245 {
1246         DATA_BLOB ret_blob = data_blob(NULL, strlen(strhex)/2+1);
1247
1248         ret_blob.length = strhex_to_str(ret_blob.data,  
1249                                         strlen(strhex), 
1250                                         strhex);
1251
1252         return ret_blob;
1253 }
1254
1255 /**
1256  * Routine to print a buffer as HEX digits, into an allocated string.
1257  */
1258
1259 void hex_encode(const unsigned char *buff_in, size_t len, char **out_hex_buffer)
1260 {
1261         int i;
1262         char *hex_buffer;
1263
1264         *out_hex_buffer = smb_xmalloc((len*2)+1);
1265         hex_buffer = *out_hex_buffer;
1266
1267         for (i = 0; i < len; i++)
1268                 slprintf(&hex_buffer[i*2], 3, "%02X", buff_in[i]);
1269 }
1270
1271
1272 /**
1273  Unescape a URL encoded string, in place.
1274 **/
1275
1276 void rfc1738_unescape(char *buf)
1277 {
1278         char *p=buf;
1279
1280         while ((p=strchr_m(p,'+')))
1281                 *p = ' ';
1282
1283         p = buf;
1284
1285         while (p && *p && (p=strchr_m(p,'%'))) {
1286                 int c1 = p[1];
1287                 int c2 = p[2];
1288
1289                 if (c1 >= '0' && c1 <= '9')
1290                         c1 = c1 - '0';
1291                 else if (c1 >= 'A' && c1 <= 'F')
1292                         c1 = 10 + c1 - 'A';
1293                 else if (c1 >= 'a' && c1 <= 'f')
1294                         c1 = 10 + c1 - 'a';
1295                 else {p++; continue;}
1296
1297                 if (c2 >= '0' && c2 <= '9')
1298                         c2 = c2 - '0';
1299                 else if (c2 >= 'A' && c2 <= 'F')
1300                         c2 = 10 + c2 - 'A';
1301                 else if (c2 >= 'a' && c2 <= 'f')
1302                         c2 = 10 + c2 - 'a';
1303                 else {p++; continue;}
1304                         
1305                 *p = (c1<<4) | c2;
1306
1307                 memmove(p+1, p+3, strlen(p+3)+1);
1308                 p++;
1309         }
1310 }
1311
1312 static const char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1313
1314 /**
1315  * Decode a base64 string into a DATA_BLOB - simple and slow algorithm
1316  **/
1317 DATA_BLOB base64_decode_data_blob(const char *s)
1318 {
1319         int bit_offset, byte_offset, idx, i, n;
1320         DATA_BLOB decoded = data_blob(s, strlen(s)+1);
1321         uint8_t *d = decoded.data;
1322         char *p;
1323
1324         n=i=0;
1325
1326         while (*s && (p=strchr_m(b64,*s))) {
1327                 idx = (int)(p - b64);
1328                 byte_offset = (i*6)/8;
1329                 bit_offset = (i*6)%8;
1330                 d[byte_offset] &= ~((1<<(8-bit_offset))-1);
1331                 if (bit_offset < 3) {
1332                         d[byte_offset] |= (idx << (2-bit_offset));
1333                         n = byte_offset+1;
1334                 } else {
1335                         d[byte_offset] |= (idx >> (bit_offset-2));
1336                         d[byte_offset+1] = 0;
1337                         d[byte_offset+1] |= (idx << (8-(bit_offset-2))) & 0xFF;
1338                         n = byte_offset+2;
1339                 }
1340                 s++; i++;
1341         }
1342
1343         /* fix up length */
1344         decoded.length = n;
1345         return decoded;
1346 }
1347
1348 /**
1349  * Decode a base64 string in-place - wrapper for the above
1350  **/
1351 void base64_decode_inplace(char *s)
1352 {
1353         DATA_BLOB decoded = base64_decode_data_blob(s);
1354         memcpy(s, decoded.data, decoded.length);
1355         data_blob_free(&decoded);
1356
1357         /* null terminate */
1358         s[decoded.length] = '\0';
1359 }
1360
1361 /**
1362  * Encode a base64 string into a malloc()ed string caller to free.
1363  *
1364  *From SQUID: adopted from http://ftp.sunet.se/pub2/gnu/vm/base64-encode.c with adjustments
1365  **/
1366 char * base64_encode_data_blob(DATA_BLOB data)
1367 {
1368         int bits = 0;
1369         int char_count = 0;
1370         size_t out_cnt = 0;
1371         size_t len = data.length;
1372         size_t output_len = data.length * 2;
1373         char *result = malloc(output_len); /* get us plenty of space */
1374
1375         while (len-- && out_cnt < (data.length * 2) - 5) {
1376                 int c = (uint8_t) *(data.data++);
1377                 bits += c;
1378                 char_count++;
1379                 if (char_count == 3) {
1380                         result[out_cnt++] = b64[bits >> 18];
1381                         result[out_cnt++] = b64[(bits >> 12) & 0x3f];
1382                         result[out_cnt++] = b64[(bits >> 6) & 0x3f];
1383             result[out_cnt++] = b64[bits & 0x3f];
1384             bits = 0;
1385             char_count = 0;
1386         } else {
1387             bits <<= 8;
1388         }
1389     }
1390     if (char_count != 0) {
1391         bits <<= 16 - (8 * char_count);
1392         result[out_cnt++] = b64[bits >> 18];
1393         result[out_cnt++] = b64[(bits >> 12) & 0x3f];
1394         if (char_count == 1) {
1395             result[out_cnt++] = '=';
1396             result[out_cnt++] = '=';
1397         } else {
1398             result[out_cnt++] = b64[(bits >> 6) & 0x3f];
1399             result[out_cnt++] = '=';
1400         }
1401     }
1402     result[out_cnt] = '\0';     /* terminate */
1403     return result;
1404 }
1405
1406 #ifdef VALGRIND
1407 size_t valgrind_strlen(const char *s)
1408 {
1409         size_t count;
1410         for(count = 0; *s++; count++)
1411                 ;
1412         return count;
1413 }
1414 #endif
1415
1416
1417 /*
1418   format a string into length-prefixed dotted domain format, as used in NBT
1419   and in some ADS structures
1420 */
1421 const char *str_format_nbt_domain(TALLOC_CTX *mem_ctx, const char *s)
1422 {
1423         char *ret;
1424         int i;
1425         if (!s || !*s) {
1426                 return talloc_strdup(mem_ctx, "");
1427         }
1428         ret = talloc(mem_ctx, strlen(s)+2);
1429         if (!ret) {
1430                 return ret;
1431         }
1432         
1433         memcpy(ret+1, s, strlen(s)+1);
1434         ret[0] = '.';
1435
1436         for (i=0;ret[i];i++) {
1437                 if (ret[i] == '.') {
1438                         char *p = strchr(ret+i+1, '.');
1439                         if (p) {
1440                                 ret[i] = p-(ret+i+1);
1441                         } else {
1442                                 ret[i] = strlen(ret+i+1);
1443                         }
1444                 }
1445         }
1446
1447         return ret;
1448 }
1449
1450 BOOL add_string_to_array(TALLOC_CTX *mem_ctx,
1451                          const char *str, const char ***strings, int *num)
1452 {
1453         char *dup_str = talloc_strdup(mem_ctx, str);
1454
1455         *strings = talloc_realloc(*strings,
1456                                   ((*num)+1) * sizeof(**strings));
1457
1458         if ((*strings == NULL) || (dup_str == NULL))
1459                 return False;
1460
1461         (*strings)[*num] = dup_str;
1462         *num += 1;
1463
1464         return True;
1465 }
1466
1467
1468
1469 /*
1470   varient of strcmp() that handles NULL ptrs
1471 */
1472 int strcmp_safe(const char *s1, const char *s2)
1473 {
1474         if (s1 == s2) {
1475                 return 0;
1476         }
1477         if (s1 == NULL || s2 == NULL) {
1478                 return s1?-1:1;
1479         }
1480         return strcmp(s1, s2);
1481 }