1 const char miscutil_rcs[] = "$Id: miscutil.c,v 1.57 2008/03/24 15:29:51 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/miscutil.c,v $
6 * Purpose : zalloc, hash_string, safe_strerror, strcmpic,
7 * strncmpic, chomp, and MinGW32 strdup
9 * These are each too small to deserve their own file
10 * but don't really fit in any other file.
12 * Copyright : Written by and Copyright (C) 2001-2007
13 * the SourceForge Privoxy team. http://www.privoxy.org/
15 * Based on the Internet Junkbuster originally written
16 * by and Copyright (C) 1997 Anonymous Coders and
17 * Junkbusters Corporation. http://www.junkbusters.com
19 * The timegm replacement function was taken from GnuPG,
20 * Copyright (C) 2004 Free Software Foundation, Inc.
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".
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.
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.
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.
46 * $Log: miscutil.c,v $
47 * Revision 1.57 2008/03/24 15:29:51 fabiankeil
50 * Revision 1.56 2007/12/01 12:59:05 fabiankeil
51 * Some sanity checks for pick_from_range().
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.
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.
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.
65 * Revision 1.52 2007/08/19 12:32:34 fabiankeil
66 * Fix a conversion warning.
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.
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.
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.
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.
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.
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.
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
102 * Revision 1.44 2006/11/07 12:46:43 fabiankeil
103 * Silence compiler warning on NetBSD 3.1.
105 * Revision 1.43 2006/09/23 13:26:38 roro
106 * Replace TABs by spaces in source code.
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
113 * Revision 1.41 2006/08/18 16:03:17 david__schmidt
114 * Tweak for OS/2 build happiness.
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
122 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
124 * - Moved randomization code into pick_from_range().
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.
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)
136 * Revision 1.37.2.4 2003/12/01 14:45:14 oes
137 * Fixed two more problems with wildcarding in simplematch()
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\!
142 * Revision 1.37.2.2 2002/11/12 14:28:18 oes
143 * Proper backtracking in simplematch; fixes bug #632888
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).
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
153 * Revision 1.36 2002/04/26 12:55:38 oes
154 * New function string_toupper
156 * Revision 1.35 2002/03/26 22:29:55 swa
157 * we have a new homepage!
159 * Revision 1.34 2002/03/24 13:25:43 swa
160 * name change related issues
162 * Revision 1.33 2002/03/07 03:46:53 oes
163 * Fixed compiler warnings etc
165 * Revision 1.32 2002/03/06 23:02:57 jongfoster
168 * Revision 1.31 2002/03/05 04:52:42 oes
169 * Deleted non-errlog debugging code
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
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!)
180 * Revision 1.28 2002/03/03 09:18:03 joergs
181 * Made jumbjuster work on AmigaOS again.
183 * Revision 1.27 2002/01/21 00:52:32 jongfoster
184 * Adding string_join()
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)
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)
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.
203 * Add some fatal-error log message for failed malloc().
204 * Add '-d' if compiled with 'configure --with-debug' to
205 * enable debug output.
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.
211 * Revision 1.22 2001/10/26 17:39:38 oes
212 * Moved ijb_isspace and ijb_tolower to project.h
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)
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.
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.
230 * Revision 1.18 2001/09/20 13:33:43 steudten
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.
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.
239 * Revision 1.16 2001/09/10 10:56:59 oes
240 * Silenced compiler warnings
242 * Revision 1.15 2001/07/13 14:02:24 oes
243 * Removed vim-settings
245 * Revision 1.14 2001/06/29 21:45:41 oes
246 * Indentation, CRLF->LF, Tab-> Space
248 * Revision 1.13 2001/06/29 13:32:14 oes
249 * Removed logentry from cancelled commit
251 * Revision 1.12 2001/06/09 10:55:28 jongfoster
252 * Changing BUFSIZ ==> BUFFER_SIZE
254 * Revision 1.11 2001/06/07 23:09:19 jongfoster
255 * Cosmetic indentation changes.
257 * Revision 1.10 2001/06/07 14:51:38 joergs
258 * make_path() no longer adds '/' if the dir already ends in '/'.
260 * Revision 1.9 2001/06/07 14:43:17 swa
261 * slight mistake in make_path, unix path style is /.
263 * Revision 1.8 2001/06/05 22:32:01 jongfoster
264 * New function make_path() to splice directory and file names together.
266 * Revision 1.7 2001/06/03 19:12:30 oes
267 * introduced bindup()
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.
273 * Revision 1.5 2001/06/01 10:31:51 oes
274 * Added character class matching to trivimatch; renamed to simplematch
276 * Revision 1.4 2001/05/31 17:32:31 oes
278 * - Enhanced domain part globbing with infix and prefix asterisk
279 * matching and optional unanchored operation
281 * Revision 1.3 2001/05/29 23:10:09 oes
284 * - Introduced chomp()
285 * - Moved strsav() from showargs to miscutil
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
292 * Also modified interceptor behaviour:
293 * - We now intercept all URLs beginning with one of the following
294 * prefixes (and *only* these prefixes):
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
310 * Revision 1.1.1.1 2001/05/15 13:59:00 oes
311 * Initial import of version 2.9.3 source tree
314 *********************************************************************/
320 #include <sys/types.h>
322 #if !defined(_WIN32) && !defined(__OS2__)
324 #endif /* #if !defined(_WIN32) && !defined(__OS2__) */
329 #if !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV)
331 #endif /* !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV) */
334 #include "miscutil.h"
338 const char miscutil_h_rcs[] = MISCUTIL_H_VERSION;
340 /*********************************************************************
344 * Description : Malloc some memory and set it to '\0'.
345 * The way calloc() ought to be -acjc
348 * 1 : size = Size of memory chunk to return.
350 * Returns : Pointer to newly malloc'd memory chunk.
352 *********************************************************************/
353 void *zalloc(size_t size)
357 if ((ret = (void *)malloc(size)) != NULL)
359 memset(ret, 0, size);
368 /*********************************************************************
370 * Function : write_pid_file
372 * Description : Writes a pid file with the pid of the main process
378 *********************************************************************/
379 void write_pid_file(void)
384 * If no --pidfile option was given,
385 * we can live without one.
387 if (pidfile == NULL) return;
389 if ((fp = fopen(pidfile, "w")) == NULL)
391 log_error(LOG_LEVEL_INFO, "can't open pidfile '%s': %E", pidfile);
395 fprintf(fp, "%u\n", (unsigned int) getpid());
401 #endif /* def unix */
404 /*********************************************************************
406 * Function : hash_string
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.
413 * 1 : s : string to be hashed.
415 * Returns : an unsigned long variable with the hashed value.
417 *********************************************************************/
418 unsigned int hash_string( const char* s )
424 h = 5 * h + (unsigned int)*s;
433 /*********************************************************************
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.
443 * 1 : s = string to duplicate
445 * Returns : Pointer to newly malloc'ed copy of the string.
447 *********************************************************************/
448 char *strdup( const char *s )
450 char * result = (char *)malloc( strlen(s)+1 );
460 #endif /* def __MINGW32__ */
464 /*********************************************************************
466 * Function : safe_strerror
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.
473 * 1 : err = the `errno' of the last operation.
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.
479 *********************************************************************/
480 char *safe_strerror(int err)
483 char buf[BUFFER_SIZE];
488 #endif /* HAVE_STRERROR */
492 snprintf(buf, sizeof(buf), "(errno = %d)", err);
501 /*********************************************************************
503 * Function : strcmpic
505 * Description : Case insensitive string comparison
508 * 1 : s1 = string 1 to compare
509 * 2 : s2 = string 2 to compare
511 * Returns : 0 if s1==s2, Negative if s1<s2, Positive if s1>s2
513 *********************************************************************/
514 int strcmpic(const char *s1, const char *s2)
521 if ( ( *s1 != *s2 ) && ( ijb_tolower(*s1) != ijb_tolower(*s2) ) )
527 return(ijb_tolower(*s1) - ijb_tolower(*s2));
532 /*********************************************************************
534 * Function : strncmpic
536 * Description : Case insensitive string comparison (upto n characters)
539 * 1 : s1 = string 1 to compare
540 * 2 : s2 = string 2 to compare
541 * 3 : n = maximum characters to compare
543 * Returns : 0 if s1==s2, Negative if s1<s2, Positive if s1>s2
545 *********************************************************************/
546 int strncmpic(const char *s1, const char *s2, size_t n)
548 if (n <= 0) return(0);
554 if ( ( *s1 != *s2 ) && ( ijb_tolower(*s1) != ijb_tolower(*s2) ) )
563 return(ijb_tolower(*s1) - ijb_tolower(*s2));
568 /*********************************************************************
572 * Description : In-situ-eliminate all leading and trailing whitespace
576 * 1 : s : string to be chomped.
578 * Returns : chomped string
580 *********************************************************************/
581 char *chomp(char *string)
586 * strip trailing whitespace
588 p = string + strlen(string);
589 while (p > string && ijb_isspace(*(p-1)))
596 * find end of leading whitespace
599 while (*q && ijb_isspace(*q))
605 * if there was any, move the rest forwards
620 /*********************************************************************
622 * Function : string_append
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.
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:
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 ... }
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 ...}
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.
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.
667 *********************************************************************/
668 jb_err string_append(char **target_string, const char *text_to_append)
674 assert(target_string);
675 assert(text_to_append);
677 if (*target_string == NULL)
679 return JB_ERR_MEMORY;
682 if (*text_to_append == '\0')
687 old_len = strlen(*target_string);
689 new_size = strlen(text_to_append) + old_len + 1;
691 if (NULL == (new_string = realloc(*target_string, new_size)))
693 free(*target_string);
695 *target_string = NULL;
696 return JB_ERR_MEMORY;
699 strlcpy(new_string + old_len, text_to_append, new_size - old_len);
701 *target_string = new_string;
706 /*********************************************************************
708 * Function : string_join
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.
714 * For comparison, string_append requires that the
715 * second string is non-NULL, and doesn't free it.
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().
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.
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).
738 *********************************************************************/
739 jb_err string_join(char **target_string, char *text_to_append)
743 assert(target_string);
745 if (text_to_append == NULL)
747 freez(*target_string);
748 return JB_ERR_MEMORY;
751 err = string_append(target_string, text_to_append);
753 free(text_to_append);
759 /*********************************************************************
761 * Function : string_toupper
763 * Description : Produce a copy of string with all convertible
764 * characters converted to uppercase.
767 * 1 : string = string to convert
769 * Returns : Uppercase copy of string if possible,
770 * NULL on out-of-memory or if string was NULL.
772 *********************************************************************/
773 char *string_toupper(const char *string)
778 if (!string || ((result = (char *) zalloc(strlen(string) + 1)) == NULL))
788 *p++ = (char)toupper((int) *q++);
796 /*********************************************************************
800 * Description : Duplicate the first n characters of a string that may
801 * contain '\0' characters.
804 * 1 : string = string to be duplicated
805 * 2 : len = number of bytes to duplicate
807 * Returns : pointer to copy, or NULL if failiure
809 *********************************************************************/
810 char *bindup(const char *string, size_t len)
814 if (NULL == (duplicate = (char *)malloc(len)))
820 memcpy(duplicate, string, len);
828 /*********************************************************************
830 * Function : make_path
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
839 * 1 : dir: Name of directory or NULL for none.
840 * 2 : file: Name of file. Should not be NULL or empty.
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
847 *********************************************************************/
848 char * make_path(const char * dir, const char * file)
859 strncpy(path,dir+2,512);
863 strncpy(path,dir+1,512);
868 strncpy(path,dir,512);
876 if(AddPart(path,file,512))
884 #else /* ndef AMIGA */
886 if ((file == NULL) || (*file == '\0'))
888 return NULL; /* Error */
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__ */
904 size_t path_size = strlen(dir) + strlen(file) + 2; /* +2 for trailing (back)slash and \0 */
907 if ( *dir != '/' && basedir && *basedir )
910 * Relative path, so start with the base directory.
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);
920 #endif /* defined unix */
922 path = malloc(path_size);
923 if (!path ) log_error(LOG_LEVEL_FATAL, "malloc failed!");
924 strlcpy(path, dir, path_size);
927 #if defined(_WIN32) || defined(__OS2__)
928 if(path[strlen(path)-1] != '\\')
930 strlcat(path, "\\", path_size);
932 #else /* ifndef _WIN32 || __OS2__ */
933 if(path[strlen(path)-1] != '/')
935 strlcat(path, "/", path_size);
937 #endif /* ifndef _WIN32 || __OS2__ */
938 strlcat(path, file, path_size);
942 #endif /* ndef AMIGA */
946 /*********************************************************************
948 * Function : pick_from_range
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.
955 * 1 : range: Highest possible number to pick.
957 * Returns : Picked number.
959 *********************************************************************/
960 long int pick_from_range(long int range)
967 if (range <= 0) return 0;
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);
978 * On Windows and mingw32 srand() has to be called in every
979 * rand()-using thread, but can cause crashes if it's not
982 * Currently we don't have mutexes for mingw32, and for
983 * our purpose this cludge is probably preferable to crashes.
985 * The warning is shown once on startup from jcc.c.
987 number = (range + GetCurrentThreadId() % range) / 2;
990 * XXX: Which platforms reach this and are there
991 * better options than just using rand() and hoping
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 */
999 #endif /* (def HAVE_RANDOM) */
1005 #ifdef USE_PRIVOXY_STRLCPY
1006 /*********************************************************************
1008 * Function : privoxy_strlcpy
1010 * Description : strlcpy(3) look-alike for those without decent libc.
1013 * 1 : destination: buffer to copy into.
1014 * 2 : source: String to copy.
1015 * 3 : size: Size of destination buffer.
1017 * Returns : The length of the string that privoxy_strlcpy() tried to create.
1019 *********************************************************************/
1020 size_t privoxy_strlcpy(char *destination, const char *source, const size_t size)
1024 snprintf(destination, size, "%s", source);
1026 * Platforms that lack strlcpy() also tend to have
1027 * a broken snprintf implementation that doesn't
1028 * guarantee nul termination.
1030 * XXX: the configure script should detect and reject those.
1032 destination[size-1] = '\0';
1034 return strlen(source);
1036 #endif /* def USE_PRIVOXY_STRLCPY */
1039 #ifndef HAVE_STRLCAT
1040 /*********************************************************************
1042 * Function : privoxy_strlcat
1044 * Description : strlcat(3) look-alike for those without decent libc.
1047 * 1 : destination: C string.
1048 * 2 : source: String to copy.
1049 * 3 : size: Size of destination buffer.
1051 * Returns : The length of the string that privoxy_strlcat() tried to create.
1053 *********************************************************************/
1054 size_t privoxy_strlcat(char *destination, const char *source, const size_t size)
1056 const size_t old_length = strlen(destination);
1057 return old_length + strlcpy(destination + old_length, source, size - old_length);
1059 #endif /* ndef HAVE_STRLCAT */
1062 #if !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV)
1063 /*********************************************************************
1067 * Description : libc replacement function for the inverse of gmtime().
1068 * Copyright (C) 2004 Free Software Foundation, Inc.
1070 * Code originally copied from GnuPG, modifications done
1071 * for Privoxy: style changed, #ifdefs for _WIN32 added
1072 * to have it work on mingw32.
1074 * XXX: It's very unlikely to happen, but if the malloc()
1075 * call fails the time zone will be permanently set to UTC.
1078 * 1 : tm: Broken-down time struct.
1080 * Returns : tm converted into time_t seconds.
1082 *********************************************************************/
1083 time_t timegm(struct tm *tm)
1088 zone = getenv("TZ");
1091 answer = mktime(tm);
1096 old_zone = malloc(3 + strlen(zone) + 1);
1099 strcpy(old_zone, "TZ=");
1100 strcat(old_zone, zone);
1104 #endif /* def _WIN32 */
1109 #ifdef HAVE_UNSETENV
1111 #elif defined(_WIN32)
1121 #endif /* !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV) */
1124 #ifndef HAVE_SNPRINTF
1126 * What follows is a portable snprintf routine, written by Mark Martinec.
1127 * See: http://www.ijs.si/software/snprintf/
1130 - a portable implementation of snprintf,
1131 including vsnprintf.c, asnprintf, vasnprintf, asprintf, vasprintf
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.
1144 Mark Martinec <mark.martinec@ijs.si>, April 1999, June 2000
1145 Copyright © 1999, Mark Martinec
1149 #define PORTABLE_SNPRINTF_VERSION_MAJOR 2
1150 #define PORTABLE_SNPRINTF_VERSION_MINOR 2
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
1156 # if !defined(PREFER_PORTABLE_SNPRINTF)
1157 # define PREFER_PORTABLE_SNPRINTF
1161 #if defined(SOLARIS_BUG_COMPATIBLE) && !defined(SOLARIS_COMPATIBLE)
1162 #define SOLARIS_COMPATIBLE
1165 #if defined(HPUX_BUG_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
1166 #define HPUX_COMPATIBLE
1169 #if defined(DIGITAL_UNIX_BUG_COMPATIBLE) && !defined(DIGITAL_UNIX_COMPATIBLE)
1170 #define DIGITAL_UNIX_COMPATIBLE
1173 #if defined(PERL_BUG_COMPATIBLE) && !defined(PERL_COMPATIBLE)
1174 #define PERL_COMPATIBLE
1177 #if defined(LINUX_BUG_COMPATIBLE) && !defined(LINUX_COMPATIBLE)
1178 #define LINUX_COMPATIBLE
1181 #include <sys/types.h>
1192 #define isdigit(c) ((c) >= '0' && (c) <= '9')
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.
1202 * Small values favor memcpy, large values favor inline code.
1204 #if defined(__alpha__) || defined(__alpha)
1205 # define breakeven_point 2 /* AXP (DEC Alpha) - gcc or cc or egcs */
1207 #if defined(__i386__) || defined(__i386)
1208 # define breakeven_point 12 /* Intel Pentium/Linux - gcc 2.96 */
1211 # define breakeven_point 10 /* HP-PA - gcc */
1213 #if defined(__sparc__) || defined(__sparc)
1214 # define breakeven_point 33 /* Sun Sparc 5 - gcc 2.8.1 */
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 */
1221 #ifndef breakeven_point
1222 # define breakeven_point 6 /* some reasonable one-size-fits-all value */
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++; } }
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; } }
1241 #if defined(NEED_ASPRINTF)
1242 int asprintf (char **ptr, const char *fmt, /*args*/ ...);
1244 #if defined(NEED_VASPRINTF)
1245 int vasprintf (char **ptr, const char *fmt, va_list ap);
1247 #if defined(NEED_ASNPRINTF)
1248 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...);
1250 #if defined(NEED_VASNPRINTF)
1251 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap);
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 */
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
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);
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";
1279 #if defined(NEED_ASPRINTF)
1280 int asprintf(char **ptr, const char *fmt, /*args*/ ...) {
1286 va_start(ap, fmt); /* measure the required size */
1287 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, 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; }
1295 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1297 assert(str_l2 == str_l);
1303 #if defined(NEED_VASPRINTF)
1304 int vasprintf(char **ptr, const char *fmt, va_list ap) {
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*/
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; }
1318 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1319 assert(str_l2 == str_l);
1325 #if defined(NEED_ASNPRINTF)
1326 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...) {
1331 va_start(ap, fmt); /* measure the required size */
1332 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, 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 */
1339 *ptr = (char *) malloc(str_m);
1340 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1344 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1346 assert(str_l2 == str_l);
1353 #if defined(NEED_VASNPRINTF)
1354 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap) {
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*/
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 */
1368 *ptr = (char *) malloc(str_m);
1369 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1371 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1372 assert(str_l2 == str_l);
1380 * If the system does have snprintf and the portable routine is not
1381 * specifically required, this module produces no code for snprintf/vsnprintf.
1383 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1385 #if !defined(NEED_SNPRINTF_ONLY)
1386 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1391 str_l = portable_vsnprintf(str, str_m, fmt, ap);
1397 #if defined(NEED_SNPRINTF_ONLY)
1398 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1400 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) {
1403 #if defined(NEED_SNPRINTF_ONLY)
1407 const char *p = fmt;
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; */
1413 #if defined(NEED_SNPRINTF_ONLY)
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));
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 */
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
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 */
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 */
1451 size_t zero_padding_insertion_ind = 0;
1452 /* index into tmp where zero padding is to be inserted */
1454 char fmt_spec = '\0';
1455 /* current conversion specifier character */
1457 str_arg = credits;/* just to make compiler happy (defined but not used)*/
1459 starting_p = p; p++; /* skip '%' */
1461 while (*p == '0' || *p == '-' || *p == '+' ||
1462 *p == ' ' || *p == '#' || *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;
1474 case '#': alternate_form = 1; break;
1479 /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
1481 /* parse field width */
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;
1494 /* parse precision */
1496 p++; precision_specified = 1;
1498 int j = va_arg(ap, int);
1500 if (j >= 0) precision = j;
1502 precision_specified = 0; precision = 0;
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.
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');
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' */
1525 length_modifier = 'l'; /* treat it as a single 'l' */
1531 /* common synonyms: */
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;
1539 /* get parameter value, do initial processing */
1541 case '%': /* % behaves similar to 's' regarding flags and field widths */
1542 case 'c': /* c behaves similar to 's' regarding flags and field widths */
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 */
1556 int j = va_arg(ap, int);
1557 uchar_arg = (unsigned char) j; /* standard demands unsigned char */
1558 str_arg = (const char *) &uchar_arg;
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;
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);
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 */
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) */
1587 int int_arg = 0; unsigned int uint_arg = 0;
1588 /* only defined for length modifier h, or for no length modifiers */
1590 long int long_arg = 0; unsigned long int ulong_arg = 0;
1591 /* only defined for length modifier l */
1593 void *ptr_arg = NULL;
1594 /* pointer argument value -only defined for p conversion */
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 */
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.
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).
1612 #ifdef SOLARIS_COMPATIBLE
1613 # ifdef SOLARIS_BUG_COMPATIBLE
1614 /* keep length modifiers even if it represents 'll' */
1616 if (length_modifier == '2') length_modifier = '\0';
1619 length_modifier = '\0';
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) {
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.
1632 int_arg = va_arg(ap, int);
1633 if (int_arg > 0) arg_sign = 1;
1634 else if (int_arg < 0) arg_sign = -1;
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;
1641 #ifdef SNPRINTF_LONGLONG_SUPPORT
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;
1649 } else { /* unsigned */
1650 switch (length_modifier) {
1653 uint_arg = va_arg(ap, unsigned int);
1654 if (uint_arg) arg_sign = 1;
1657 ulong_arg = va_arg(ap, unsigned long int);
1658 if (ulong_arg) arg_sign = 1;
1660 #ifdef SNPRINTF_LONGLONG_SUPPORT
1662 ulong_long_arg = va_arg(ap, unsigned long long int);
1663 if (ulong_long_arg) arg_sign = 1;
1668 str_arg = tmp; str_arg_l = 0;
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.
1674 #ifndef PERL_COMPATIBLE
1675 if (precision_specified) zero_padding = 0;
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 ? ' ' : '+';
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. */
1698 ) { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = 'x'; }
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)
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)". */
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). */
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) {
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;
1731 } else { /* unsigned */
1732 switch (length_modifier) {
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;
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++;
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;
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) -> "" */
1759 #ifdef DIGITAL_UNIX_BUG_COMPATIBLE /* ("%#o",0) -> "00" */
1761 /* unless zero is already the first character */
1762 && !(zero_padding_insertion_ind < str_arg_l
1763 && tmp[zero_padding_insertion_ind] == '0')
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
1770 precision = num_of_digits+1; precision_specified = 1;
1773 /* zero padding to specified precision? */
1774 if (num_of_digits < precision)
1775 number_of_zeros_to_pad = precision - num_of_digits;
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;
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 */
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" */
1795 /* discard the unrecognized conversion, just keep *
1796 * the unrecognized conversion character */
1797 str_arg = p; str_arg_l = 0;
1799 if (*p) str_arg_l++; /* include invalid conversion specifier unchanged
1800 if not at end-of-string */
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);
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));
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;
1823 /* insert first part of numerics (sign or '0x') before zero padding */
1824 int n = zero_padding_insertion_ind;
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));
1832 /* insert zero padding as requested by the precision or min field width */
1833 n = number_of_zeros_to_pad;
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));
1842 /* insert formatted string
1843 * (or as-is conversion specifier for unknown conversions) */
1844 { int n = str_arg_l - zero_padding_insertion_ind;
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,
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);
1858 if (str_l < str_m) {
1859 size_t avail = str_m-str_l;
1860 fast_memset(str+str_l, ' ', (n>avail?avail:n));
1867 #if defined(NEED_SNPRINTF_ONLY)
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';
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.
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???
1888 #endif /* ndef HAVE_SNPRINTF */