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