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