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