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