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