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