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