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