1 const char miscutil_rcs[] = "$Id: miscutil.c,v 1.59 2008/09/04 08:13:58 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.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.
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.
55 * Revision 1.57 2008/03/24 15:29:51 fabiankeil
58 * Revision 1.56 2007/12/01 12:59:05 fabiankeil
59 * Some sanity checks for pick_from_range().
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.
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.
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.
73 * Revision 1.52 2007/08/19 12:32:34 fabiankeil
74 * Fix a conversion warning.
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.
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.
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.
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.
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.
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.
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
110 * Revision 1.44 2006/11/07 12:46:43 fabiankeil
111 * Silence compiler warning on NetBSD 3.1.
113 * Revision 1.43 2006/09/23 13:26:38 roro
114 * Replace TABs by spaces in source code.
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
121 * Revision 1.41 2006/08/18 16:03:17 david__schmidt
122 * Tweak for OS/2 build happiness.
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
130 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
132 * - Moved randomization code into pick_from_range().
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.
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)
144 * Revision 1.37.2.4 2003/12/01 14:45:14 oes
145 * Fixed two more problems with wildcarding in simplematch()
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\!
150 * Revision 1.37.2.2 2002/11/12 14:28:18 oes
151 * Proper backtracking in simplematch; fixes bug #632888
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).
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
161 * Revision 1.36 2002/04/26 12:55:38 oes
162 * New function string_toupper
164 * Revision 1.35 2002/03/26 22:29:55 swa
165 * we have a new homepage!
167 * Revision 1.34 2002/03/24 13:25:43 swa
168 * name change related issues
170 * Revision 1.33 2002/03/07 03:46:53 oes
171 * Fixed compiler warnings etc
173 * Revision 1.32 2002/03/06 23:02:57 jongfoster
176 * Revision 1.31 2002/03/05 04:52:42 oes
177 * Deleted non-errlog debugging code
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
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!)
188 * Revision 1.28 2002/03/03 09:18:03 joergs
189 * Made jumbjuster work on AmigaOS again.
191 * Revision 1.27 2002/01/21 00:52:32 jongfoster
192 * Adding string_join()
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)
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)
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.
211 * Add some fatal-error log message for failed malloc().
212 * Add '-d' if compiled with 'configure --with-debug' to
213 * enable debug output.
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.
219 * Revision 1.22 2001/10/26 17:39:38 oes
220 * Moved ijb_isspace and ijb_tolower to project.h
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)
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.
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.
238 * Revision 1.18 2001/09/20 13:33:43 steudten
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.
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.
247 * Revision 1.16 2001/09/10 10:56:59 oes
248 * Silenced compiler warnings
250 * Revision 1.15 2001/07/13 14:02:24 oes
251 * Removed vim-settings
253 * Revision 1.14 2001/06/29 21:45:41 oes
254 * Indentation, CRLF->LF, Tab-> Space
256 * Revision 1.13 2001/06/29 13:32:14 oes
257 * Removed logentry from cancelled commit
259 * Revision 1.12 2001/06/09 10:55:28 jongfoster
260 * Changing BUFSIZ ==> BUFFER_SIZE
262 * Revision 1.11 2001/06/07 23:09:19 jongfoster
263 * Cosmetic indentation changes.
265 * Revision 1.10 2001/06/07 14:51:38 joergs
266 * make_path() no longer adds '/' if the dir already ends in '/'.
268 * Revision 1.9 2001/06/07 14:43:17 swa
269 * slight mistake in make_path, unix path style is /.
271 * Revision 1.8 2001/06/05 22:32:01 jongfoster
272 * New function make_path() to splice directory and file names together.
274 * Revision 1.7 2001/06/03 19:12:30 oes
275 * introduced bindup()
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.
281 * Revision 1.5 2001/06/01 10:31:51 oes
282 * Added character class matching to trivimatch; renamed to simplematch
284 * Revision 1.4 2001/05/31 17:32:31 oes
286 * - Enhanced domain part globbing with infix and prefix asterisk
287 * matching and optional unanchored operation
289 * Revision 1.3 2001/05/29 23:10:09 oes
292 * - Introduced chomp()
293 * - Moved strsav() from showargs to miscutil
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
300 * Also modified interceptor behaviour:
301 * - We now intercept all URLs beginning with one of the following
302 * prefixes (and *only* these prefixes):
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
318 * Revision 1.1.1.1 2001/05/15 13:59:00 oes
319 * Initial import of version 2.9.3 source tree
322 *********************************************************************/
328 #include <sys/types.h>
330 #if !defined(_WIN32) && !defined(__OS2__)
332 #endif /* #if !defined(_WIN32) && !defined(__OS2__) */
337 #if !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV)
339 #endif /* !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV) */
342 #include "miscutil.h"
346 const char miscutil_h_rcs[] = MISCUTIL_H_VERSION;
348 /*********************************************************************
352 * Description : Malloc some memory and set it to '\0'.
353 * The way calloc() ought to be -acjc
356 * 1 : size = Size of memory chunk to return.
358 * Returns : Pointer to newly malloc'd memory chunk.
360 *********************************************************************/
361 void *zalloc(size_t size)
365 if ((ret = (void *)malloc(size)) != NULL)
367 memset(ret, 0, size);
376 /*********************************************************************
378 * Function : write_pid_file
380 * Description : Writes a pid file with the pid of the main process
386 *********************************************************************/
387 void write_pid_file(void)
392 * If no --pidfile option was given,
393 * we can live without one.
395 if (pidfile == NULL) return;
397 if ((fp = fopen(pidfile, "w")) == NULL)
399 log_error(LOG_LEVEL_INFO, "can't open pidfile '%s': %E", pidfile);
403 fprintf(fp, "%u\n", (unsigned int) getpid());
409 #endif /* def unix */
412 /*********************************************************************
414 * Function : hash_string
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.
421 * 1 : s : string to be hashed.
423 * Returns : an unsigned long variable with the hashed value.
425 *********************************************************************/
426 unsigned int hash_string( const char* s )
432 h = 5 * h + (unsigned int)*s;
441 /*********************************************************************
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.
451 * 1 : s = string to duplicate
453 * Returns : Pointer to newly malloc'ed copy of the string.
455 *********************************************************************/
456 char *strdup( const char *s )
458 char * result = (char *)malloc( strlen(s)+1 );
468 #endif /* def __MINGW32__ */
472 /*********************************************************************
474 * Function : safe_strerror
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.
481 * 1 : err = the `errno' of the last operation.
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.
487 *********************************************************************/
488 char *safe_strerror(int err)
491 char buf[BUFFER_SIZE];
496 #endif /* HAVE_STRERROR */
500 snprintf(buf, sizeof(buf), "(errno = %d)", err);
509 /*********************************************************************
511 * Function : strcmpic
513 * Description : Case insensitive string comparison
516 * 1 : s1 = string 1 to compare
517 * 2 : s2 = string 2 to compare
519 * Returns : 0 if s1==s2, Negative if s1<s2, Positive if s1>s2
521 *********************************************************************/
522 int strcmpic(const char *s1, const char *s2)
529 if ( ( *s1 != *s2 ) && ( ijb_tolower(*s1) != ijb_tolower(*s2) ) )
535 return(ijb_tolower(*s1) - ijb_tolower(*s2));
540 /*********************************************************************
542 * Function : strncmpic
544 * Description : Case insensitive string comparison (upto n characters)
547 * 1 : s1 = string 1 to compare
548 * 2 : s2 = string 2 to compare
549 * 3 : n = maximum characters to compare
551 * Returns : 0 if s1==s2, Negative if s1<s2, Positive if s1>s2
553 *********************************************************************/
554 int strncmpic(const char *s1, const char *s2, size_t n)
556 if (n <= 0) return(0);
562 if ( ( *s1 != *s2 ) && ( ijb_tolower(*s1) != ijb_tolower(*s2) ) )
571 return(ijb_tolower(*s1) - ijb_tolower(*s2));
576 /*********************************************************************
580 * Description : In-situ-eliminate all leading and trailing whitespace
584 * 1 : s : string to be chomped.
586 * Returns : chomped string
588 *********************************************************************/
589 char *chomp(char *string)
594 * strip trailing whitespace
596 p = string + strlen(string);
597 while (p > string && ijb_isspace(*(p-1)))
604 * find end of leading whitespace
607 while (*q && ijb_isspace(*q))
613 * if there was any, move the rest forwards
628 /*********************************************************************
630 * Function : string_append
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.
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:
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 ... }
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 ...}
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.
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.
675 *********************************************************************/
676 jb_err string_append(char **target_string, const char *text_to_append)
682 assert(target_string);
683 assert(text_to_append);
685 if (*target_string == NULL)
687 return JB_ERR_MEMORY;
690 if (*text_to_append == '\0')
695 old_len = strlen(*target_string);
697 new_size = strlen(text_to_append) + old_len + 1;
699 if (NULL == (new_string = realloc(*target_string, new_size)))
701 free(*target_string);
703 *target_string = NULL;
704 return JB_ERR_MEMORY;
707 strlcpy(new_string + old_len, text_to_append, new_size - old_len);
709 *target_string = new_string;
714 /*********************************************************************
716 * Function : string_join
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.
722 * For comparison, string_append requires that the
723 * second string is non-NULL, and doesn't free it.
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().
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.
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).
746 *********************************************************************/
747 jb_err string_join(char **target_string, char *text_to_append)
751 assert(target_string);
753 if (text_to_append == NULL)
755 freez(*target_string);
756 return JB_ERR_MEMORY;
759 err = string_append(target_string, text_to_append);
761 free(text_to_append);
767 /*********************************************************************
769 * Function : string_toupper
771 * Description : Produce a copy of string with all convertible
772 * characters converted to uppercase.
775 * 1 : string = string to convert
777 * Returns : Uppercase copy of string if possible,
778 * NULL on out-of-memory or if string was NULL.
780 *********************************************************************/
781 char *string_toupper(const char *string)
786 if (!string || ((result = (char *) zalloc(strlen(string) + 1)) == NULL))
796 *p++ = (char)toupper((int) *q++);
804 /*********************************************************************
808 * Description : Duplicate the first n characters of a string that may
809 * contain '\0' characters.
812 * 1 : string = string to be duplicated
813 * 2 : len = number of bytes to duplicate
815 * Returns : pointer to copy, or NULL if failiure
817 *********************************************************************/
818 char *bindup(const char *string, size_t len)
822 if (NULL == (duplicate = (char *)malloc(len)))
828 memcpy(duplicate, string, len);
836 /*********************************************************************
838 * Function : make_path
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
847 * 1 : dir: Name of directory or NULL for none.
848 * 2 : file: Name of file. Should not be NULL or empty.
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
855 *********************************************************************/
856 char * make_path(const char * dir, const char * file)
867 strncpy(path,dir+2,512);
871 strncpy(path,dir+1,512);
876 strncpy(path,dir,512);
884 if(AddPart(path,file,512))
892 #else /* ndef AMIGA */
894 if ((file == NULL) || (*file == '\0'))
896 return NULL; /* Error */
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__ */
912 size_t path_size = strlen(dir) + strlen(file) + 2; /* +2 for trailing (back)slash and \0 */
915 if ( *dir != '/' && basedir && *basedir )
918 * Relative path, so start with the base directory.
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);
928 #endif /* defined unix */
930 path = malloc(path_size);
931 if (!path ) log_error(LOG_LEVEL_FATAL, "malloc failed!");
932 strlcpy(path, dir, path_size);
935 #if defined(_WIN32) || defined(__OS2__)
936 if(path[strlen(path)-1] != '\\')
938 strlcat(path, "\\", path_size);
940 #else /* ifndef _WIN32 || __OS2__ */
941 if(path[strlen(path)-1] != '/')
943 strlcat(path, "/", path_size);
945 #endif /* ifndef _WIN32 || __OS2__ */
946 strlcat(path, file, path_size);
950 #endif /* ndef AMIGA */
954 /*********************************************************************
956 * Function : pick_from_range
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.
963 * 1 : range: Highest possible number to pick.
965 * Returns : Picked number.
967 *********************************************************************/
968 long int pick_from_range(long int range)
975 if (range <= 0) return 0;
978 number = random() % range + 1;
979 #elif defined(MUTEX_LOCKS_AVAILABLE)
980 privoxy_mutex_lock(&rand_mutex);
982 srand((unsigned)(GetCurrentThreadId()+GetTickCount()));
983 #endif /* def _WIN32 */
984 number = rand() % (long int)(range + 1);
985 privoxy_mutex_unlock(&rand_mutex);
988 * XXX: Which platforms reach this and are there
989 * better options than just using rand() and hoping
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);
996 #endif /* (def HAVE_RANDOM) */
1002 #ifdef USE_PRIVOXY_STRLCPY
1003 /*********************************************************************
1005 * Function : privoxy_strlcpy
1007 * Description : strlcpy(3) look-alike for those without decent libc.
1010 * 1 : destination: buffer to copy into.
1011 * 2 : source: String to copy.
1012 * 3 : size: Size of destination buffer.
1014 * Returns : The length of the string that privoxy_strlcpy() tried to create.
1016 *********************************************************************/
1017 size_t privoxy_strlcpy(char *destination, const char *source, const size_t size)
1021 snprintf(destination, size, "%s", source);
1023 * Platforms that lack strlcpy() also tend to have
1024 * a broken snprintf implementation that doesn't
1025 * guarantee nul termination.
1027 * XXX: the configure script should detect and reject those.
1029 destination[size-1] = '\0';
1031 return strlen(source);
1033 #endif /* def USE_PRIVOXY_STRLCPY */
1036 #ifndef HAVE_STRLCAT
1037 /*********************************************************************
1039 * Function : privoxy_strlcat
1041 * Description : strlcat(3) look-alike for those without decent libc.
1044 * 1 : destination: C string.
1045 * 2 : source: String to copy.
1046 * 3 : size: Size of destination buffer.
1048 * Returns : The length of the string that privoxy_strlcat() tried to create.
1050 *********************************************************************/
1051 size_t privoxy_strlcat(char *destination, const char *source, const size_t size)
1053 const size_t old_length = strlen(destination);
1054 return old_length + strlcpy(destination + old_length, source, size - old_length);
1056 #endif /* ndef HAVE_STRLCAT */
1059 #if !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV)
1060 /*********************************************************************
1064 * Description : libc replacement function for the inverse of gmtime().
1065 * Copyright (C) 2004 Free Software Foundation, Inc.
1067 * Code originally copied from GnuPG, modifications done
1068 * for Privoxy: style changed, #ifdefs for _WIN32 added
1069 * to have it work on mingw32.
1071 * XXX: It's very unlikely to happen, but if the malloc()
1072 * call fails the time zone will be permanently set to UTC.
1075 * 1 : tm: Broken-down time struct.
1077 * Returns : tm converted into time_t seconds.
1079 *********************************************************************/
1080 time_t timegm(struct tm *tm)
1085 zone = getenv("TZ");
1088 answer = mktime(tm);
1093 old_zone = malloc(3 + strlen(zone) + 1);
1096 strcpy(old_zone, "TZ=");
1097 strcat(old_zone, zone);
1101 #endif /* def _WIN32 */
1106 #ifdef HAVE_UNSETENV
1108 #elif defined(_WIN32)
1118 #endif /* !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV) */
1121 #ifndef HAVE_SNPRINTF
1123 * What follows is a portable snprintf routine, written by Mark Martinec.
1124 * See: http://www.ijs.si/software/snprintf/
1127 - a portable implementation of snprintf,
1128 including vsnprintf.c, asnprintf, vasnprintf, asprintf, vasprintf
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.
1141 Mark Martinec <mark.martinec@ijs.si>, April 1999, June 2000
1142 Copyright © 1999, Mark Martinec
1146 #define PORTABLE_SNPRINTF_VERSION_MAJOR 2
1147 #define PORTABLE_SNPRINTF_VERSION_MINOR 2
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
1153 # if !defined(PREFER_PORTABLE_SNPRINTF)
1154 # define PREFER_PORTABLE_SNPRINTF
1158 #if defined(SOLARIS_BUG_COMPATIBLE) && !defined(SOLARIS_COMPATIBLE)
1159 #define SOLARIS_COMPATIBLE
1162 #if defined(HPUX_BUG_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
1163 #define HPUX_COMPATIBLE
1166 #if defined(DIGITAL_UNIX_BUG_COMPATIBLE) && !defined(DIGITAL_UNIX_COMPATIBLE)
1167 #define DIGITAL_UNIX_COMPATIBLE
1170 #if defined(PERL_BUG_COMPATIBLE) && !defined(PERL_COMPATIBLE)
1171 #define PERL_COMPATIBLE
1174 #if defined(LINUX_BUG_COMPATIBLE) && !defined(LINUX_COMPATIBLE)
1175 #define LINUX_COMPATIBLE
1178 #include <sys/types.h>
1189 #define isdigit(c) ((c) >= '0' && (c) <= '9')
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.
1199 * Small values favor memcpy, large values favor inline code.
1201 #if defined(__alpha__) || defined(__alpha)
1202 # define breakeven_point 2 /* AXP (DEC Alpha) - gcc or cc or egcs */
1204 #if defined(__i386__) || defined(__i386)
1205 # define breakeven_point 12 /* Intel Pentium/Linux - gcc 2.96 */
1208 # define breakeven_point 10 /* HP-PA - gcc */
1210 #if defined(__sparc__) || defined(__sparc)
1211 # define breakeven_point 33 /* Sun Sparc 5 - gcc 2.8.1 */
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 */
1218 #ifndef breakeven_point
1219 # define breakeven_point 6 /* some reasonable one-size-fits-all value */
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++; } }
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; } }
1238 #if defined(NEED_ASPRINTF)
1239 int asprintf (char **ptr, const char *fmt, /*args*/ ...);
1241 #if defined(NEED_VASPRINTF)
1242 int vasprintf (char **ptr, const char *fmt, va_list ap);
1244 #if defined(NEED_ASNPRINTF)
1245 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...);
1247 #if defined(NEED_VASNPRINTF)
1248 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap);
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 */
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
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);
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";
1276 #if defined(NEED_ASPRINTF)
1277 int asprintf(char **ptr, const char *fmt, /*args*/ ...) {
1283 va_start(ap, fmt); /* measure the required size */
1284 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, 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; }
1292 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1294 assert(str_l2 == str_l);
1300 #if defined(NEED_VASPRINTF)
1301 int vasprintf(char **ptr, const char *fmt, va_list ap) {
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*/
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; }
1315 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1316 assert(str_l2 == str_l);
1322 #if defined(NEED_ASNPRINTF)
1323 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...) {
1328 va_start(ap, fmt); /* measure the required size */
1329 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, 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 */
1336 *ptr = (char *) malloc(str_m);
1337 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1341 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1343 assert(str_l2 == str_l);
1350 #if defined(NEED_VASNPRINTF)
1351 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap) {
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*/
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 */
1365 *ptr = (char *) malloc(str_m);
1366 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1368 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1369 assert(str_l2 == str_l);
1377 * If the system does have snprintf and the portable routine is not
1378 * specifically required, this module produces no code for snprintf/vsnprintf.
1380 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1382 #if !defined(NEED_SNPRINTF_ONLY)
1383 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1388 str_l = portable_vsnprintf(str, str_m, fmt, ap);
1394 #if defined(NEED_SNPRINTF_ONLY)
1395 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1397 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) {
1400 #if defined(NEED_SNPRINTF_ONLY)
1404 const char *p = fmt;
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; */
1410 #if defined(NEED_SNPRINTF_ONLY)
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));
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 */
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
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 */
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 */
1448 size_t zero_padding_insertion_ind = 0;
1449 /* index into tmp where zero padding is to be inserted */
1451 char fmt_spec = '\0';
1452 /* current conversion specifier character */
1454 str_arg = credits;/* just to make compiler happy (defined but not used)*/
1456 starting_p = p; p++; /* skip '%' */
1458 while (*p == '0' || *p == '-' || *p == '+' ||
1459 *p == ' ' || *p == '#' || *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;
1471 case '#': alternate_form = 1; break;
1476 /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
1478 /* parse field width */
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;
1491 /* parse precision */
1493 p++; precision_specified = 1;
1495 int j = va_arg(ap, int);
1497 if (j >= 0) precision = j;
1499 precision_specified = 0; precision = 0;
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.
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');
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' */
1522 length_modifier = 'l'; /* treat it as a single 'l' */
1528 /* common synonyms: */
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;
1536 /* get parameter value, do initial processing */
1538 case '%': /* % behaves similar to 's' regarding flags and field widths */
1539 case 'c': /* c behaves similar to 's' regarding flags and field widths */
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 */
1553 int j = va_arg(ap, int);
1554 uchar_arg = (unsigned char) j; /* standard demands unsigned char */
1555 str_arg = (const char *) &uchar_arg;
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;
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);
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 */
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) */
1584 int int_arg = 0; unsigned int uint_arg = 0;
1585 /* only defined for length modifier h, or for no length modifiers */
1587 long int long_arg = 0; unsigned long int ulong_arg = 0;
1588 /* only defined for length modifier l */
1590 void *ptr_arg = NULL;
1591 /* pointer argument value -only defined for p conversion */
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 */
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.
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).
1609 #ifdef SOLARIS_COMPATIBLE
1610 # ifdef SOLARIS_BUG_COMPATIBLE
1611 /* keep length modifiers even if it represents 'll' */
1613 if (length_modifier == '2') length_modifier = '\0';
1616 length_modifier = '\0';
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) {
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.
1629 int_arg = va_arg(ap, int);
1630 if (int_arg > 0) arg_sign = 1;
1631 else if (int_arg < 0) arg_sign = -1;
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;
1638 #ifdef SNPRINTF_LONGLONG_SUPPORT
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;
1646 } else { /* unsigned */
1647 switch (length_modifier) {
1650 uint_arg = va_arg(ap, unsigned int);
1651 if (uint_arg) arg_sign = 1;
1654 ulong_arg = va_arg(ap, unsigned long int);
1655 if (ulong_arg) arg_sign = 1;
1657 #ifdef SNPRINTF_LONGLONG_SUPPORT
1659 ulong_long_arg = va_arg(ap, unsigned long long int);
1660 if (ulong_long_arg) arg_sign = 1;
1665 str_arg = tmp; str_arg_l = 0;
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.
1671 #ifndef PERL_COMPATIBLE
1672 if (precision_specified) zero_padding = 0;
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 ? ' ' : '+';
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. */
1695 ) { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = 'x'; }
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)
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)". */
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). */
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) {
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;
1728 } else { /* unsigned */
1729 switch (length_modifier) {
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;
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++;
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;
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) -> "" */
1756 #ifdef DIGITAL_UNIX_BUG_COMPATIBLE /* ("%#o",0) -> "00" */
1758 /* unless zero is already the first character */
1759 && !(zero_padding_insertion_ind < str_arg_l
1760 && tmp[zero_padding_insertion_ind] == '0')
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
1767 precision = num_of_digits+1; precision_specified = 1;
1770 /* zero padding to specified precision? */
1771 if (num_of_digits < precision)
1772 number_of_zeros_to_pad = precision - num_of_digits;
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;
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 */
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" */
1792 /* discard the unrecognized conversion, just keep *
1793 * the unrecognized conversion character */
1794 str_arg = p; str_arg_l = 0;
1796 if (*p) str_arg_l++; /* include invalid conversion specifier unchanged
1797 if not at end-of-string */
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);
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));
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;
1820 /* insert first part of numerics (sign or '0x') before zero padding */
1821 int n = zero_padding_insertion_ind;
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));
1829 /* insert zero padding as requested by the precision or min field width */
1830 n = number_of_zeros_to_pad;
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));
1839 /* insert formatted string
1840 * (or as-is conversion specifier for unknown conversions) */
1841 { int n = str_arg_l - zero_padding_insertion_ind;
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,
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);
1855 if (str_l < str_m) {
1856 size_t avail = str_m-str_l;
1857 fast_memset(str+str_l, ' ', (n>avail?avail:n));
1864 #if defined(NEED_SNPRINTF_ONLY)
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';
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.
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???
1885 #endif /* ndef HAVE_SNPRINTF */