- Added LOG_LEVEL_DEANIMATE
[privoxy.git] / miscutil.c
1 /* vim:ts=3: */
2 const char miscutil_rcs[] = "$Id: miscutil.c,v 1.13 2001/06/29 13:32:14 oes Exp $";
3 /*********************************************************************
4  *
5  * File        :  $Source: /cvsroot/ijbswa/current/miscutil.c,v $
6  *
7  * Purpose     :  zalloc, hash_string, safe_strerror, strcmpic,
8  *                strncmpic, strsav, chomp, and MinGW32 strdup
9  *                functions. 
10  *                These are each too small to deserve their own file
11  *                but don't really fit in any other file.
12  *
13  * Copyright   :  Written by and Copyright (C) 2001 the SourceForge
14  *                IJBSWA team.  http://ijbswa.sourceforge.net
15  *
16  *                Based on the Internet Junkbuster originally written
17  *                by and Copyright (C) 1997 Anonymous Coders and 
18  *                Junkbusters Corporation.  http://www.junkbusters.com
19  *
20  *                This program is free software; you can redistribute it 
21  *                and/or modify it under the terms of the GNU General
22  *                Public License as published by the Free Software
23  *                Foundation; either version 2 of the License, or (at
24  *                your option) any later version.
25  *
26  *                This program is distributed in the hope that it will
27  *                be useful, but WITHOUT ANY WARRANTY; without even the
28  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
29  *                PARTICULAR PURPOSE.  See the GNU General Public
30  *                License for more details.
31  *
32  *                The GNU General Public License should be included with
33  *                this file.  If not, you can view it at
34  *                http://www.gnu.org/copyleft/gpl.html
35  *                or write to the Free Software Foundation, Inc., 59
36  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
37  *
38  * Revisions   :
39  *    $Log: miscutil.c,v $
40  *    Revision 1.13  2001/06/29 13:32:14  oes
41  *    Removed logentry from cancelled commit
42  *
43  *    Revision 1.12  2001/06/09 10:55:28  jongfoster
44  *    Changing BUFSIZ ==> BUFFER_SIZE
45  *
46  *    Revision 1.11  2001/06/07 23:09:19  jongfoster
47  *    Cosmetic indentation changes.
48  *
49  *    Revision 1.10  2001/06/07 14:51:38  joergs
50  *    make_path() no longer adds '/' if the dir already ends in '/'.
51  *
52  *    Revision 1.9  2001/06/07 14:43:17  swa
53  *    slight mistake in make_path, unix path style is /.
54  *
55  *    Revision 1.8  2001/06/05 22:32:01  jongfoster
56  *    New function make_path() to splice directory and file names together.
57  *
58  *    Revision 1.7  2001/06/03 19:12:30  oes
59  *    introduced bindup()
60  *
61  *    Revision 1.6  2001/06/01 18:14:49  jongfoster
62  *    Changing the calls to strerr() to check HAVE_STRERR (which is defined
63  *    in config.h if appropriate) rather than the NO_STRERR macro.
64  *
65  *    Revision 1.5  2001/06/01 10:31:51  oes
66  *    Added character class matching to trivimatch; renamed to simplematch
67  *
68  *    Revision 1.4  2001/05/31 17:32:31  oes
69  *
70  *     - Enhanced domain part globbing with infix and prefix asterisk
71  *       matching and optional unanchored operation
72  *
73  *    Revision 1.3  2001/05/29 23:10:09  oes
74  *
75  *
76  *     - Introduced chomp()
77  *     - Moved strsav() from showargs to miscutil
78  *
79  *    Revision 1.2  2001/05/29 09:50:24  jongfoster
80  *    Unified blocklist/imagelist/permissionslist.
81  *    File format is still under discussion, but the internal changes
82  *    are (mostly) done.
83  *
84  *    Also modified interceptor behaviour:
85  *    - We now intercept all URLs beginning with one of the following
86  *      prefixes (and *only* these prefixes):
87  *        * http://i.j.b/
88  *        * http://ijbswa.sf.net/config/
89  *        * http://ijbswa.sourceforge.net/config/
90  *    - New interceptors "home page" - go to http://i.j.b/ to see it.
91  *    - Internal changes so that intercepted and fast redirect pages
92  *      are not replaced with an image.
93  *    - Interceptors now have the option to send a binary page direct
94  *      to the client. (i.e. ijb-send-banner uses this)
95  *    - Implemented show-url-info interceptor.  (Which is why I needed
96  *      the above interceptors changes - a typical URL is
97  *      "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
98  *      The previous mechanism would not have intercepted that, and
99  *      if it had been intercepted then it then it would have replaced
100  *      it with an image.)
101  *
102  *    Revision 1.1.1.1  2001/05/15 13:59:00  oes
103  *    Initial import of version 2.9.3 source tree
104  *
105  *
106  *********************************************************************/
107 \f
108
109 #include "config.h"
110
111 #include <stdio.h>
112 #include <stdlib.h>
113 #include <string.h>
114 #include <malloc.h>
115 #include <ctype.h>
116
117 /*
118  * FIXME: Only need project.h for BUFFER_SIZE.  It would be nice
119  * to remove this dependency.
120  */
121 #include "project.h"
122 #include "miscutil.h"
123 #include "errlog.h"
124
125 const char miscutil_h_rcs[] = MISCUTIL_H_VERSION;
126
127 /* Fix a problem with Solaris.  There should be no effect on other
128  * platforms.
129  * Solaris's isspace() is a macro which uses it's argument directly
130  * as an array index.  Therefore we need to make sure that high-bit
131  * characters generate +ve values, and ideally we also want to make
132  * the argument match the declared parameter type of "int".
133  */
134 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
135 #define ijb_isspace(__X) isspace((int)(unsigned char)(__X))   
136
137 /*********************************************************************
138  *
139  * Function    :  zalloc
140  *
141  * Description :  Malloc some memory and set it to '\0'.
142  *                The way calloc() ought to be -acjc
143  *
144  * Parameters  :
145  *          1  :  size = Size of memory chunk to return.
146  *
147  * Returns     :  Pointer to newly malloc'd memory chunk.
148  *
149  *********************************************************************/
150 void *zalloc(int size)
151 {
152    void * ret;
153
154    if ((ret = (void *)malloc(size)) != NULL)
155    {
156       memset(ret, 0, size);
157    }
158
159    return(ret);
160 }
161
162
163 /*********************************************************************
164  *
165  * Function    :  hash_string
166  *
167  * Description :  Take a string and compute a (hopefuly) unique numeric
168  *                integer value.  This has several uses, but being able
169  *                to "switch" a string the one of my favorites.
170  *
171  * Parameters  :
172  *          1  :  s : string to be hashed.
173  *
174  * Returns     :  an unsigned long variable with the hashed value.
175  *
176  *********************************************************************/
177 unsigned long hash_string( const char* s )
178 {
179    unsigned long h = 0ul; 
180
181    for ( ; *s; ++s )
182    {
183       h = 5 * h + *s;
184    }
185
186    return (h);
187
188 }
189
190
191 #ifdef __MINGW32__
192 /*********************************************************************
193  *
194  * Function    :  strdup
195  *
196  * Description :  For some reason (which is beyond me), gcc and WIN32
197  *                don't like strdup.  When a "free" is executed on a
198  *                strdup'd ptr, it can at times freez up!  So I just
199  *                replaced it and problem was solved.
200  *
201  * Parameters  :
202  *          1  :  s = string to duplicate
203  *
204  * Returns     :  Pointer to newly malloc'ed copy of the string.
205  *
206  *********************************************************************/
207 char *strdup( const char *s )
208 {
209    char * result = (char *)malloc( strlen(s)+1 );
210
211    if (result != NULL)
212    {
213       strcpy( result, s );
214    }
215
216    return( result );
217 }
218
219 #endif /* def __MINGW32__ */
220
221
222
223 /*********************************************************************
224  *
225  * Function    :  safe_strerror
226  *
227  * Description :  Variant of the library routine strerror() which will
228  *                work on systems without the library routine, and
229  *                which should never return NULL.
230  *
231  * Parameters  :
232  *          1  :  err = the `errno' of the last operation.
233  *
234  * Returns     :  An "English" string of the last `errno'.  Allocated
235  *                with strdup(), so caller frees.  May be NULL if the
236  *                system is out of memory.
237  *
238  *********************************************************************/
239 char *safe_strerror(int err)
240 {
241    char *s = NULL;
242    char buf[BUFFER_SIZE];
243
244
245 #ifdef HAVE_STRERROR
246    s = strerror(err);
247 #endif /* HAVE_STRERROR */
248
249    if (s == NULL)
250    {
251       sprintf(buf, "(errno = %d)", err);
252       s = buf;
253    }
254
255    return(strdup(s));
256
257 }
258
259
260 /*********************************************************************
261  *
262  * Function    :  strcmpic
263  *
264  * Description :  Case insensitive string comparison
265  *
266  * Parameters  :
267  *          1  :  s1 = string 1 to compare
268  *          2  :  s2 = string 2 to compare
269  *
270  * Returns     :  0 if s1==s2, Negative if s1<s2, Positive if s1>s2
271  *
272  *********************************************************************/
273 int strcmpic(const char *s1, const char *s2)
274 {
275    while (*s1 && *s2)
276    {
277       if ( ( *s1 != *s2 ) && ( ijb_tolower(*s1) != ijb_tolower(*s2) ) )
278       {
279          break;
280       }
281       s1++, s2++;
282    }
283    return(ijb_tolower(*s1) - ijb_tolower(*s2));
284
285 }
286
287
288 /*********************************************************************
289  *
290  * Function    :  strncmpic
291  *
292  * Description :  Case insensitive string comparison (upto n characters)
293  *
294  * Parameters  :
295  *          1  :  s1 = string 1 to compare
296  *          2  :  s2 = string 2 to compare
297  *          3  :  n = maximum characters to compare
298  *
299  * Returns     :  0 if s1==s2, Negative if s1<s2, Positive if s1>s2
300  *
301  *********************************************************************/
302 int strncmpic(const char *s1, const char *s2, size_t n)
303 {
304    if (n <= 0) return(0);
305
306    while (*s1 && *s2)
307    {
308       if ( ( *s1 != *s2 ) && ( ijb_tolower(*s1) != ijb_tolower(*s2) ) )
309       {
310          break;
311       }
312
313       if (--n <= 0) break;
314
315       s1++, s2++;
316    }
317    return(ijb_tolower(*s1) - ijb_tolower(*s2));
318
319 }
320
321
322 /*********************************************************************
323  *
324  * Function    :  chomp
325  *
326  * Description :  In-situ-eliminate all leading and trailing whitespace
327  *                from a string.
328  *
329  * Parameters  :
330  *          1  :  s : string to be chomped.
331  *
332  * Returns     :  chomped string
333  *
334  *********************************************************************/
335 char *chomp(char *string)
336 {
337    char *p, *q, *r;
338
339    /* 
340     * strip trailing whitespace
341     */
342    p = string + strlen(string);
343    while (p > string && ijb_isspace(*(p-1)))
344    {
345       p--;
346    }
347    *p = '\0';
348
349    /* 
350     * find end of leading whitespace 
351     */
352    q = r = string;
353    while (*q && ijb_isspace(*q))
354    {
355       q++;
356    }
357
358    /*
359     * if there was any, move the rest forwards
360     */
361    if (q != string)
362    {
363       while (q <= p)
364       {
365          *r++ = *q++;
366       }
367    }
368
369    return(string);
370
371 }
372
373 /*********************************************************************
374  *
375  * Function    :  strsav
376  *
377  * Description :  Reallocate "old" and append text to it.  This makes
378  *                it easier to append to malloc'd strings.
379  *
380  * Parameters  :
381  *          1  :  old = Old text that is to be extended.  Will be
382  *                free()d by this routine.
383  *          2  :  text_to_append = Text to be appended to old.
384  *
385  * Returns     :  Pointer to newly malloc'ed appended string.
386  *                If there is no text to append, return old.  Caller
387  *                must free().
388  *
389  *********************************************************************/
390 char *strsav(char *old, const char *text_to_append)
391 {
392    int old_len, new_len;
393    char *p;
394
395    if (( text_to_append == NULL) || (*text_to_append == '\0'))
396    {
397       return(old);
398    }
399
400    if (NULL != old)
401    {
402       old_len = strlen(old);
403    }
404    else
405    {
406       old_len = 0;
407    }
408
409    new_len = old_len + strlen(text_to_append) + 1;
410
411    if (old)
412    {
413       if ((p = realloc(old, new_len)) == NULL)
414       {
415          log_error(LOG_LEVEL_FATAL, "realloc(%d) bytes failed!", new_len);
416          /* Never get here - LOG_LEVEL_FATAL causes program exit */
417       }
418    }
419    else
420    {
421       if ((p = (char *)malloc(new_len)) == NULL)
422       {
423          log_error(LOG_LEVEL_FATAL, "malloc(%d) bytes failed!", new_len);
424          /* Never get here - LOG_LEVEL_FATAL causes program exit */
425       }
426    }
427
428    strcpy(p + old_len, text_to_append);
429    return(p);
430
431 }
432
433
434 /*********************************************************************
435  *
436  * Function    :  simplematch
437  *
438  * Description :  String matching, with a (greedy) '*' wildcard that
439  *                stands for zero or more arbitrary characters and
440  *                character classes in [], which take both enumerations
441  *                and ranges.
442  *
443  * Parameters  :
444  *          1  :  pattern = pattern for matching
445  *          2  :  text    = text to be matched
446  *
447  * Returns     :  0 if match, else nonzero
448  *
449  *********************************************************************/
450 int simplematch(char *pattern, char *text)
451 {
452    char *fallback; 
453    char *pat = pattern;
454    char *txt = text;
455    int wildcard = 0;
456   
457    char lastchar = 'a';
458    unsigned i;
459    unsigned char charmap[32];
460   
461   
462    while (*txt)
463    {
464
465       /* EOF pattern but !EOF text? */
466       if (*pat == '\0')
467       {
468          return 1;
469       }
470
471       /* '*' in the pattern?  */
472       if (*pat == '*') 
473       {
474      
475          /* The pattern ends afterwards? Speed up the return. */
476          if (*++pat == '\0')
477          {
478             return 0;
479          }
480      
481          /* Else, set wildcard mode and remember position after '*' */
482          wildcard = 1;
483          fallback = pat;
484       }
485
486       /* Character range specification? */
487       if (*pat == '[')
488       {
489          memset(charmap, '\0', sizeof(charmap));
490
491          while (*++pat != ']')
492          {
493             if (!*pat)
494             { 
495                return 1;
496             }
497             else if (*pat == '-')
498             {
499                if ((*++pat == ']') || *pat == '\0')
500                {
501                   return(1);
502                }
503                for(i = lastchar; i <= *pat; i++)
504                {
505                   charmap[i / 8] |= (1 << (i % 8));
506                } 
507             }
508             else
509             {
510                charmap[*pat / 8] |= (1 << (*pat % 8));
511                lastchar = *pat;
512             }
513          }
514       } /* -END- if Character range specification */
515
516
517       /* Compare: Char match, or char range match*/
518       if ((*pat == *txt)  
519       || ((*pat == ']') && (charmap[*txt / 8] & (1 << (*txt % 8)))) )
520       {
521          /* Sucess, go ahead */
522          pat++;
523       }
524       else
525       {
526          /* In wildcard mode, just try again after failiure */
527          if(wildcard)
528          {
529             pat = fallback;
530          }
531
532          /* Else, bad luck */
533          else
534          {
535             return 1;
536          }
537       }
538       txt++;
539    }
540
541    /* Cut off extra '*'s */
542    if(*pat == '*')  pat++;
543
544    /* If this is the pattern's end, fine! */
545    return(*pat);
546
547 }
548
549
550 /*********************************************************************
551  *
552  * Function    :  bindup
553  *
554  * Description :  Duplicate the first n characters of a string that may
555  *                contain '\0' characters.
556  *
557  * Parameters  :
558  *          1  :  string = string to be duplicated
559  *          2  :  n = number of bytes to duplicate
560  *
561  * Returns     :  pointer to copy, or NULL if failiure
562  *
563  *********************************************************************/
564 char *bindup(const char *string, int n)
565 {
566    char *dup;
567
568    if (NULL == (dup = (char *)malloc(n)))
569    {
570       return NULL;
571    }
572    else
573    {
574      memcpy(dup, string, n);
575    }
576
577    return dup;
578
579 }
580
581
582 /*********************************************************************
583  *
584  * Function    :  make_path
585  *
586  * Description :  Takes a directory name and a file name, returns 
587  *                the complete path.  Handles windows/unix differences.
588  *                If the file name is already an absolute path, or if
589  *                the directory name is NULL or empty, it returns 
590  *                the filename. 
591  *
592  * Parameters  :
593  *          1  :  dir: Name of directory or NULL for none.
594  *          2  :  file: Name of file.  Should not be NULL or empty.
595  *
596  * Returns     :  "dir/file" (Or on windows, "dir\file").
597  *                It allocates the string on the heap.  Caller frees.
598  *                Returns NULL in error (i.e. NULL file or out of
599  *                memory) 
600  *
601  *********************************************************************/
602 char * make_path(const char * dir, const char * file)
603 {
604 #ifdef AMIGA
605    char path[512];
606
607    if(dir)
608    {
609       strncpy(path,dir,512);
610       path[511]=0;
611    } else {
612       path[0]=0;
613    }
614    if(AddPart(path,file,512))
615    {
616       return strdup(path);
617    } else {
618       return NULL;
619    }
620 #else /* ndef AMIGA */
621
622    if ((file == NULL) || (*file == '\0'))
623    {
624       return NULL; /* Error */
625    }
626
627    if ((dir == NULL) || (*dir == '\0') /* No directory specified */
628 #ifdef _WIN32
629       || (*file == '\\') || (file[1] == ':') /* Absolute path (DOS) */
630 #else /* ifndef _WIN32 */
631       || (*file == '/') /* Absolute path (U*ix) */
632 #endif /* ifndef _WIN32 */
633       )
634    {
635       return strdup(file);
636    }
637    else
638    {
639       char * path = malloc(strlen(dir) + strlen(file) + 2);
640       strcpy(path, dir);
641 #ifdef _WIN32
642       strcat(path, "\\");
643 #else /* ifndef _WIN32 */
644       if(path[strlen(path)-1] != '/') strcat(path, "/");
645 #endif /* ifndef _WIN32 */
646       strcat(path, file);
647
648       return path;
649    }
650 #endif /* ndef AMIGA */
651 }
652
653
654 /*
655   Local Variables:
656   tab-width: 3
657   end:
658 */