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