Fix for problem with "" string in trim_string(). Pointed out by Ben Winslow <rain...
[samba.git] / source3 / lib / util_str.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    Samba utility functions
5    Copyright (C) Andrew Tridgell 1992-1998
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 extern int DEBUGLEVEL;
25
26 static char *last_ptr=NULL;
27
28 void set_first_token(char *ptr)
29 {
30         last_ptr = ptr;
31 }
32
33 /****************************************************************************
34   Get the next token from a string, return False if none found
35   handles double-quotes. 
36 Based on a routine by GJC@VILLAGE.COM. 
37 Extensively modified by Andrew.Tridgell@anu.edu.au
38 ****************************************************************************/
39 BOOL next_token(char **ptr,char *buff,char *sep, size_t bufsize)
40 {
41   char *s;
42   BOOL quoted;
43   size_t len=1;
44
45   if (!ptr) ptr = &last_ptr;
46   if (!ptr) return(False);
47
48   s = *ptr;
49
50   /* default to simple separators */
51   if (!sep) sep = " \t\n\r";
52
53   /* find the first non sep char */
54   while(*s && strchr(sep,*s)) s++;
55
56   /* nothing left? */
57   if (! *s) return(False);
58
59   /* copy over the token */
60   for (quoted = False; len < bufsize && *s && (quoted || !strchr(sep,*s)); s++)
61     {
62             if (*s == '\"') {
63                     quoted = !quoted;
64             } else {
65                     len++;
66                     *buff++ = *s;
67             }
68     }
69
70   *ptr = (*s) ? s+1 : s;  
71   *buff = 0;
72   last_ptr = *ptr;
73
74   return(True);
75 }
76
77 /****************************************************************************
78 Convert list of tokens to array; dependent on above routine.
79 Uses last_ptr from above - bit of a hack.
80 ****************************************************************************/
81 char **toktocliplist(int *ctok, char *sep)
82 {
83   char *s=last_ptr;
84   int ictok=0;
85   char **ret, **iret;
86
87   if (!sep) sep = " \t\n\r";
88
89   while(*s && strchr(sep,*s)) s++;
90
91   /* nothing left? */
92   if (!*s) return(NULL);
93
94   do {
95     ictok++;
96     while(*s && (!strchr(sep,*s))) s++;
97     while(*s && strchr(sep,*s)) *s++=0;
98   } while(*s);
99
100   *ctok=ictok;
101   s=last_ptr;
102
103   if (!(ret=iret=malloc(ictok*sizeof(char *)))) return NULL;
104   
105   while(ictok--) {    
106     *iret++=s;
107     while(*s++);
108     while(!*s) s++;
109   }
110
111   return ret;
112 }
113
114
115 /*******************************************************************
116   case insensitive string compararison
117 ********************************************************************/
118 int StrCaseCmp(const char *s, const char *t)
119 {
120   /* compare until we run out of string, either t or s, or find a difference */
121   /* We *must* use toupper rather than tolower here due to the
122      asynchronous upper to lower mapping.
123    */
124 #if !defined(KANJI_WIN95_COMPATIBILITY)
125   /*
126    * For completeness we should put in equivalent code for code pages
127    * 949 (Korean hangul) and 950 (Big5 Traditional Chinese) here - but
128    * doubt anyone wants Samba to behave differently from Win95 and WinNT
129    * here. They both treat full width ascii characters as case senstive
130    * filenames (ie. they don't do the work we do here).
131    * JRA.
132    */
133
134   if(lp_client_code_page() == KANJI_CODEPAGE)
135   {
136     /* Win95 treats full width ascii characters as case sensitive. */
137     int diff;
138     for (;;)
139     {
140       if (!*s || !*t)
141             return toupper (*s) - toupper (*t);
142       else if (is_sj_alph (*s) && is_sj_alph (*t))
143       {
144         diff = sj_toupper2 (*(s+1)) - sj_toupper2 (*(t+1));
145         if (diff)
146           return diff;
147         s += 2;
148         t += 2;
149       }
150       else if (is_shift_jis (*s) && is_shift_jis (*t))
151       {
152         diff = ((int) (unsigned char) *s) - ((int) (unsigned char) *t);
153         if (diff)
154           return diff;
155         diff = ((int) (unsigned char) *(s+1)) - ((int) (unsigned char) *(t+1));
156         if (diff)
157           return diff;
158         s += 2;
159         t += 2;
160       }
161       else if (is_shift_jis (*s))
162         return 1;
163       else if (is_shift_jis (*t))
164         return -1;
165       else 
166       {
167         diff = toupper (*s) - toupper (*t);
168         if (diff)
169           return diff;
170         s++;
171         t++;
172       }
173     }
174   }
175   else
176 #endif /* KANJI_WIN95_COMPATIBILITY */
177   {
178     while (*s && *t && toupper(*s) == toupper(*t))
179     {
180       s++;
181       t++;
182     }
183
184     return(toupper(*s) - toupper(*t));
185   }
186 }
187
188 /*******************************************************************
189   case insensitive string compararison, length limited
190 ********************************************************************/
191 int StrnCaseCmp(const char *s, const char *t, size_t n)
192 {
193   /* compare until we run out of string, either t or s, or chars */
194   /* We *must* use toupper rather than tolower here due to the
195      asynchronous upper to lower mapping.
196    */
197 #if !defined(KANJI_WIN95_COMPATIBILITY)
198   /*
199    * For completeness we should put in equivalent code for code pages
200    * 949 (Korean hangul) and 950 (Big5 Traditional Chinese) here - but
201    * doubt anyone wants Samba to behave differently from Win95 and WinNT
202    * here. They both treat full width ascii characters as case senstive
203    * filenames (ie. they don't do the work we do here).
204    * JRA. 
205    */
206
207   if(lp_client_code_page() == KANJI_CODEPAGE)
208   {
209     /* Win95 treats full width ascii characters as case sensitive. */
210     int diff;
211     for (;n > 0;)
212     {
213       if (!*s || !*t)
214         return toupper (*s) - toupper (*t);
215       else if (is_sj_alph (*s) && is_sj_alph (*t))
216       {
217         diff = sj_toupper2 (*(s+1)) - sj_toupper2 (*(t+1));
218         if (diff)
219           return diff;
220         s += 2;
221         t += 2;
222         n -= 2;
223       }
224       else if (is_shift_jis (*s) && is_shift_jis (*t))
225       {
226         diff = ((int) (unsigned char) *s) - ((int) (unsigned char) *t);
227         if (diff)
228           return diff;
229         diff = ((int) (unsigned char) *(s+1)) - ((int) (unsigned char) *(t+1));
230         if (diff)
231           return diff;
232         s += 2;
233         t += 2;
234         n -= 2;
235       }
236       else if (is_shift_jis (*s))
237         return 1;
238       else if (is_shift_jis (*t))
239         return -1;
240       else 
241       {
242         diff = toupper (*s) - toupper (*t);
243         if (diff)
244           return diff;
245         s++;
246         t++;
247         n--;
248       }
249     }
250     return 0;
251   }
252   else
253 #endif /* KANJI_WIN95_COMPATIBILITY */
254   {
255     while (n && *s && *t && toupper(*s) == toupper(*t))
256     {
257       s++;
258       t++;
259       n--;
260     }
261
262     /* not run out of chars - strings are different lengths */
263     if (n) 
264       return(toupper(*s) - toupper(*t));
265
266     /* identical up to where we run out of chars, 
267        and strings are same length */
268     return(0);
269   }
270 }
271
272 /*******************************************************************
273   compare 2 strings 
274 ********************************************************************/
275 BOOL strequal(const char *s1, const char *s2)
276 {
277   if (s1 == s2) return(True);
278   if (!s1 || !s2) return(False);
279   
280   return(StrCaseCmp(s1,s2)==0);
281 }
282
283 /*******************************************************************
284   compare 2 strings up to and including the nth char.
285   ******************************************************************/
286 BOOL strnequal(const char *s1,const char *s2,size_t n)
287 {
288   if (s1 == s2) return(True);
289   if (!s1 || !s2 || !n) return(False);
290   
291   return(StrnCaseCmp(s1,s2,n)==0);
292 }
293
294 /*******************************************************************
295   compare 2 strings (case sensitive)
296 ********************************************************************/
297 BOOL strcsequal(const char *s1,const char *s2)
298 {
299   if (s1 == s2) return(True);
300   if (!s1 || !s2) return(False);
301   
302   return(strcmp(s1,s2)==0);
303 }
304
305 /***************************************************************************
306 Do a case-insensitive, whitespace-ignoring string compare.
307 ***************************************************************************/
308 int strwicmp(char *psz1, char *psz2)
309 {
310         /* if BOTH strings are NULL, return TRUE, if ONE is NULL return */
311         /* appropriate value. */
312         if (psz1 == psz2)
313                 return (0);
314         else if (psz1 == NULL)
315                 return (-1);
316         else if (psz2 == NULL)
317                 return (1);
318
319         /* sync the strings on first non-whitespace */
320         while (1)
321         {
322                 while (isspace(*psz1))
323                         psz1++;
324                 while (isspace(*psz2))
325                         psz2++;
326                 if (toupper(*psz1) != toupper(*psz2) || *psz1 == '\0'
327                     || *psz2 == '\0')
328                         break;
329                 psz1++;
330                 psz2++;
331         }
332         return (*psz1 - *psz2);
333 }
334
335
336 /*******************************************************************
337   convert a string to lower case
338 ********************************************************************/
339 void strlower(char *s)
340 {
341   while (*s)
342   {
343 #if !defined(KANJI_WIN95_COMPATIBILITY)
344   /*
345    * For completeness we should put in equivalent code for code pages
346    * 949 (Korean hangul) and 950 (Big5 Traditional Chinese) here - but
347    * doubt anyone wants Samba to behave differently from Win95 and WinNT
348    * here. They both treat full width ascii characters as case senstive
349    * filenames (ie. they don't do the work we do here).
350    * JRA. 
351    */
352
353     if(lp_client_code_page() == KANJI_CODEPAGE)
354     {
355       /* Win95 treats full width ascii characters as case sensitive. */
356       if (is_shift_jis (*s))
357       {
358         if (is_sj_upper (s[0], s[1]))
359           s[1] = sj_tolower2 (s[1]);
360         s += 2;
361       }
362       else if (is_kana (*s))
363       {
364         s++;
365       }
366       else
367       {
368         if (isupper(*s))
369           *s = tolower(*s);
370         s++;
371       }
372     }
373     else
374 #endif /* KANJI_WIN95_COMPATIBILITY */
375     {
376       size_t skip = get_character_len( *s );
377       if( skip != 0 )
378         s += skip;
379       else
380       {
381         if (isupper(*s))
382           *s = tolower(*s);
383         s++;
384       }
385     }
386   }
387 }
388
389 /*******************************************************************
390   convert a string to upper case
391 ********************************************************************/
392 void strupper(char *s)
393 {
394   while (*s)
395   {
396 #if !defined(KANJI_WIN95_COMPATIBILITY)
397   /*
398    * For completeness we should put in equivalent code for code pages
399    * 949 (Korean hangul) and 950 (Big5 Traditional Chinese) here - but
400    * doubt anyone wants Samba to behave differently from Win95 and WinNT
401    * here. They both treat full width ascii characters as case senstive
402    * filenames (ie. they don't do the work we do here).
403    * JRA. 
404    */
405
406     if(lp_client_code_page() == KANJI_CODEPAGE)
407     {
408       /* Win95 treats full width ascii characters as case sensitive. */
409       if (is_shift_jis (*s))
410       {
411         if (is_sj_lower (s[0], s[1]))
412           s[1] = sj_toupper2 (s[1]);
413         s += 2;
414       }
415       else if (is_kana (*s))
416       {
417         s++;
418       }
419       else
420       {
421         if (islower(*s))
422           *s = toupper(*s);
423         s++;
424       }
425     }
426     else
427 #endif /* KANJI_WIN95_COMPATIBILITY */
428     {
429       size_t skip = get_character_len( *s );
430       if( skip != 0 )
431         s += skip;
432       else
433       {
434         if (islower(*s))
435           *s = toupper(*s);
436         s++;
437       }
438     }
439   }
440 }
441
442 /*******************************************************************
443   convert a string to "normal" form
444 ********************************************************************/
445 void strnorm(char *s)
446 {
447   extern int case_default;
448   if (case_default == CASE_UPPER)
449     strupper(s);
450   else
451     strlower(s);
452 }
453
454 /*******************************************************************
455 check if a string is in "normal" case
456 ********************************************************************/
457 BOOL strisnormal(char *s)
458 {
459   extern int case_default;
460   if (case_default == CASE_UPPER)
461     return(!strhaslower(s));
462
463   return(!strhasupper(s));
464 }
465
466
467 /****************************************************************************
468   string replace
469 ****************************************************************************/
470 void string_replace(char *s,char oldc,char newc)
471 {
472   size_t skip;
473
474   /*
475    * sbcs optimization.
476    */
477   if(!global_is_multibyte_codepage) {
478     while (*s) {
479       if (oldc == *s)
480         *s = newc;
481       s++;
482     }
483   } else {
484     while (*s)
485     {
486       skip = get_character_len( *s );
487       if( skip != 0 )
488         s += skip;
489       else
490       {
491         if (oldc == *s)
492           *s = newc;
493         s++;
494       }
495     }
496   }
497 }
498
499
500 /*******************************************************************
501 skip past some strings in a buffer
502 ********************************************************************/
503 char *skip_string(char *buf,size_t n)
504 {
505   while (n--)
506     buf += strlen(buf) + 1;
507   return(buf);
508 }
509
510 /*******************************************************************
511  Count the number of characters in a string. Normally this will
512  be the same as the number of bytes in a string for single byte strings,
513  but will be different for multibyte.
514  16.oct.98, jdblair@cobaltnet.com.
515 ********************************************************************/
516
517 size_t str_charnum(const char *s)
518 {
519   size_t len = 0;
520   
521   /*
522    * sbcs optimization.
523    */
524   if(!global_is_multibyte_codepage) {
525     return strlen(s);
526   } else {
527     while (*s != '\0') {
528       int skip = get_character_len(*s);
529       s += (skip ? skip : 1);
530       len++;
531     }
532   }
533   return len;
534 }
535
536 /*******************************************************************
537 trim the specified elements off the front and back of a string
538 ********************************************************************/
539
540 BOOL trim_string(char *s,const char *front,const char *back)
541 {
542     BOOL ret = False;
543     size_t s_len;
544     size_t front_len;
545     size_t back_len;
546     char        *sP;
547
548         /* Ignore null or empty strings. */
549
550     if ( !s || (s[0] == '\0'))
551         return False;
552
553     sP  = s;
554     s_len       = strlen( s ) + 1;
555     front_len   = (front) ? strlen( front ) + 1 : 0;
556     back_len    = (back) ? strlen( back ) + 1 : 0;
557
558     /*
559      * remove "front" string from given "s", if it matches front part,
560      * repeatedly.
561      */
562     if ( front && front_len > 1 ) {
563         while (( s_len >= front_len )&&
564                ( memcmp( sP, front, front_len - 1 )) == 0 ) {
565             ret         = True;
566             sP          += ( front_len - 1 );
567             s_len       -= ( front_len - 1 );
568         }
569     }
570
571     /*
572      * we'll memmove sP to s later, after we're done with
573      * back part removal, for minimizing copy.
574      */
575
576
577     /*
578      * We split out the multibyte code page
579      * case here for speed purposes. Under a
580      * multibyte code page we need to walk the
581      * string forwards only and multiple times.
582      * Thanks to John Blair for finding this
583      * one. JRA.
584      */
585     /*
586      * This JRA's comment is partly correct, but partly wrong.
587      * You can always check from "end" part, and if it did not match,
588      * it means there is no possibility of finding one.
589      * If you found matching point, mark them, then look from front
590      * if marking point suits multi-byte string rule.
591      * Kenichi Okuyama.
592      */
593
594     if ( back && back_len > 1 && s_len > back_len) {
595         char    *bP     = sP + s_len - back_len;
596         long    b_len   = s_len;
597
598         while (( b_len >= back_len )&&
599                ( memcmp( bP, back, back_len - 1 ) == 0 )) {
600             bP          -= ( back_len - 1 );
601             b_len       -= ( back_len - 1 );
602         }
603
604         /*
605          * You're here, means you ether have found match multiple times,
606          * or you found none. If you've found match, then bP should be
607          * moving.
608          */
609         if ( bP != sP + s_len - back_len ) {
610             bP  += ( back_len - 1 ); /* slide bP to first matching point. */
611
612             if( !global_is_multibyte_codepage ) {
613                 /* simply terminate */
614                 (*bP)   = '\0';
615                 s_len   = b_len;
616                 ret     = True;
617             } else {
618                 /* trace string from start. */
619                 char    *cP     = sP;
620                 while ( cP < sP + s_len - back_len ) {
621                     size_t      skip;
622                     skip        = skip_multibyte_char( *cP );
623                     cP  += ( skip ? skip : 1 );
624                     if ( cP == bP ) {
625                         /* you found the match */
626                         (*bP)   = '\0';
627                         ret     = True;
628                         s_len   = b_len;
629                         break;
630                     }
631                     while (( cP > bP )&&( bP < sP + s_len - back_len )) {
632                         bP      += ( back_len - 1 );
633                         b_len   += ( back_len - 1 );
634                     }
635                 }
636             }
637         }
638     }
639
640     /* if front found matching point */
641     if ( sP != s ) {
642         /* slide string to buffer top */
643         memmove( s, sP, s_len );
644     }
645     return ret;
646 }
647
648
649 /****************************************************************************
650 does a string have any uppercase chars in it?
651 ****************************************************************************/
652 BOOL strhasupper(const char *s)
653 {
654   while (*s) 
655   {
656 #if !defined(KANJI_WIN95_COMPATIBILITY)
657   /*
658    * For completeness we should put in equivalent code for code pages
659    * 949 (Korean hangul) and 950 (Big5 Traditional Chinese) here - but
660    * doubt anyone wants Samba to behave differently from Win95 and WinNT
661    * here. They both treat full width ascii characters as case senstive
662    * filenames (ie. they don't do the work we do here).
663    * JRA. 
664    */
665
666     if(lp_client_code_page() == KANJI_CODEPAGE)
667     {
668       /* Win95 treats full width ascii characters as case sensitive. */
669       if (is_shift_jis (*s))
670         s += 2;
671       else if (is_kana (*s))
672         s++;
673       else
674       {
675         if (isupper(*s))
676           return(True);
677         s++;
678       }
679     }
680     else
681 #endif /* KANJI_WIN95_COMPATIBILITY */
682     {
683       size_t skip = get_character_len( *s );
684       if( skip != 0 )
685         s += skip;
686       else {
687         if (isupper(*s))
688           return(True);
689         s++;
690       }
691     }
692   }
693   return(False);
694 }
695
696 /****************************************************************************
697 does a string have any lowercase chars in it?
698 ****************************************************************************/
699 BOOL strhaslower(const char *s)
700 {
701   while (*s) 
702   {
703 #if !defined(KANJI_WIN95_COMPATIBILITY)
704   /*
705    * For completeness we should put in equivalent code for code pages
706    * 949 (Korean hangul) and 950 (Big5 Traditional Chinese) here - but
707    * doubt anyone wants Samba to behave differently from Win95 and WinNT
708    * here. They both treat full width ascii characters as case senstive
709    * filenames (ie. they don't do the work we do here).
710    * JRA. 
711    */
712
713     if(lp_client_code_page() == KANJI_CODEPAGE)
714     {
715       /* Win95 treats full width ascii characters as case sensitive. */
716       if (is_shift_jis (*s))
717       {
718         if (is_sj_upper (s[0], s[1]))
719           return(True);
720         if (is_sj_lower (s[0], s[1]))
721           return (True);
722         s += 2;
723       }
724       else if (is_kana (*s))
725       {
726         s++;
727       }
728       else
729       {
730         if (islower(*s))
731           return(True);
732         s++;
733       }
734     }
735     else
736 #endif /* KANJI_WIN95_COMPATIBILITY */
737     {
738       size_t skip = get_character_len( *s );
739       if( skip != 0 )
740         s += skip;
741       else {
742         if (islower(*s))
743           return(True);
744         s++;
745       }
746     }
747   }
748   return(False);
749 }
750
751 /****************************************************************************
752 find the number of chars in a string
753 ****************************************************************************/
754 size_t count_chars(const char *s,char c)
755 {
756   size_t count=0;
757
758 #if !defined(KANJI_WIN95_COMPATIBILITY)
759   /*
760    * For completeness we should put in equivalent code for code pages
761    * 949 (Korean hangul) and 950 (Big5 Traditional Chinese) here - but
762    * doubt anyone wants Samba to behave differently from Win95 and WinNT
763    * here. They both treat full width ascii characters as case senstive
764    * filenames (ie. they don't do the work we do here).
765    * JRA. 
766    */
767
768   if(lp_client_code_page() == KANJI_CODEPAGE)
769   {
770     /* Win95 treats full width ascii characters as case sensitive. */
771     while (*s) 
772     {
773       if (is_shift_jis (*s))
774         s += 2;
775       else 
776       {
777         if (*s == c)
778           count++;
779         s++;
780       }
781     }
782   }
783   else
784 #endif /* KANJI_WIN95_COMPATIBILITY */
785   {
786     while (*s) 
787     {
788       size_t skip = get_character_len( *s );
789       if( skip != 0 )
790         s += skip;
791       else {
792         if (*s == c)
793           count++;
794         s++;
795       }
796     }
797   }
798   return(count);
799 }
800
801 /*******************************************************************
802 Return True if a string consists only of one particular character.
803 ********************************************************************/
804
805 BOOL str_is_all(const char *s,char c)
806 {
807   if(s == NULL)
808     return False;
809   if(!*s)
810     return False;
811
812 #if !defined(KANJI_WIN95_COMPATIBILITY)
813   /*
814    * For completeness we should put in equivalent code for code pages
815    * 949 (Korean hangul) and 950 (Big5 Traditional Chinese) here - but
816    * doubt anyone wants Samba to behave differently from Win95 and WinNT
817    * here. They both treat full width ascii characters as case senstive
818    * filenames (ie. they don't do the work we do here).
819    * JRA.
820    */
821
822   if(lp_client_code_page() == KANJI_CODEPAGE)
823   {
824     /* Win95 treats full width ascii characters as case sensitive. */
825     while (*s)
826     {
827       if (is_shift_jis (*s))
828         s += 2;
829       else
830       {
831         if (*s != c)
832           return False;
833         s++;
834       }
835     }
836   }
837   else
838 #endif /* KANJI_WIN95_COMPATIBILITY */
839   {
840     while (*s)
841     {
842       size_t skip = get_character_len( *s );
843       if( skip != 0 )
844         s += skip;
845       else {
846         if (*s != c)
847           return False;
848         s++;
849       }
850     }
851   }
852   return True;
853 }
854
855 /*******************************************************************
856 safe string copy into a known length string. maxlength does not
857 include the terminating zero.
858 ********************************************************************/
859
860 char *safe_strcpy(char *dest,const char *src, size_t maxlength)
861 {
862     size_t len;
863
864     if (!dest) {
865         DEBUG(0,("ERROR: NULL dest in safe_strcpy\n"));
866         return NULL;
867     }
868
869     if (!src) {
870         *dest = 0;
871         return dest;
872     }  
873
874     len = strlen(src);
875
876     if (len > maxlength) {
877             DEBUG(0,("ERROR: string overflow by %d in safe_strcpy [%.50s]\n",
878                      (int)(len-maxlength), src));
879             len = maxlength;
880     }
881       
882     memcpy(dest, src, len);
883     dest[len] = 0;
884     return dest;
885 }  
886
887 /*******************************************************************
888 safe string cat into a string. maxlength does not
889 include the terminating zero.
890 ********************************************************************/
891
892 char *safe_strcat(char *dest, const char *src, size_t maxlength)
893 {
894     size_t src_len, dest_len;
895
896     if (!dest) {
897         DEBUG(0,("ERROR: NULL dest in safe_strcat\n"));
898         return NULL;
899     }
900
901     if (!src) {
902         return dest;
903     }  
904
905     src_len = strlen(src);
906     dest_len = strlen(dest);
907
908     if (src_len + dest_len > maxlength) {
909             DEBUG(0,("ERROR: string overflow by %d in safe_strcat [%.50s]\n",
910                      (int)(src_len + dest_len - maxlength), src));
911             src_len = maxlength - dest_len;
912     }
913       
914     memcpy(&dest[dest_len], src, src_len);
915     dest[dest_len + src_len] = 0;
916     return dest;
917 }
918
919 /*******************************************************************
920  Paranoid strcpy into a buffer of given length (includes terminating
921  zero. Strips out all but 'a-Z0-9' and replaces with '_'. Deliberately
922  does *NOT* check for multibyte characters. Don't change it !
923 ********************************************************************/
924
925 char *alpha_strcpy(char *dest, const char *src, size_t maxlength)
926 {
927         size_t len, i;
928
929         if (!dest) {
930                 DEBUG(0,("ERROR: NULL dest in alpha_strcpy\n"));
931                 return NULL;
932         }
933
934         if (!src) {
935                 *dest = 0;
936                 return dest;
937         }  
938
939         len = strlen(src);
940         if (len >= maxlength)
941                 len = maxlength - 1;
942
943         for(i = 0; i < len; i++) {
944                 int val = (src[i] & 0xff);
945                 if(isupper(val) ||islower(val) || isdigit(val))
946                         dest[i] = src[i];
947                 else
948                         dest[i] = '_';
949         }
950
951         dest[i] = '\0';
952
953         return dest;
954 }
955
956 /****************************************************************************
957  Like strncpy but always null terminates. Make sure there is room!
958  The variable n should always be one less than the available size.
959 ****************************************************************************/
960
961 char *StrnCpy(char *dest,const char *src,size_t n)
962 {
963   char *d = dest;
964   if (!dest) return(NULL);
965   if (!src) {
966     *dest = 0;
967     return(dest);
968   }
969   while (n-- && (*d++ = *src++)) ;
970   *d = 0;
971   return(dest);
972 }
973
974 /****************************************************************************
975 like strncpy but copies up to the character marker.  always null terminates.
976 returns a pointer to the character marker in the source string (src).
977 ****************************************************************************/
978 char *strncpyn(char *dest, const char *src,size_t n, char c)
979 {
980         char *p;
981         size_t str_len;
982
983         p = strchr(src, c);
984         if (p == NULL)
985         {
986                 DEBUG(5, ("strncpyn: separator character (%c) not found\n", c));
987                 return NULL;
988         }
989
990         str_len = PTR_DIFF(p, src);
991         strncpy(dest, src, MIN(n, str_len));
992         dest[str_len] = '\0';
993
994         return p;
995 }
996
997
998 /*************************************************************
999  Routine to get hex characters and turn them into a 16 byte array.
1000  the array can be variable length, and any non-hex-numeric
1001  characters are skipped.  "0xnn" or "0Xnn" is specially catered
1002  for.
1003
1004  valid examples: "0A5D15"; "0x15, 0x49, 0xa2"; "59\ta9\te3\n"
1005
1006 **************************************************************/
1007 size_t strhex_to_str(char *p, size_t len, const char *strhex)
1008 {
1009         size_t i;
1010         size_t num_chars = 0;
1011         unsigned char   lonybble, hinybble;
1012         char           *hexchars = "0123456789ABCDEF";
1013         char           *p1 = NULL, *p2 = NULL;
1014
1015         for (i = 0; i < len && strhex[i] != 0; i++)
1016         {
1017                 if (strnequal(hexchars, "0x", 2))
1018                 {
1019                         i++; /* skip two chars */
1020                         continue;
1021                 }
1022
1023                 if (!(p1 = strchr(hexchars, toupper(strhex[i]))))
1024                 {
1025                         break;
1026                 }
1027
1028                 i++; /* next hex digit */
1029
1030                 if (!(p2 = strchr(hexchars, toupper(strhex[i]))))
1031                 {
1032                         break;
1033                 }
1034
1035                 /* get the two nybbles */
1036                 hinybble = PTR_DIFF(p1, hexchars);
1037                 lonybble = PTR_DIFF(p2, hexchars);
1038
1039                 p[num_chars] = (hinybble << 4) | lonybble;
1040                 num_chars++;
1041
1042                 p1 = NULL;
1043                 p2 = NULL;
1044         }
1045         return num_chars;
1046 }
1047
1048 /****************************************************************************
1049 check if a string is part of a list
1050 ****************************************************************************/
1051 BOOL in_list(char *s,char *list,BOOL casesensitive)
1052 {
1053   pstring tok;
1054   char *p=list;
1055
1056   if (!list) return(False);
1057
1058   while (next_token(&p,tok,LIST_SEP,sizeof(tok))) {
1059     if (casesensitive) {
1060       if (strcmp(tok,s) == 0)
1061         return(True);
1062     } else {
1063       if (StrCaseCmp(tok,s) == 0)
1064         return(True);
1065     }
1066   }
1067   return(False);
1068 }
1069
1070 /* this is used to prevent lots of mallocs of size 1 */
1071 static char *null_string = NULL;
1072
1073 /****************************************************************************
1074 set a string value, allocing the space for the string
1075 ****************************************************************************/
1076 static BOOL string_init(char **dest,const char *src)
1077 {
1078   size_t l;
1079   if (!src)     
1080     src = "";
1081
1082   l = strlen(src);
1083
1084   if (l == 0)
1085     {
1086       if (!null_string) {
1087         if((null_string = (char *)malloc(1)) == NULL) {
1088           DEBUG(0,("string_init: malloc fail for null_string.\n"));
1089           return False;
1090         }
1091         *null_string = 0;
1092       }
1093       *dest = null_string;
1094     }
1095   else
1096     {
1097       (*dest) = (char *)malloc(l+1);
1098       if ((*dest) == NULL) {
1099               DEBUG(0,("Out of memory in string_init\n"));
1100               return False;
1101       }
1102
1103       pstrcpy(*dest,src);
1104     }
1105   return(True);
1106 }
1107
1108 /****************************************************************************
1109 free a string value
1110 ****************************************************************************/
1111 void string_free(char **s)
1112 {
1113   if (!s || !(*s)) return;
1114   if (*s == null_string)
1115     *s = NULL;
1116   if (*s) free(*s);
1117   *s = NULL;
1118 }
1119
1120 /****************************************************************************
1121 set a string value, allocing the space for the string, and deallocating any 
1122 existing space
1123 ****************************************************************************/
1124 BOOL string_set(char **dest,const char *src)
1125 {
1126   string_free(dest);
1127
1128   return(string_init(dest,src));
1129 }
1130
1131
1132 /****************************************************************************
1133 substitute a string for a pattern in another string. Make sure there is 
1134 enough room!
1135
1136 This routine looks for pattern in s and replaces it with 
1137 insert. It may do multiple replacements.
1138
1139 any of " ; ' $ or ` in the insert string are replaced with _
1140 if len==0 then no length check is performed
1141 ****************************************************************************/
1142 void string_sub(char *s,const char *pattern,const char *insert, size_t len)
1143 {
1144         char *p;
1145         ssize_t ls,lp,li, i;
1146
1147         if (!insert || !pattern || !s) return;
1148
1149         ls = (ssize_t)strlen(s);
1150         lp = (ssize_t)strlen(pattern);
1151         li = (ssize_t)strlen(insert);
1152
1153         if (!*pattern) return;
1154         
1155         while (lp <= ls && (p = strstr(s,pattern))) {
1156                 if (len && (ls + (li-lp) >= len)) {
1157                         DEBUG(0,("ERROR: string overflow by %d in string_sub(%.50s, %d)\n", 
1158                                  (int)(ls + (li-lp) - len),
1159                                  pattern, (int)len));
1160                         break;
1161                 }
1162                 if (li != lp) {
1163                         memmove(p+li,p+lp,strlen(p+lp)+1);
1164                 }
1165                 for (i=0;i<li;i++) {
1166                         switch (insert[i]) {
1167                         case '`':
1168                         case '"':
1169                         case '\'':
1170                         case ';':
1171                         case '$':
1172                         case '%':
1173                         case '\r':
1174                         case '\n':
1175                                 p[i] = '_';
1176                                 break;
1177                         default:
1178                                 p[i] = insert[i];
1179                         }
1180                 }
1181                 s = p + li;
1182                 ls += (li-lp);
1183         }
1184 }
1185
1186 void fstring_sub(char *s,const char *pattern,const char *insert)
1187 {
1188         string_sub(s, pattern, insert, sizeof(fstring));
1189 }
1190
1191 void pstring_sub(char *s,const char *pattern,const char *insert)
1192 {
1193         string_sub(s, pattern, insert, sizeof(pstring));
1194 }
1195
1196 /****************************************************************************
1197 similar to string_sub() but allows for any character to be substituted. 
1198 Use with caution!
1199 if len==0 then no length check is performed
1200 ****************************************************************************/
1201 void all_string_sub(char *s,const char *pattern,const char *insert, size_t len)
1202 {
1203         char *p;
1204         ssize_t ls,lp,li;
1205
1206         if (!insert || !pattern || !s) return;
1207
1208         ls = (ssize_t)strlen(s);
1209         lp = (ssize_t)strlen(pattern);
1210         li = (ssize_t)strlen(insert);
1211
1212         if (!*pattern) return;
1213         
1214         while (lp <= ls && (p = strstr(s,pattern))) {
1215                 if (len && (ls + (li-lp) >= len)) {
1216                         DEBUG(0,("ERROR: string overflow by %d in all_string_sub(%.50s, %d)\n", 
1217                                  (int)(ls + (li-lp) - len),
1218                                  pattern, (int)len));
1219                         break;
1220                 }
1221                 if (li != lp) {
1222                         memmove(p+li,p+lp,strlen(p+lp)+1);
1223                 }
1224                 memcpy(p, insert, li);
1225                 s = p + li;
1226                 ls += (li-lp);
1227         }
1228 }
1229
1230 /****************************************************************************
1231  splits out the front and back at a separator.
1232 ****************************************************************************/
1233 void split_at_last_component(char *path, char *front, char sep, char *back)
1234 {
1235         char *p = strrchr(path, sep);
1236
1237         if (p != NULL)
1238         {
1239                 *p = 0;
1240         }
1241         if (front != NULL)
1242         {
1243                 pstrcpy(front, path);
1244         }
1245         if (p != NULL)
1246         {
1247                 if (back != NULL)
1248                 {
1249                         pstrcpy(back, p+1);
1250                 }
1251                 *p = '\\';
1252         }
1253         else
1254         {
1255                 if (back != NULL)
1256                 {
1257                         back[0] = 0;
1258                 }
1259         }
1260 }
1261
1262
1263 /****************************************************************************
1264 write an octal as a string
1265 ****************************************************************************/
1266 char *octal_string(int i)
1267 {
1268         static char ret[64];
1269         if (i == -1) {
1270                 return "-1";
1271         }
1272         slprintf(ret, sizeof(ret)-1, "0%o", i);
1273         return ret;
1274 }
1275
1276
1277 /****************************************************************************
1278 truncate a string at a specified length
1279 ****************************************************************************/
1280 char *string_truncate(char *s, int length)
1281 {
1282         if (s && strlen(s) > length) {
1283                 s[length] = 0;
1284         }
1285         return s;
1286 }