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