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