3eb707ca15da9d39590c24c8587b17a3bdd06482
[privoxy.git] / miscutil.c
1 const char miscutil_rcs[] = "$Id: miscutil.c,v 1.57 2008/03/24 15:29:51 fabiankeil Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/miscutil.c,v $
5  *
6  * Purpose     :  zalloc, hash_string, safe_strerror, strcmpic,
7  *                strncmpic, 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-2007
13  *                the SourceForge Privoxy team. http://www.privoxy.org/
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  *                The timegm replacement function was taken from GnuPG,
20  *                Copyright (C) 2004 Free Software Foundation, Inc.
21  *
22  *                The snprintf replacement function is written by
23  *                Mark Martinec who also holds the copyright. It can be
24  *                used under the terms of the GPL or the terms of the
25  *                "Frontier Artistic License".
26  *
27  *                This program is free software; you can redistribute it 
28  *                and/or modify it under the terms of the GNU General
29  *                Public License as published by the Free Software
30  *                Foundation; either version 2 of the License, or (at
31  *                your option) any later version.
32  *
33  *                This program is distributed in the hope that it will
34  *                be useful, but WITHOUT ANY WARRANTY; without even the
35  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
36  *                PARTICULAR PURPOSE.  See the GNU General Public
37  *                License for more details.
38  *
39  *                The GNU General Public License should be included with
40  *                this file.  If not, you can view it at
41  *                http://www.gnu.org/copyleft/gpl.html
42  *                or write to the Free Software Foundation, Inc., 59
43  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
44  *
45  * Revisions   :
46  *    $Log: miscutil.c,v $
47  *    Revision 1.57  2008/03/24 15:29:51  fabiankeil
48  *    Pet gcc43.
49  *
50  *    Revision 1.56  2007/12/01 12:59:05  fabiankeil
51  *    Some sanity checks for pick_from_range().
52  *
53  *    Revision 1.55  2007/11/03 17:34:49  fabiankeil
54  *    Log the "weak randomization factor" warning only
55  *    once for mingw32 and provide some more details.
56  *
57  *    Revision 1.54  2007/09/19 20:28:37  fabiankeil
58  *    If privoxy_strlcpy() is called with a "buffer" size
59  *    of 0, don't touch whatever destination points to.
60  *
61  *    Revision 1.53  2007/09/09 18:20:20  fabiankeil
62  *    Turn privoxy_strlcpy() into a function and try to work with
63  *    b0rked snprintf() implementations too. Reported by icmp30.
64  *
65  *    Revision 1.52  2007/08/19 12:32:34  fabiankeil
66  *    Fix a conversion warning.
67  *
68  *    Revision 1.51  2007/06/17 16:12:22  fabiankeil
69  *    #ifdef _WIN32 the last commit. According to David Shaw,
70  *    one of the gnupg developers, the changes are mingw32-specific.
71  *
72  *    Revision 1.50  2007/06/10 14:59:59  fabiankeil
73  *    Change replacement timegm() to better match our style, plug a small
74  *    but guaranteed memory leak and fix "time zone breathing" on mingw32.
75  *
76  *    Revision 1.49  2007/05/11 11:48:15  fabiankeil
77  *    - Delete strsav() which was replaced
78  *      by string_append() years ago.
79  *    - Add a strlcat() look-alike.
80  *    - Use strlcat() and strlcpy() in those parts
81  *      of the code that are run on unixes.
82  *
83  *    Revision 1.48  2007/04/09 17:48:51  fabiankeil
84  *    Check for HAVE_SNPRINTF instead of __OS2__
85  *    before including the portable snprintf() code.
86  *
87  *    Revision 1.47  2007/03/17 11:52:15  fabiankeil
88  *    - Use snprintf instead of sprintf.
89  *    - Mention copyright for the replacement
90  *      functions in the copyright header.
91  *
92  *    Revision 1.46  2007/01/18 15:03:20  fabiankeil
93  *    Don't include replacement timegm() if
94  *    putenv() or tzset() isn't available.
95  *
96  *    Revision 1.45  2006/12/26 17:31:41  fabiankeil
97  *    Mutex protect rand() if POSIX threading
98  *    is used, warn the user if that's not possible
99  *    and stop using it on _WIN32 where it could
100  *    cause crashes.
101  *
102  *    Revision 1.44  2006/11/07 12:46:43  fabiankeil
103  *    Silence compiler warning on NetBSD 3.1.
104  *
105  *    Revision 1.43  2006/09/23 13:26:38  roro
106  *    Replace TABs by spaces in source code.
107  *
108  *    Revision 1.42  2006/09/09 14:01:45  fabiankeil
109  *    Integrated Oliver Yeoh's domain pattern fix
110  *    to make sure *x matches xx. Closes Patch 1217393
111  *    and Bug 1170767.
112  *
113  *    Revision 1.41  2006/08/18 16:03:17  david__schmidt
114  *    Tweak for OS/2 build happiness.
115  *
116  *    Revision 1.40  2006/08/17 17:15:10  fabiankeil
117  *    - Back to timegm() using GnuPG's replacement if necessary.
118  *      Using mktime() and localtime() could add a on hour offset if
119  *      the randomize factor was big enough to lead to a summer/wintertime
120  *      switch.
121  *
122  *    - Removed now-useless Privoxy 3.0.3 compatibility glue.
123  *
124  *    - Moved randomization code into pick_from_range().
125  *
126  *    - Changed parse_header_time definition.
127  *      time_t isn't guaranteed to be signed and
128  *      if it isn't, -1 isn't available as error code.
129  *      Changed some variable types in client_if_modified_since()
130  *      because of the same reason.
131  *
132  *    Revision 1.39  2006/07/18 14:48:46  david__schmidt
133  *    Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
134  *    with what was really the latest development (the v_3_0_branch branch)
135  *
136  *    Revision 1.37.2.4  2003/12/01 14:45:14  oes
137  *    Fixed two more problems with wildcarding in simplematch()
138  *
139  *    Revision 1.37.2.3  2003/11/20 11:39:24  oes
140  *    Bugfix: The "?" wildcard for domain names had never been implemented. Ooops\!
141  *
142  *    Revision 1.37.2.2  2002/11/12 14:28:18  oes
143  *    Proper backtracking in simplematch; fixes bug #632888
144  *
145  *    Revision 1.37.2.1  2002/09/25 12:58:51  oes
146  *    Made strcmpic and strncmpic safe against NULL arguments
147  *    (which are now treated as empty strings).
148  *
149  *    Revision 1.37  2002/04/26 18:29:43  jongfoster
150  *    Fixing this Visual C++ warning:
151  *    miscutil.c(710) : warning C4090: '=' : different 'const' qualifiers
152  *
153  *    Revision 1.36  2002/04/26 12:55:38  oes
154  *    New function string_toupper
155  *
156  *    Revision 1.35  2002/03/26 22:29:55  swa
157  *    we have a new homepage!
158  *
159  *    Revision 1.34  2002/03/24 13:25:43  swa
160  *    name change related issues
161  *
162  *    Revision 1.33  2002/03/07 03:46:53  oes
163  *    Fixed compiler warnings etc
164  *
165  *    Revision 1.32  2002/03/06 23:02:57  jongfoster
166  *    Removing tabs
167  *
168  *    Revision 1.31  2002/03/05 04:52:42  oes
169  *    Deleted non-errlog debugging code
170  *
171  *    Revision 1.30  2002/03/04 18:27:42  oes
172  *    - Deleted deletePidFile
173  *    - Made write_pid_file use the --pidfile option value
174  *      (or no PID file, if the option was absent)
175  *    - Played styleguide police
176  *
177  *    Revision 1.29  2002/03/04 02:08:02  david__schmidt
178  *    Enable web editing of actions file on OS/2 (it had been broken all this time!)
179  *
180  *    Revision 1.28  2002/03/03 09:18:03  joergs
181  *    Made jumbjuster work on AmigaOS again.
182  *
183  *    Revision 1.27  2002/01/21 00:52:32  jongfoster
184  *    Adding string_join()
185  *
186  *    Revision 1.26  2001/12/30 14:07:32  steudten
187  *    - Add signal handling (unix)
188  *    - Add SIGHUP handler (unix)
189  *    - Add creation of pidfile (unix)
190  *    - Add action 'top' in rc file (RH)
191  *    - Add entry 'SIGNALS' to manpage
192  *    - Add exit message to logfile (unix)
193  *
194  *    Revision 1.25  2001/11/13 00:16:38  jongfoster
195  *    Replacing references to malloc.h with the standard stdlib.h
196  *    (See ANSI or K&R 2nd Ed)
197  *
198  *    Revision 1.24  2001/11/05 21:41:43  steudten
199  *    Add changes to be a real daemon just for unix os.
200  *    (change cwd to /, detach from controlling tty, set
201  *    process group and session leader to the own process.
202  *    Add DBG() Macro.
203  *    Add some fatal-error log message for failed malloc().
204  *    Add '-d' if compiled with 'configure --with-debug' to
205  *    enable debug output.
206  *
207  *    Revision 1.23  2001/10/29 03:48:10  david__schmidt
208  *    OS/2 native needed a snprintf() routine.  Added one to miscutil, brackedted
209  *    by and __OS2__ ifdef.
210  *
211  *    Revision 1.22  2001/10/26 17:39:38  oes
212  *    Moved ijb_isspace and ijb_tolower to project.h
213  *
214  *    Revision 1.21  2001/10/23 21:27:50  jongfoster
215  *    Standardising error codes in string_append
216  *    make_path() no longer adds '\\' if the dir already ends in '\\' (this
217  *    is just copying a UNIX-specific fix to the Windows-specific part)
218  *
219  *    Revision 1.20  2001/10/22 15:33:56  david__schmidt
220  *    Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
221  *    filters.c.  Added a FIXME in front of the offending code.  I'll gladly
222  *    put in a better/more robust fix for all parties if one is presented...
223  *    It seems that just returning 200 instead of 404 would pretty much fix
224  *    it for everyone, but I don't know all the history of the problem.
225  *
226  *    Revision 1.19  2001/10/14 22:02:57  jongfoster
227  *    New function string_append() which is like strsav(), but running
228  *    out of memory isn't automatically FATAL.
229  *
230  *    Revision 1.18  2001/09/20 13:33:43  steudten
231  *
232  *    change long to int as return value in hash_string(). Remember the wraparound
233  *    for int = long = sizeof(4) - thats maybe not what we want.
234  *
235  *    Revision 1.17  2001/09/13 20:51:29  jongfoster
236  *    Fixing potential problems with characters >=128 in simplematch()
237  *    This was also a compiler warning.
238  *
239  *    Revision 1.16  2001/09/10 10:56:59  oes
240  *    Silenced compiler warnings
241  *
242  *    Revision 1.15  2001/07/13 14:02:24  oes
243  *    Removed vim-settings
244  *
245  *    Revision 1.14  2001/06/29 21:45:41  oes
246  *    Indentation, CRLF->LF, Tab-> Space
247  *
248  *    Revision 1.13  2001/06/29 13:32:14  oes
249  *    Removed logentry from cancelled commit
250  *
251  *    Revision 1.12  2001/06/09 10:55:28  jongfoster
252  *    Changing BUFSIZ ==> BUFFER_SIZE
253  *
254  *    Revision 1.11  2001/06/07 23:09:19  jongfoster
255  *    Cosmetic indentation changes.
256  *
257  *    Revision 1.10  2001/06/07 14:51:38  joergs
258  *    make_path() no longer adds '/' if the dir already ends in '/'.
259  *
260  *    Revision 1.9  2001/06/07 14:43:17  swa
261  *    slight mistake in make_path, unix path style is /.
262  *
263  *    Revision 1.8  2001/06/05 22:32:01  jongfoster
264  *    New function make_path() to splice directory and file names together.
265  *
266  *    Revision 1.7  2001/06/03 19:12:30  oes
267  *    introduced bindup()
268  *
269  *    Revision 1.6  2001/06/01 18:14:49  jongfoster
270  *    Changing the calls to strerr() to check HAVE_STRERR (which is defined
271  *    in config.h if appropriate) rather than the NO_STRERR macro.
272  *
273  *    Revision 1.5  2001/06/01 10:31:51  oes
274  *    Added character class matching to trivimatch; renamed to simplematch
275  *
276  *    Revision 1.4  2001/05/31 17:32:31  oes
277  *
278  *     - Enhanced domain part globbing with infix and prefix asterisk
279  *       matching and optional unanchored operation
280  *
281  *    Revision 1.3  2001/05/29 23:10:09  oes
282  *
283  *
284  *     - Introduced chomp()
285  *     - Moved strsav() from showargs to miscutil
286  *
287  *    Revision 1.2  2001/05/29 09:50:24  jongfoster
288  *    Unified blocklist/imagelist/permissionslist.
289  *    File format is still under discussion, but the internal changes
290  *    are (mostly) done.
291  *
292  *    Also modified interceptor behaviour:
293  *    - We now intercept all URLs beginning with one of the following
294  *      prefixes (and *only* these prefixes):
295  *        * http://i.j.b/
296  *        * http://ijbswa.sf.net/config/
297  *        * http://ijbswa.sourceforge.net/config/
298  *    - New interceptors "home page" - go to http://i.j.b/ to see it.
299  *    - Internal changes so that intercepted and fast redirect pages
300  *      are not replaced with an image.
301  *    - Interceptors now have the option to send a binary page direct
302  *      to the client. (i.e. ijb-send-banner uses this)
303  *    - Implemented show-url-info interceptor.  (Which is why I needed
304  *      the above interceptors changes - a typical URL is
305  *      "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
306  *      The previous mechanism would not have intercepted that, and
307  *      if it had been intercepted then it then it would have replaced
308  *      it with an image.)
309  *
310  *    Revision 1.1.1.1  2001/05/15 13:59:00  oes
311  *    Initial import of version 2.9.3 source tree
312  *
313  *
314  *********************************************************************/
315 \f
316
317 #include "config.h"
318
319 #include <stdio.h>
320 #include <sys/types.h>
321 #include <stdlib.h>
322 #if !defined(_WIN32) && !defined(__OS2__)
323 #include <unistd.h>
324 #endif /* #if !defined(_WIN32) && !defined(__OS2__) */
325 #include <string.h>
326 #include <ctype.h>
327 #include <assert.h>
328
329 #if !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV)
330 #include <time.h>
331 #endif /* !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV) */
332
333 #include "project.h"
334 #include "miscutil.h"
335 #include "errlog.h"
336 #include "jcc.h"
337
338 const char miscutil_h_rcs[] = MISCUTIL_H_VERSION;
339
340 /*********************************************************************
341  *
342  * Function    :  zalloc
343  *
344  * Description :  Malloc some memory and set it to '\0'.
345  *                The way calloc() ought to be -acjc
346  *
347  * Parameters  :
348  *          1  :  size = Size of memory chunk to return.
349  *
350  * Returns     :  Pointer to newly malloc'd memory chunk.
351  *
352  *********************************************************************/
353 void *zalloc(size_t size)
354 {
355    void * ret;
356
357    if ((ret = (void *)malloc(size)) != NULL)
358    {
359       memset(ret, 0, size);
360    }
361
362    return(ret);
363
364 }
365
366
367 #if defined(unix)
368 /*********************************************************************
369  *
370  * Function    :  write_pid_file 
371  *
372  * Description :  Writes a pid file with the pid of the main process 
373  *
374  * Parameters  :  None
375  *
376  * Returns     :  N/A 
377  *
378  *********************************************************************/
379 void write_pid_file(void)
380 {
381    FILE   *fp;
382    
383    /*
384     * If no --pidfile option was given,
385     * we can live without one.
386     */
387    if (pidfile == NULL) return;
388
389    if ((fp = fopen(pidfile, "w")) == NULL)
390    {
391       log_error(LOG_LEVEL_INFO, "can't open pidfile '%s': %E", pidfile);
392    }
393    else
394    {
395       fprintf(fp, "%u\n", (unsigned int) getpid());
396       fclose (fp);
397    }
398    return;
399
400 }
401 #endif /* def unix */
402
403
404 /*********************************************************************
405  *
406  * Function    :  hash_string
407  *
408  * Description :  Take a string and compute a (hopefuly) unique numeric
409  *                integer value.  This has several uses, but being able
410  *                to "switch" a string the one of my favorites.
411  *
412  * Parameters  :
413  *          1  :  s : string to be hashed.
414  *
415  * Returns     :  an unsigned long variable with the hashed value.
416  *
417  *********************************************************************/
418 unsigned int hash_string( const char* s )
419 {
420    unsigned int h = 0; 
421
422    for ( ; *s; ++s )
423    {
424       h = 5 * h + (unsigned int)*s;
425    }
426
427    return (h);
428
429 }
430
431
432 #ifdef __MINGW32__
433 /*********************************************************************
434  *
435  * Function    :  strdup
436  *
437  * Description :  For some reason (which is beyond me), gcc and WIN32
438  *                don't like strdup.  When a "free" is executed on a
439  *                strdup'd ptr, it can at times freez up!  So I just
440  *                replaced it and problem was solved.
441  *
442  * Parameters  :
443  *          1  :  s = string to duplicate
444  *
445  * Returns     :  Pointer to newly malloc'ed copy of the string.
446  *
447  *********************************************************************/
448 char *strdup( const char *s )
449 {
450    char * result = (char *)malloc( strlen(s)+1 );
451
452    if (result != NULL)
453    {
454       strcpy( result, s );
455    }
456
457    return( result );
458 }
459
460 #endif /* def __MINGW32__ */
461
462
463
464 /*********************************************************************
465  *
466  * Function    :  safe_strerror
467  *
468  * Description :  Variant of the library routine strerror() which will
469  *                work on systems without the library routine, and
470  *                which should never return NULL.
471  *
472  * Parameters  :
473  *          1  :  err = the `errno' of the last operation.
474  *
475  * Returns     :  An "English" string of the last `errno'.  Allocated
476  *                with strdup(), so caller frees.  May be NULL if the
477  *                system is out of memory.
478  *
479  *********************************************************************/
480 char *safe_strerror(int err)
481 {
482    char *s = NULL;
483    char buf[BUFFER_SIZE];
484
485
486 #ifdef HAVE_STRERROR
487    s = strerror(err);
488 #endif /* HAVE_STRERROR */
489
490    if (s == NULL)
491    {
492       snprintf(buf, sizeof(buf), "(errno = %d)", err);
493       s = buf;
494    }
495
496    return(strdup(s));
497
498 }
499
500
501 /*********************************************************************
502  *
503  * Function    :  strcmpic
504  *
505  * Description :  Case insensitive string comparison
506  *
507  * Parameters  :
508  *          1  :  s1 = string 1 to compare
509  *          2  :  s2 = string 2 to compare
510  *
511  * Returns     :  0 if s1==s2, Negative if s1<s2, Positive if s1>s2
512  *
513  *********************************************************************/
514 int strcmpic(const char *s1, const char *s2)
515 {
516    if (!s1) s1 = "";
517    if (!s2) s2 = "";
518
519    while (*s1 && *s2)
520    {
521       if ( ( *s1 != *s2 ) && ( ijb_tolower(*s1) != ijb_tolower(*s2) ) )
522       {
523          break;
524       }
525       s1++, s2++;
526    }
527    return(ijb_tolower(*s1) - ijb_tolower(*s2));
528
529 }
530
531
532 /*********************************************************************
533  *
534  * Function    :  strncmpic
535  *
536  * Description :  Case insensitive string comparison (upto n characters)
537  *
538  * Parameters  :
539  *          1  :  s1 = string 1 to compare
540  *          2  :  s2 = string 2 to compare
541  *          3  :  n = maximum characters to compare
542  *
543  * Returns     :  0 if s1==s2, Negative if s1<s2, Positive if s1>s2
544  *
545  *********************************************************************/
546 int strncmpic(const char *s1, const char *s2, size_t n)
547 {
548    if (n <= 0) return(0);
549    if (!s1) s1 = "";
550    if (!s2) s2 = "";
551    
552    while (*s1 && *s2)
553    {
554       if ( ( *s1 != *s2 ) && ( ijb_tolower(*s1) != ijb_tolower(*s2) ) )
555       {
556          break;
557       }
558
559       if (--n <= 0) break;
560
561       s1++, s2++;
562    }
563    return(ijb_tolower(*s1) - ijb_tolower(*s2));
564
565 }
566
567
568 /*********************************************************************
569  *
570  * Function    :  chomp
571  *
572  * Description :  In-situ-eliminate all leading and trailing whitespace
573  *                from a string.
574  *
575  * Parameters  :
576  *          1  :  s : string to be chomped.
577  *
578  * Returns     :  chomped string
579  *
580  *********************************************************************/
581 char *chomp(char *string)
582 {
583    char *p, *q, *r;
584
585    /* 
586     * strip trailing whitespace
587     */
588    p = string + strlen(string);
589    while (p > string && ijb_isspace(*(p-1)))
590    {
591       p--;
592    }
593    *p = '\0';
594
595    /* 
596     * find end of leading whitespace 
597     */
598    q = r = string;
599    while (*q && ijb_isspace(*q))
600    {
601       q++;
602    }
603
604    /*
605     * if there was any, move the rest forwards
606     */
607    if (q != string)
608    {
609       while (q <= p)
610       {
611          *r++ = *q++;
612       }
613    }
614
615    return(string);
616
617 }
618
619
620 /*********************************************************************
621  *
622  * Function    :  string_append
623  *
624  * Description :  Reallocate target_string and append text to it.  
625  *                This makes it easier to append to malloc'd strings.
626  *                This is similar to the (removed) strsav(), but
627  *                running out of memory isn't catastrophic.
628  *
629  *                Programming style:
630  *
631  *                The following style provides sufficient error
632  *                checking for this routine, with minimal clutter
633  *                in the source code.  It is recommended if you
634  *                have many calls to this function:
635  *
636  *                char * s = strdup(...); // don't check for error
637  *                string_append(&s, ...);  // don't check for error
638  *                string_append(&s, ...);  // don't check for error
639  *                string_append(&s, ...);  // don't check for error
640  *                if (NULL == s) { ... handle error ... }
641  *
642  *                OR, equivalently:
643  *
644  *                char * s = strdup(...); // don't check for error
645  *                string_append(&s, ...);  // don't check for error
646  *                string_append(&s, ...);  // don't check for error
647  *                if (string_append(&s, ...)) {... handle error ...}
648  *
649  * Parameters  :
650  *          1  :  target_string = Pointer to old text that is to be
651  *                extended.  *target_string will be free()d by this
652  *                routine.  target_string must be non-NULL.
653  *                If *target_string is NULL, this routine will
654  *                do nothing and return with an error - this allows
655  *                you to make many calls to this routine and only
656  *                check for errors after the last one.
657  *          2  :  text_to_append = Text to be appended to old.
658  *                Must not be NULL.
659  *
660  * Returns     :  JB_ERR_OK on success, and sets *target_string
661  *                   to newly malloc'ed appended string.  Caller
662  *                   must free(*target_string).
663  *                JB_ERR_MEMORY on out-of-memory.  (And free()s
664  *                   *target_string and sets it to NULL).
665  *                JB_ERR_MEMORY if *target_string is NULL.
666  *
667  *********************************************************************/
668 jb_err string_append(char **target_string, const char *text_to_append)
669 {
670    size_t old_len;
671    char *new_string;
672    size_t new_size;
673
674    assert(target_string);
675    assert(text_to_append);
676
677    if (*target_string == NULL)
678    {
679       return JB_ERR_MEMORY;
680    }
681
682    if (*text_to_append == '\0')
683    {
684       return JB_ERR_OK;
685    }
686
687    old_len = strlen(*target_string);
688
689    new_size = strlen(text_to_append) + old_len + 1;
690
691    if (NULL == (new_string = realloc(*target_string, new_size)))
692    {
693       free(*target_string);
694
695       *target_string = NULL;
696       return JB_ERR_MEMORY;
697    }
698
699    strlcpy(new_string + old_len, text_to_append, new_size - old_len);
700
701    *target_string = new_string;
702    return JB_ERR_OK;
703 }
704
705
706 /*********************************************************************
707  *
708  * Function    :  string_join
709  *
710  * Description :  Join two strings together.  Frees BOTH the original
711  *                strings.  If either or both input strings are NULL,
712  *                fails as if it had run out of memory.
713  *
714  *                For comparison, string_append requires that the
715  *                second string is non-NULL, and doesn't free it.
716  *
717  *                Rationale: Too often, we want to do
718  *                string_append(s, html_encode(s2)).  That assert()s
719  *                if s2 is NULL or if html_encode() runs out of memory.
720  *                It also leaks memory.  Proper checking is cumbersome.
721  *                The solution: string_join(s, html_encode(s2)) is safe,
722  *                and will free the memory allocated by html_encode().
723  *
724  * Parameters  :
725  *          1  :  target_string = Pointer to old text that is to be
726  *                extended.  *target_string will be free()d by this
727  *                routine.  target_string must be non-NULL.
728  *          2  :  text_to_append = Text to be appended to old.
729  *
730  * Returns     :  JB_ERR_OK on success, and sets *target_string
731  *                   to newly malloc'ed appended string.  Caller
732  *                   must free(*target_string).
733  *                JB_ERR_MEMORY on out-of-memory, or if
734  *                   *target_string or text_to_append is NULL.  (In
735  *                   this case, frees *target_string and text_to_append,
736  *                   sets *target_string to NULL).
737  *
738  *********************************************************************/
739 jb_err string_join(char **target_string, char *text_to_append)
740 {
741    jb_err err;
742
743    assert(target_string);
744
745    if (text_to_append == NULL)
746    {
747       freez(*target_string);
748       return JB_ERR_MEMORY;
749    }
750
751    err = string_append(target_string, text_to_append);
752
753    free(text_to_append);
754
755    return err;
756 }
757
758
759 /*********************************************************************
760  *
761  * Function    :  string_toupper
762  *
763  * Description :  Produce a copy of string with all convertible
764  *                characters converted to uppercase.
765  *
766  * Parameters  :
767  *          1  :  string = string to convert
768  *
769  * Returns     :  Uppercase copy of string if possible, 
770  *                NULL on out-of-memory or if string was NULL.
771  *
772  *********************************************************************/
773 char *string_toupper(const char *string)
774 {
775    char *result, *p;
776    const char *q;
777
778    if (!string || ((result = (char *) zalloc(strlen(string) + 1)) == NULL))
779    {
780       return NULL;
781    }
782    
783    q = string;
784    p = result;
785
786    while (*q != '\0')
787    {
788       *p++ = (char)toupper((int) *q++);
789    }
790
791    return result;
792
793 }
794
795
796 /*********************************************************************
797  *
798  * Function    :  bindup
799  *
800  * Description :  Duplicate the first n characters of a string that may
801  *                contain '\0' characters.
802  *
803  * Parameters  :
804  *          1  :  string = string to be duplicated
805  *          2  :  len = number of bytes to duplicate
806  *
807  * Returns     :  pointer to copy, or NULL if failiure
808  *
809  *********************************************************************/
810 char *bindup(const char *string, size_t len)
811 {
812    char *duplicate;
813
814    if (NULL == (duplicate = (char *)malloc(len)))
815    {
816       return NULL;
817    }
818    else
819    {
820      memcpy(duplicate, string, len);
821    }
822
823    return duplicate;
824
825 }
826
827
828 /*********************************************************************
829  *
830  * Function    :  make_path
831  *
832  * Description :  Takes a directory name and a file name, returns 
833  *                the complete path.  Handles windows/unix differences.
834  *                If the file name is already an absolute path, or if
835  *                the directory name is NULL or empty, it returns 
836  *                the filename. 
837  *
838  * Parameters  :
839  *          1  :  dir: Name of directory or NULL for none.
840  *          2  :  file: Name of file.  Should not be NULL or empty.
841  *
842  * Returns     :  "dir/file" (Or on windows, "dir\file").
843  *                It allocates the string on the heap.  Caller frees.
844  *                Returns NULL in error (i.e. NULL file or out of
845  *                memory) 
846  *
847  *********************************************************************/
848 char * make_path(const char * dir, const char * file)
849 {
850 #ifdef AMIGA
851    char path[512];
852
853    if(dir)
854    {
855       if(dir[0] == '.')
856       {
857          if(dir[1] == '/')
858          {
859             strncpy(path,dir+2,512);
860          }
861          else
862          {
863             strncpy(path,dir+1,512);
864          }
865       }
866       else
867       {
868          strncpy(path,dir,512);
869       }
870       path[511]=0;
871    }
872    else
873    {
874       path[0]=0;
875    }
876    if(AddPart(path,file,512))
877    {
878       return strdup(path);
879    }
880    else
881    {
882       return NULL;
883    }
884 #else /* ndef AMIGA */
885
886    if ((file == NULL) || (*file == '\0'))
887    {
888       return NULL; /* Error */
889    }
890
891    if ((dir == NULL) || (*dir == '\0') /* No directory specified */
892 #if defined(_WIN32) || defined(__OS2__)
893       || (*file == '\\') || (file[1] == ':') /* Absolute path (DOS) */
894 #else /* ifndef _WIN32 || __OS2__ */
895       || (*file == '/') /* Absolute path (U*ix) */
896 #endif /* ifndef _WIN32 || __OS2__  */
897       )
898    {
899       return strdup(file);
900    }
901    else
902    {
903       char * path;
904       size_t path_size = strlen(dir) + strlen(file) + 2; /* +2 for trailing (back)slash and \0 */
905
906 #if defined(unix)
907       if ( *dir != '/' && basedir && *basedir )
908       {
909          /*
910           * Relative path, so start with the base directory.
911           */
912          path_size += strlen(basedir) + 1; /* +1 for the slash */
913          path = malloc(path_size);
914          if (!path ) log_error(LOG_LEVEL_FATAL, "malloc failed!");
915          strlcpy(path, basedir, path_size);
916          strlcat(path, "/", path_size);
917          strlcat(path, dir, path_size);
918       }
919       else
920 #endif /* defined unix */
921       {
922          path = malloc(path_size);
923          if (!path ) log_error(LOG_LEVEL_FATAL, "malloc failed!");
924          strlcpy(path, dir, path_size);
925       }
926
927 #if defined(_WIN32) || defined(__OS2__)
928       if(path[strlen(path)-1] != '\\')
929       {
930          strlcat(path, "\\", path_size);
931       }
932 #else /* ifndef _WIN32 || __OS2__ */
933       if(path[strlen(path)-1] != '/')
934       {
935          strlcat(path, "/", path_size);
936       }
937 #endif /* ifndef _WIN32 || __OS2__ */
938       strlcat(path, file, path_size);
939
940       return path;
941    }
942 #endif /* ndef AMIGA */
943 }
944
945
946 /*********************************************************************
947  *
948  * Function    :  pick_from_range
949  *
950  * Description :  Pick a positive number out of a given range.
951  *                Should only be used if randomness would be nice,
952  *                but isn't really necessary.
953  *
954  * Parameters  :
955  *          1  :  range: Highest possible number to pick.
956  *
957  * Returns     :  Picked number. 
958  *
959  *********************************************************************/
960 long int pick_from_range(long int range)
961 {
962    long int number;
963
964    assert(range != 0);
965    assert(range > 0);
966
967    if (range <= 0) return 0;
968
969 #ifdef HAVE_RANDOM
970    number = random() % range + 1; 
971 #elif defined(FEATURE_PTHREAD)
972    pthread_mutex_lock(&rand_mutex);
973    number = rand() % (long int)(range + 1);
974    pthread_mutex_unlock(&rand_mutex);
975 #else
976 #ifdef _WIN32
977    /*
978     * On Windows and mingw32 srand() has to be called in every
979     * rand()-using thread, but can cause crashes if it's not
980     * mutex protected.
981     *
982     * Currently we don't have mutexes for mingw32, and for
983     * our purpose this cludge is probably preferable to crashes.
984     *
985     * The warning is shown once on startup from jcc.c.
986     */
987    number = (range + GetCurrentThreadId() % range) / 2;
988 #else
989    /*
990     * XXX: Which platforms reach this and are there
991     * better options than just using rand() and hoping
992     * that it's safe?
993     */
994    log_error(LOG_LEVEL_INFO, "No thread-safe PRNG available? Header time randomization might cause "
995       "crashes, predictable results or even combine these fine options.");
996    number = rand() % (long int)(range + 1);
997 #endif /* def _WIN32 */ 
998
999 #endif /* (def HAVE_RANDOM) */
1000
1001    return number;
1002 }
1003
1004
1005 #ifdef USE_PRIVOXY_STRLCPY
1006 /*********************************************************************
1007  *
1008  * Function    :  privoxy_strlcpy
1009  *
1010  * Description :  strlcpy(3) look-alike for those without decent libc.
1011  *
1012  * Parameters  :
1013  *          1  :  destination: buffer to copy into.
1014  *          2  :  source: String to copy.
1015  *          3  :  size: Size of destination buffer.
1016  *
1017  * Returns     :  The length of the string that privoxy_strlcpy() tried to create.
1018  *
1019  *********************************************************************/
1020 size_t privoxy_strlcpy(char *destination, const char *source, const size_t size)
1021 {
1022    if (0 < size)
1023    {
1024       snprintf(destination, size, "%s", source);
1025       /*
1026        * Platforms that lack strlcpy() also tend to have
1027        * a broken snprintf implementation that doesn't
1028        * guarantee nul termination.
1029        *
1030        * XXX: the configure script should detect and reject those.
1031        */
1032       destination[size-1] = '\0';
1033    }
1034    return strlen(source);
1035 }
1036 #endif /* def USE_PRIVOXY_STRLCPY */
1037
1038
1039 #ifndef HAVE_STRLCAT
1040 /*********************************************************************
1041  *
1042  * Function    :  privoxy_strlcat
1043  *
1044  * Description :  strlcat(3) look-alike for those without decent libc.
1045  *
1046  * Parameters  :
1047  *          1  :  destination: C string.
1048  *          2  :  source: String to copy.
1049  *          3  :  size: Size of destination buffer.
1050  *
1051  * Returns     :  The length of the string that privoxy_strlcat() tried to create.
1052  *
1053  *********************************************************************/
1054 size_t privoxy_strlcat(char *destination, const char *source, const size_t size)
1055 {
1056    const size_t old_length = strlen(destination);
1057    return old_length + strlcpy(destination + old_length, source, size - old_length);
1058 }
1059 #endif /* ndef HAVE_STRLCAT */
1060
1061
1062 #if !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV)
1063 /*********************************************************************
1064  *
1065  * Function    :  timegm
1066  *
1067  * Description :  libc replacement function for the inverse of gmtime().
1068  *                Copyright (C) 2004 Free Software Foundation, Inc.
1069  *
1070  *                Code originally copied from GnuPG, modifications done
1071  *                for Privoxy: style changed, #ifdefs for _WIN32 added
1072  *                to have it work on mingw32.
1073  *
1074  *                XXX: It's very unlikely to happen, but if the malloc()
1075  *                call fails the time zone will be permanently set to UTC.
1076  *
1077  * Parameters  :
1078  *          1  :  tm: Broken-down time struct.
1079  *
1080  * Returns     :  tm converted into time_t seconds. 
1081  *
1082  *********************************************************************/
1083 time_t timegm(struct tm *tm)
1084 {
1085    time_t answer;
1086    char *zone;
1087
1088    zone = getenv("TZ");
1089    putenv("TZ=UTC");
1090    tzset();
1091    answer = mktime(tm);
1092    if (zone)
1093    {
1094       char *old_zone;
1095
1096       old_zone = malloc(3 + strlen(zone) + 1);
1097       if (old_zone)
1098       {
1099          strcpy(old_zone, "TZ=");
1100          strcat(old_zone, zone);
1101          putenv(old_zone);
1102 #ifdef _WIN32
1103          free(old_zone);
1104 #endif /* def _WIN32 */
1105       }
1106    }
1107    else
1108    {
1109 #ifdef HAVE_UNSETENV
1110       unsetenv("TZ");
1111 #elif defined(_WIN32)
1112       putenv("TZ=");
1113 #else
1114       putenv("TZ");
1115 #endif
1116    }
1117    tzset();
1118
1119    return answer;
1120 }
1121 #endif /* !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV) */
1122
1123
1124 #ifndef HAVE_SNPRINTF
1125 /*
1126  * What follows is a portable snprintf routine, written by Mark Martinec.
1127  * See: http://www.ijs.si/software/snprintf/
1128
1129                                   snprintf.c
1130                    - a portable implementation of snprintf,
1131        including vsnprintf.c, asnprintf, vasnprintf, asprintf, vasprintf
1132                                        
1133    snprintf is a routine to convert numeric and string arguments to
1134    formatted strings. It is similar to sprintf(3) provided in a system's
1135    C library, yet it requires an additional argument - the buffer size -
1136    and it guarantees never to store anything beyond the given buffer,
1137    regardless of the format or arguments to be formatted. Some newer
1138    operating systems do provide snprintf in their C library, but many do
1139    not or do provide an inadequate (slow or idiosyncratic) version, which
1140    calls for a portable implementation of this routine.
1141
1142 Author
1143
1144    Mark Martinec <mark.martinec@ijs.si>, April 1999, June 2000
1145    Copyright Â© 1999, Mark Martinec
1146
1147  */
1148
1149 #define PORTABLE_SNPRINTF_VERSION_MAJOR 2
1150 #define PORTABLE_SNPRINTF_VERSION_MINOR 2
1151
1152 #if defined(NEED_ASPRINTF) || defined(NEED_ASNPRINTF) || defined(NEED_VASPRINTF) || defined(NEED_VASNPRINTF)
1153 # if defined(NEED_SNPRINTF_ONLY)
1154 # undef NEED_SNPRINTF_ONLY
1155 # endif
1156 # if !defined(PREFER_PORTABLE_SNPRINTF)
1157 # define PREFER_PORTABLE_SNPRINTF
1158 # endif
1159 #endif
1160
1161 #if defined(SOLARIS_BUG_COMPATIBLE) && !defined(SOLARIS_COMPATIBLE)
1162 #define SOLARIS_COMPATIBLE
1163 #endif
1164
1165 #if defined(HPUX_BUG_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
1166 #define HPUX_COMPATIBLE
1167 #endif
1168
1169 #if defined(DIGITAL_UNIX_BUG_COMPATIBLE) && !defined(DIGITAL_UNIX_COMPATIBLE)
1170 #define DIGITAL_UNIX_COMPATIBLE
1171 #endif
1172
1173 #if defined(PERL_BUG_COMPATIBLE) && !defined(PERL_COMPATIBLE)
1174 #define PERL_COMPATIBLE
1175 #endif
1176
1177 #if defined(LINUX_BUG_COMPATIBLE) && !defined(LINUX_COMPATIBLE)
1178 #define LINUX_COMPATIBLE
1179 #endif
1180
1181 #include <sys/types.h>
1182 #include <string.h>
1183 #include <stdlib.h>
1184 #include <stdio.h>
1185 #include <stdarg.h>
1186 #include <assert.h>
1187 #include <errno.h>
1188
1189 #ifdef isdigit
1190 #undef isdigit
1191 #endif
1192 #define isdigit(c) ((c) >= '0' && (c) <= '9')
1193
1194 /* For copying strings longer or equal to 'breakeven_point'
1195  * it is more efficient to call memcpy() than to do it inline.
1196  * The value depends mostly on the processor architecture,
1197  * but also on the compiler and its optimization capabilities.
1198  * The value is not critical, some small value greater than zero
1199  * will be just fine if you don't care to squeeze every drop
1200  * of performance out of the code.
1201  *
1202  * Small values favor memcpy, large values favor inline code.
1203  */
1204 #if defined(__alpha__) || defined(__alpha)
1205 #  define breakeven_point   2    /* AXP (DEC Alpha)     - gcc or cc or egcs */
1206 #endif
1207 #if defined(__i386__)  || defined(__i386)
1208 #  define breakeven_point  12    /* Intel Pentium/Linux - gcc 2.96 */
1209 #endif
1210 #if defined(__hppa)
1211 #  define breakeven_point  10    /* HP-PA               - gcc */
1212 #endif
1213 #if defined(__sparc__) || defined(__sparc)
1214 #  define breakeven_point  33    /* Sun Sparc 5         - gcc 2.8.1 */
1215 #endif
1216
1217 /* some other values of possible interest: */
1218 /* #define breakeven_point  8 */ /* VAX 4000          - vaxc */
1219 /* #define breakeven_point 19 */ /* VAX 4000          - gcc 2.7.0 */
1220
1221 #ifndef breakeven_point
1222 #  define breakeven_point   6    /* some reasonable one-size-fits-all value */
1223 #endif
1224
1225 #define fast_memcpy(d,s,n) \
1226   { register size_t nn = (size_t)(n); \
1227     if (nn >= breakeven_point) memcpy((d), (s), nn); \
1228     else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
1229       register char *dd; register const char *ss; \
1230       for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } }
1231
1232 #define fast_memset(d,c,n) \
1233   { register size_t nn = (size_t)(n); \
1234     if (nn >= breakeven_point) memset((d), (int)(c), nn); \
1235     else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
1236       register char *dd; register const int cc=(int)(c); \
1237       for (dd=(d); nn>0; nn--) *dd++ = cc; } }
1238
1239 /* prototypes */
1240
1241 #if defined(NEED_ASPRINTF)
1242 int asprintf   (char **ptr, const char *fmt, /*args*/ ...);
1243 #endif
1244 #if defined(NEED_VASPRINTF)
1245 int vasprintf  (char **ptr, const char *fmt, va_list ap);
1246 #endif
1247 #if defined(NEED_ASNPRINTF)
1248 int asnprintf  (char **ptr, size_t str_m, const char *fmt, /*args*/ ...);
1249 #endif
1250 #if defined(NEED_VASNPRINTF)
1251 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap);
1252 #endif
1253
1254 #if defined(HAVE_SNPRINTF)
1255 /* declare our portable snprintf  routine under name portable_snprintf  */
1256 /* declare our portable vsnprintf routine under name portable_vsnprintf */
1257 #else
1258 /* declare our portable routines under names snprintf and vsnprintf */
1259 #define portable_snprintf snprintf
1260 #if !defined(NEED_SNPRINTF_ONLY)
1261 #define portable_vsnprintf vsnprintf
1262 #endif
1263 #endif
1264
1265 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1266 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...);
1267 #if !defined(NEED_SNPRINTF_ONLY)
1268 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap);
1269 #endif
1270 #endif
1271
1272 /* declarations */
1273
1274 static char credits[] = "\n\
1275 @(#)snprintf.c, v2.2: Mark Martinec, <mark.martinec@ijs.si>\n\
1276 @(#)snprintf.c, v2.2: Copyright 1999, Mark Martinec. Frontier Artistic License applies.\n\
1277 @(#)snprintf.c, v2.2: http://www.ijs.si/software/snprintf/\n";
1278
1279 #if defined(NEED_ASPRINTF)
1280 int asprintf(char **ptr, const char *fmt, /*args*/ ...) {
1281   va_list ap;
1282   size_t str_m;
1283   int str_l;
1284
1285   *ptr = NULL;
1286   va_start(ap, fmt);                            /* measure the required size */
1287   str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
1288   va_end(ap);
1289   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
1290   *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
1291   if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1292   else {
1293     int str_l2;
1294     va_start(ap, fmt);
1295     str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1296     va_end(ap);
1297     assert(str_l2 == str_l);
1298   }
1299   return str_l;
1300 }
1301 #endif
1302
1303 #if defined(NEED_VASPRINTF)
1304 int vasprintf(char **ptr, const char *fmt, va_list ap) {
1305   size_t str_m;
1306   int str_l;
1307
1308   *ptr = NULL;
1309   { va_list ap2;
1310     va_copy(ap2, ap);  /* don't consume the original ap, we'll need it again */
1311     str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1312     va_end(ap2);
1313   }
1314   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
1315   *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
1316   if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1317   else {
1318     int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1319     assert(str_l2 == str_l);
1320   }
1321   return str_l;
1322 }
1323 #endif
1324
1325 #if defined(NEED_ASNPRINTF)
1326 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...) {
1327   va_list ap;
1328   int str_l;
1329
1330   *ptr = NULL;
1331   va_start(ap, fmt);                            /* measure the required size */
1332   str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
1333   va_end(ap);
1334   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
1335   if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1;      /* truncate */
1336   /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1337   if (str_m == 0) {  /* not interested in resulting string, just return size */
1338   } else {
1339     *ptr = (char *) malloc(str_m);
1340     if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1341     else {
1342       int str_l2;
1343       va_start(ap, fmt);
1344       str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1345       va_end(ap);
1346       assert(str_l2 == str_l);
1347     }
1348   }
1349   return str_l;
1350 }
1351 #endif
1352
1353 #if defined(NEED_VASNPRINTF)
1354 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap) {
1355   int str_l;
1356
1357   *ptr = NULL;
1358   { va_list ap2;
1359     va_copy(ap2, ap);  /* don't consume the original ap, we'll need it again */
1360     str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1361     va_end(ap2);
1362   }
1363   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
1364   if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1;      /* truncate */
1365   /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1366   if (str_m == 0) {  /* not interested in resulting string, just return size */
1367   } else {
1368     *ptr = (char *) malloc(str_m);
1369     if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1370     else {
1371       int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1372       assert(str_l2 == str_l);
1373     }
1374   }
1375   return str_l;
1376 }
1377 #endif
1378
1379 /*
1380  * If the system does have snprintf and the portable routine is not
1381  * specifically required, this module produces no code for snprintf/vsnprintf.
1382  */
1383 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1384
1385 #if !defined(NEED_SNPRINTF_ONLY)
1386 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1387   va_list ap;
1388   int str_l;
1389
1390   va_start(ap, fmt);
1391   str_l = portable_vsnprintf(str, str_m, fmt, ap);
1392   va_end(ap);
1393   return str_l;
1394 }
1395 #endif
1396
1397 #if defined(NEED_SNPRINTF_ONLY)
1398 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1399 #else
1400 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) {
1401 #endif
1402
1403 #if defined(NEED_SNPRINTF_ONLY)
1404   va_list ap;
1405 #endif
1406   size_t str_l = 0;
1407   const char *p = fmt;
1408
1409 /* In contrast with POSIX, the ISO C99 now says
1410  * that str can be NULL and str_m can be 0.
1411  * This is more useful than the old:  if (str_m < 1) return -1; */
1412
1413 #if defined(NEED_SNPRINTF_ONLY)
1414   va_start(ap, fmt);
1415 #endif
1416   if (!p) p = "";
1417   while (*p) {
1418     if (*p != '%') {
1419    /* if (str_l < str_m) str[str_l++] = *p++;    -- this would be sufficient */
1420    /* but the following code achieves better performance for cases
1421     * where format string is long and contains few conversions */
1422       const char *q = strchr(p+1,'%');
1423       size_t n = !q ? strlen(p) : (q-p);
1424       if (str_l < str_m) {
1425         size_t avail = str_m-str_l;
1426         fast_memcpy(str+str_l, p, (n>avail?avail:n));
1427       }
1428       p += n; str_l += n;
1429     } else {
1430       const char *starting_p;
1431       size_t min_field_width = 0, precision = 0;
1432       int zero_padding = 0, precision_specified = 0, justify_left = 0;
1433       int alternate_form = 0, force_sign = 0;
1434       int space_for_positive = 1; /* If both the ' ' and '+' flags appear,
1435                                      the ' ' flag should be ignored. */
1436       char length_modifier = '\0';            /* allowed values: \0, h, l, L */
1437       char tmp[32];/* temporary buffer for simple numeric->string conversion */
1438
1439       const char *str_arg;      /* string address in case of string argument */
1440       size_t str_arg_l;         /* natural field width of arg without padding
1441                                    and sign */
1442       unsigned char uchar_arg;
1443         /* unsigned char argument value - only defined for c conversion.
1444            N.B. standard explicitly states the char argument for
1445            the c conversion is unsigned */
1446
1447       size_t number_of_zeros_to_pad = 0;
1448         /* number of zeros to be inserted for numeric conversions
1449            as required by the precision or minimal field width */
1450
1451       size_t zero_padding_insertion_ind = 0;
1452         /* index into tmp where zero padding is to be inserted */
1453
1454       char fmt_spec = '\0';
1455         /* current conversion specifier character */
1456
1457       str_arg = credits;/* just to make compiler happy (defined but not used)*/
1458       str_arg = NULL;
1459       starting_p = p; p++;  /* skip '%' */
1460    /* parse flags */
1461       while (*p == '0' || *p == '-' || *p == '+' ||
1462              *p == ' ' || *p == '#' || *p == '\'') {
1463         switch (*p) {
1464         case '0': zero_padding = 1; break;
1465         case '-': justify_left = 1; break;
1466         case '+': force_sign = 1; space_for_positive = 0; break;
1467         case ' ': force_sign = 1;
1468      /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */
1469 #ifdef PERL_COMPATIBLE
1470      /* ... but in Perl the last of ' ' and '+' applies */
1471                   space_for_positive = 1;
1472 #endif
1473                   break;
1474         case '#': alternate_form = 1; break;
1475         case '\'': break;
1476         }
1477         p++;
1478       }
1479    /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
1480
1481    /* parse field width */
1482       if (*p == '*') {
1483         int j;
1484         p++; j = va_arg(ap, int);
1485         if (j >= 0) min_field_width = j;
1486         else { min_field_width = -j; justify_left = 1; }
1487       } else if (isdigit((int)(*p))) {
1488         /* size_t could be wider than unsigned int;
1489            make sure we treat argument like common implementations do */
1490         unsigned int uj = *p++ - '0';
1491         while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1492         min_field_width = uj;
1493       }
1494    /* parse precision */
1495       if (*p == '.') {
1496         p++; precision_specified = 1;
1497         if (*p == '*') {
1498           int j = va_arg(ap, int);
1499           p++;
1500           if (j >= 0) precision = j;
1501           else {
1502             precision_specified = 0; precision = 0;
1503          /* NOTE:
1504           *   Solaris 2.6 man page claims that in this case the precision
1505           *   should be set to 0.  Digital Unix 4.0, HPUX 10 and BSD man page
1506           *   claim that this case should be treated as unspecified precision,
1507           *   which is what we do here.
1508           */
1509           }
1510         } else if (isdigit((int)(*p))) {
1511           /* size_t could be wider than unsigned int;
1512              make sure we treat argument like common implementations do */
1513           unsigned int uj = *p++ - '0';
1514           while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1515           precision = uj;
1516         }
1517       }
1518    /* parse 'h', 'l' and 'll' length modifiers */
1519       if (*p == 'h' || *p == 'l') {
1520         length_modifier = *p; p++;
1521         if (length_modifier == 'l' && *p == 'l') {   /* double l = long long */
1522 #ifdef SNPRINTF_LONGLONG_SUPPORT
1523           length_modifier = '2';                  /* double l encoded as '2' */
1524 #else
1525           length_modifier = 'l';                 /* treat it as a single 'l' */
1526 #endif
1527           p++;
1528         }
1529       }
1530       fmt_spec = *p;
1531    /* common synonyms: */
1532       switch (fmt_spec) {
1533       case 'i': fmt_spec = 'd'; break;
1534       case 'D': fmt_spec = 'd'; length_modifier = 'l'; break;
1535       case 'U': fmt_spec = 'u'; length_modifier = 'l'; break;
1536       case 'O': fmt_spec = 'o'; length_modifier = 'l'; break;
1537       default: break;
1538       }
1539    /* get parameter value, do initial processing */
1540       switch (fmt_spec) {
1541       case '%': /* % behaves similar to 's' regarding flags and field widths */
1542       case 'c': /* c behaves similar to 's' regarding flags and field widths */
1543       case 's':
1544         length_modifier = '\0';          /* wint_t and wchar_t not supported */
1545      /* the result of zero padding flag with non-numeric conversion specifier*/
1546      /* is undefined. Solaris and HPUX 10 does zero padding in this case,    */
1547      /* Digital Unix and Linux does not. */
1548 #if !defined(SOLARIS_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
1549         zero_padding = 0;    /* turn zero padding off for string conversions */
1550 #endif
1551         str_arg_l = 1;
1552         switch (fmt_spec) {
1553         case '%':
1554           str_arg = p; break;
1555         case 'c': {
1556           int j = va_arg(ap, int);
1557           uchar_arg = (unsigned char) j;   /* standard demands unsigned char */
1558           str_arg = (const char *) &uchar_arg;
1559           break;
1560         }
1561         case 's':
1562           str_arg = va_arg(ap, const char *);
1563           if (!str_arg) str_arg_l = 0;
1564        /* make sure not to address string beyond the specified precision !!! */
1565           else if (!precision_specified) str_arg_l = strlen(str_arg);
1566        /* truncate string if necessary as requested by precision */
1567           else if (precision == 0) str_arg_l = 0;
1568           else {
1569        /* memchr on HP does not like n > 2^31  !!! */
1570             const char *q = memchr(str_arg, '\0',
1571                              precision <= 0x7fffffff ? precision : 0x7fffffff);
1572             str_arg_l = !q ? precision : (q-str_arg);
1573           }
1574           break;
1575         default: break;
1576         }
1577         break;
1578       case 'd': case 'u': case 'o': case 'x': case 'X': case 'p': {
1579         /* NOTE: the u, o, x, X and p conversion specifiers imply
1580                  the value is unsigned;  d implies a signed value */
1581
1582         int arg_sign = 0;
1583           /* 0 if numeric argument is zero (or if pointer is NULL for 'p'),
1584             +1 if greater than zero (or nonzero for unsigned arguments),
1585             -1 if negative (unsigned argument is never negative) */
1586
1587         int int_arg = 0;  unsigned int uint_arg = 0;
1588           /* only defined for length modifier h, or for no length modifiers */
1589
1590         long int long_arg = 0;  unsigned long int ulong_arg = 0;
1591           /* only defined for length modifier l */
1592
1593         void *ptr_arg = NULL;
1594           /* pointer argument value -only defined for p conversion */
1595
1596 #ifdef SNPRINTF_LONGLONG_SUPPORT
1597         long long int long_long_arg = 0;
1598         unsigned long long int ulong_long_arg = 0;
1599           /* only defined for length modifier ll */
1600 #endif
1601         if (fmt_spec == 'p') {
1602         /* HPUX 10: An l, h, ll or L before any other conversion character
1603          *   (other than d, i, u, o, x, or X) is ignored.
1604          * Digital Unix:
1605          *   not specified, but seems to behave as HPUX does.
1606          * Solaris: If an h, l, or L appears before any other conversion
1607          *   specifier (other than d, i, u, o, x, or X), the behavior
1608          *   is undefined. (Actually %hp converts only 16-bits of address
1609          *   and %llp treats address as 64-bit data which is incompatible
1610          *   with (void *) argument on a 32-bit system).
1611          */
1612 #ifdef SOLARIS_COMPATIBLE
1613 #  ifdef SOLARIS_BUG_COMPATIBLE
1614           /* keep length modifiers even if it represents 'll' */
1615 #  else
1616           if (length_modifier == '2') length_modifier = '\0';
1617 #  endif
1618 #else
1619           length_modifier = '\0';
1620 #endif
1621           ptr_arg = va_arg(ap, void *);
1622           if (ptr_arg != NULL) arg_sign = 1;
1623         } else if (fmt_spec == 'd') {  /* signed */
1624           switch (length_modifier) {
1625           case '\0':
1626           case 'h':
1627          /* It is non-portable to specify a second argument of char or short
1628           * to va_arg, because arguments seen by the called function
1629           * are not char or short.  C converts char and short arguments
1630           * to int before passing them to a function.
1631           */
1632             int_arg = va_arg(ap, int);
1633             if      (int_arg > 0) arg_sign =  1;
1634             else if (int_arg < 0) arg_sign = -1;
1635             break;
1636           case 'l':
1637             long_arg = va_arg(ap, long int);
1638             if      (long_arg > 0) arg_sign =  1;
1639             else if (long_arg < 0) arg_sign = -1;
1640             break;
1641 #ifdef SNPRINTF_LONGLONG_SUPPORT
1642           case '2':
1643             long_long_arg = va_arg(ap, long long int);
1644             if      (long_long_arg > 0) arg_sign =  1;
1645             else if (long_long_arg < 0) arg_sign = -1;
1646             break;
1647 #endif
1648           }
1649         } else {  /* unsigned */
1650           switch (length_modifier) {
1651           case '\0':
1652           case 'h':
1653             uint_arg = va_arg(ap, unsigned int);
1654             if (uint_arg) arg_sign = 1;
1655             break;
1656           case 'l':
1657             ulong_arg = va_arg(ap, unsigned long int);
1658             if (ulong_arg) arg_sign = 1;
1659             break;
1660 #ifdef SNPRINTF_LONGLONG_SUPPORT
1661           case '2':
1662             ulong_long_arg = va_arg(ap, unsigned long long int);
1663             if (ulong_long_arg) arg_sign = 1;
1664             break;
1665 #endif
1666           }
1667         }
1668         str_arg = tmp; str_arg_l = 0;
1669      /* NOTE:
1670       *   For d, i, u, o, x, and X conversions, if precision is specified,
1671       *   the '0' flag should be ignored. This is so with Solaris 2.6,
1672       *   Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl.
1673       */
1674 #ifndef PERL_COMPATIBLE
1675         if (precision_specified) zero_padding = 0;
1676 #endif
1677         if (fmt_spec == 'd') {
1678           if (force_sign && arg_sign >= 0)
1679             tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1680          /* leave negative numbers for sprintf to handle,
1681             to avoid handling tricky cases like (short int)(-32768) */
1682 #ifdef LINUX_COMPATIBLE
1683         } else if (fmt_spec == 'p' && force_sign && arg_sign > 0) {
1684           tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1685 #endif
1686         } else if (alternate_form) {
1687           if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X') )
1688             { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = fmt_spec; }
1689          /* alternate form should have no effect for p conversion, but ... */
1690 #ifdef HPUX_COMPATIBLE
1691           else if (fmt_spec == 'p'
1692          /* HPUX 10: for an alternate form of p conversion,
1693           *          a nonzero result is prefixed by 0x. */
1694 #ifndef HPUX_BUG_COMPATIBLE
1695          /* Actually it uses 0x prefix even for a zero value. */
1696                    && arg_sign != 0
1697 #endif
1698                   ) { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = 'x'; }
1699 #endif
1700         }
1701         zero_padding_insertion_ind = str_arg_l;
1702         if (!precision_specified) precision = 1;   /* default precision is 1 */
1703         if (precision == 0 && arg_sign == 0
1704 #if defined(HPUX_BUG_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1705             && fmt_spec != 'p'
1706          /* HPUX 10 man page claims: With conversion character p the result of
1707           * converting a zero value with a precision of zero is a null string.
1708           * Actually HP returns all zeroes, and Linux returns "(nil)". */
1709 #endif
1710         ) {
1711          /* converted to null string */
1712          /* When zero value is formatted with an explicit precision 0,
1713             the resulting formatted string is empty (d, i, u, o, x, X, p).   */
1714         } else {
1715           char f[5]; int f_l = 0;
1716           f[f_l++] = '%';    /* construct a simple format string for sprintf */
1717           if (!length_modifier) { }
1718           else if (length_modifier=='2') { f[f_l++] = 'l'; f[f_l++] = 'l'; }
1719           else f[f_l++] = length_modifier;
1720           f[f_l++] = fmt_spec; f[f_l++] = '\0';
1721           if (fmt_spec == 'p') str_arg_l += sprintf(tmp+str_arg_l, f, ptr_arg);
1722           else if (fmt_spec == 'd') {  /* signed */
1723             switch (length_modifier) {
1724             case '\0':
1725             case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, int_arg);  break;
1726             case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, long_arg); break;
1727 #ifdef SNPRINTF_LONGLONG_SUPPORT
1728             case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,long_long_arg); break;
1729 #endif
1730             }
1731           } else {  /* unsigned */
1732             switch (length_modifier) {
1733             case '\0':
1734             case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, uint_arg);  break;
1735             case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, ulong_arg); break;
1736 #ifdef SNPRINTF_LONGLONG_SUPPORT
1737             case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,ulong_long_arg);break;
1738 #endif
1739             }
1740           }
1741          /* include the optional minus sign and possible "0x"
1742             in the region before the zero padding insertion point */
1743           if (zero_padding_insertion_ind < str_arg_l &&
1744               tmp[zero_padding_insertion_ind] == '-') {
1745             zero_padding_insertion_ind++;
1746           }
1747           if (zero_padding_insertion_ind+1 < str_arg_l &&
1748               tmp[zero_padding_insertion_ind]   == '0' &&
1749              (tmp[zero_padding_insertion_ind+1] == 'x' ||
1750               tmp[zero_padding_insertion_ind+1] == 'X') ) {
1751             zero_padding_insertion_ind += 2;
1752           }
1753         }
1754         { size_t num_of_digits = str_arg_l - zero_padding_insertion_ind;
1755           if (alternate_form && fmt_spec == 'o'
1756 #ifdef HPUX_COMPATIBLE                                  /* ("%#.o",0) -> ""  */
1757               && (str_arg_l > 0)
1758 #endif
1759 #ifdef DIGITAL_UNIX_BUG_COMPATIBLE                      /* ("%#o",0) -> "00" */
1760 #else
1761               /* unless zero is already the first character */
1762               && !(zero_padding_insertion_ind < str_arg_l
1763                    && tmp[zero_padding_insertion_ind] == '0')
1764 #endif
1765           ) {        /* assure leading zero for alternate-form octal numbers */
1766             if (!precision_specified || precision < num_of_digits+1) {
1767              /* precision is increased to force the first character to be zero,
1768                 except if a zero value is formatted with an explicit precision
1769                 of zero */
1770               precision = num_of_digits+1; precision_specified = 1;
1771             }
1772           }
1773        /* zero padding to specified precision? */
1774           if (num_of_digits < precision) 
1775             number_of_zeros_to_pad = precision - num_of_digits;
1776         }
1777      /* zero padding to specified minimal field width? */
1778         if (!justify_left && zero_padding) {
1779           int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1780           if (n > 0) number_of_zeros_to_pad += n;
1781         }
1782         break;
1783       }
1784       default: /* unrecognized conversion specifier, keep format string as-is*/
1785         zero_padding = 0;  /* turn zero padding off for non-numeric convers. */
1786 #ifndef DIGITAL_UNIX_COMPATIBLE
1787         justify_left = 1; min_field_width = 0;                /* reset flags */
1788 #endif
1789 #if defined(PERL_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1790      /* keep the entire format string unchanged */
1791         str_arg = starting_p; str_arg_l = p - starting_p;
1792      /* well, not exactly so for Linux, which does something inbetween,
1793       * and I don't feel an urge to imitate it: "%+++++hy" -> "%+y"  */
1794 #else
1795      /* discard the unrecognized conversion, just keep *
1796       * the unrecognized conversion character          */
1797         str_arg = p; str_arg_l = 0;
1798 #endif
1799         if (*p) str_arg_l++;  /* include invalid conversion specifier unchanged
1800                                  if not at end-of-string */
1801         break;
1802       }
1803       if (*p) p++;      /* step over the just processed conversion specifier */
1804    /* insert padding to the left as requested by min_field_width;
1805       this does not include the zero padding in case of numerical conversions*/
1806       if (!justify_left) {                /* left padding with blank or zero */
1807         int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1808         if (n > 0) {
1809           if (str_l < str_m) {
1810             size_t avail = str_m-str_l;
1811             fast_memset(str+str_l, (zero_padding?'0':' '), (n>avail?avail:n));
1812           }
1813           str_l += n;
1814         }
1815       }
1816    /* zero padding as requested by the precision or by the minimal field width
1817     * for numeric conversions required? */
1818       if (number_of_zeros_to_pad <= 0) {
1819      /* will not copy first part of numeric right now, *
1820       * force it to be copied later in its entirety    */
1821         zero_padding_insertion_ind = 0;
1822       } else {
1823      /* insert first part of numerics (sign or '0x') before zero padding */
1824         int n = zero_padding_insertion_ind;
1825         if (n > 0) {
1826           if (str_l < str_m) {
1827             size_t avail = str_m-str_l;
1828             fast_memcpy(str+str_l, str_arg, (n>avail?avail:n));
1829           }
1830           str_l += n;
1831         }
1832      /* insert zero padding as requested by the precision or min field width */
1833         n = number_of_zeros_to_pad;
1834         if (n > 0) {
1835           if (str_l < str_m) {
1836             size_t avail = str_m-str_l;
1837             fast_memset(str+str_l, '0', (n>avail?avail:n));
1838           }
1839           str_l += n;
1840         }
1841       }
1842    /* insert formatted string
1843     * (or as-is conversion specifier for unknown conversions) */
1844       { int n = str_arg_l - zero_padding_insertion_ind;
1845         if (n > 0) {
1846           if (str_l < str_m) {
1847             size_t avail = str_m-str_l;
1848             fast_memcpy(str+str_l, str_arg+zero_padding_insertion_ind,
1849                         (n>avail?avail:n));
1850           }
1851           str_l += n;
1852         }
1853       }
1854    /* insert right padding */
1855       if (justify_left) {          /* right blank padding to the field width */
1856         int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1857         if (n > 0) {
1858           if (str_l < str_m) {
1859             size_t avail = str_m-str_l;
1860             fast_memset(str+str_l, ' ', (n>avail?avail:n));
1861           }
1862           str_l += n;
1863         }
1864       }
1865     }
1866   }
1867 #if defined(NEED_SNPRINTF_ONLY)
1868   va_end(ap);
1869 #endif
1870   if (str_m > 0) { /* make sure the string is null-terminated
1871                       even at the expense of overwriting the last character
1872                       (shouldn't happen, but just in case) */
1873     str[str_l <= str_m-1 ? str_l : str_m-1] = '\0';
1874   }
1875   /* Return the number of characters formatted (excluding trailing null
1876    * character), that is, the number of characters that would have been
1877    * written to the buffer if it were large enough.
1878    *
1879    * The value of str_l should be returned, but str_l is of unsigned type
1880    * size_t, and snprintf is int, possibly leading to an undetected
1881    * integer overflow, resulting in a negative return value, which is illegal.
1882    * Both XSH5 and ISO C99 (at least the draft) are silent on this issue.
1883    * Should errno be set to EOVERFLOW and EOF returned in this case???
1884    */
1885   return (int) str_l;
1886 }
1887 #endif
1888 #endif /* ndef HAVE_SNPRINTF */
1889 /*
1890   Local Variables:
1891   tab-width: 3
1892   end:
1893 */