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