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