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