1 const char miscutil_rcs[] = "$Id: miscutil.c,v 1.51 2007/06/17 16:12:22 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.51 2007/06/17 16:12:22 fabiankeil
48 * #ifdef _WIN32 the last commit. According to David Shaw,
49 * one of the gnupg developers, the changes are mingw32-specific.
51 * Revision 1.50 2007/06/10 14:59:59 fabiankeil
52 * Change replacement timegm() to better match our style, plug a small
53 * but guaranteed memory leak and fix "time zone breathing" on mingw32.
55 * Revision 1.49 2007/05/11 11:48:15 fabiankeil
56 * - Delete strsav() which was replaced
57 * by string_append() years ago.
58 * - Add a strlcat() look-alike.
59 * - Use strlcat() and strlcpy() in those parts
60 * of the code that are run on unixes.
62 * Revision 1.48 2007/04/09 17:48:51 fabiankeil
63 * Check for HAVE_SNPRINTF instead of __OS2__
64 * before including the portable snprintf() code.
66 * Revision 1.47 2007/03/17 11:52:15 fabiankeil
67 * - Use snprintf instead of sprintf.
68 * - Mention copyright for the replacement
69 * functions in the copyright header.
71 * Revision 1.46 2007/01/18 15:03:20 fabiankeil
72 * Don't include replacement timegm() if
73 * putenv() or tzset() isn't available.
75 * Revision 1.45 2006/12/26 17:31:41 fabiankeil
76 * Mutex protect rand() if POSIX threading
77 * is used, warn the user if that's not possible
78 * and stop using it on _WIN32 where it could
81 * Revision 1.44 2006/11/07 12:46:43 fabiankeil
82 * Silence compiler warning on NetBSD 3.1.
84 * Revision 1.43 2006/09/23 13:26:38 roro
85 * Replace TABs by spaces in source code.
87 * Revision 1.42 2006/09/09 14:01:45 fabiankeil
88 * Integrated Oliver Yeoh's domain pattern fix
89 * to make sure *x matches xx. Closes Patch 1217393
92 * Revision 1.41 2006/08/18 16:03:17 david__schmidt
93 * Tweak for OS/2 build happiness.
95 * Revision 1.40 2006/08/17 17:15:10 fabiankeil
96 * - Back to timegm() using GnuPG's replacement if necessary.
97 * Using mktime() and localtime() could add a on hour offset if
98 * the randomize factor was big enough to lead to a summer/wintertime
101 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
103 * - Moved randomization code into pick_from_range().
105 * - Changed parse_header_time definition.
106 * time_t isn't guaranteed to be signed and
107 * if it isn't, -1 isn't available as error code.
108 * Changed some variable types in client_if_modified_since()
109 * because of the same reason.
111 * Revision 1.39 2006/07/18 14:48:46 david__schmidt
112 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
113 * with what was really the latest development (the v_3_0_branch branch)
115 * Revision 1.37.2.4 2003/12/01 14:45:14 oes
116 * Fixed two more problems with wildcarding in simplematch()
118 * Revision 1.37.2.3 2003/11/20 11:39:24 oes
119 * Bugfix: The "?" wildcard for domain names had never been implemented. Ooops\!
121 * Revision 1.37.2.2 2002/11/12 14:28:18 oes
122 * Proper backtracking in simplematch; fixes bug #632888
124 * Revision 1.37.2.1 2002/09/25 12:58:51 oes
125 * Made strcmpic and strncmpic safe against NULL arguments
126 * (which are now treated as empty strings).
128 * Revision 1.37 2002/04/26 18:29:43 jongfoster
129 * Fixing this Visual C++ warning:
130 * miscutil.c(710) : warning C4090: '=' : different 'const' qualifiers
132 * Revision 1.36 2002/04/26 12:55:38 oes
133 * New function string_toupper
135 * Revision 1.35 2002/03/26 22:29:55 swa
136 * we have a new homepage!
138 * Revision 1.34 2002/03/24 13:25:43 swa
139 * name change related issues
141 * Revision 1.33 2002/03/07 03:46:53 oes
142 * Fixed compiler warnings etc
144 * Revision 1.32 2002/03/06 23:02:57 jongfoster
147 * Revision 1.31 2002/03/05 04:52:42 oes
148 * Deleted non-errlog debugging code
150 * Revision 1.30 2002/03/04 18:27:42 oes
151 * - Deleted deletePidFile
152 * - Made write_pid_file use the --pidfile option value
153 * (or no PID file, if the option was absent)
154 * - Played styleguide police
156 * Revision 1.29 2002/03/04 02:08:02 david__schmidt
157 * Enable web editing of actions file on OS/2 (it had been broken all this time!)
159 * Revision 1.28 2002/03/03 09:18:03 joergs
160 * Made jumbjuster work on AmigaOS again.
162 * Revision 1.27 2002/01/21 00:52:32 jongfoster
163 * Adding string_join()
165 * Revision 1.26 2001/12/30 14:07:32 steudten
166 * - Add signal handling (unix)
167 * - Add SIGHUP handler (unix)
168 * - Add creation of pidfile (unix)
169 * - Add action 'top' in rc file (RH)
170 * - Add entry 'SIGNALS' to manpage
171 * - Add exit message to logfile (unix)
173 * Revision 1.25 2001/11/13 00:16:38 jongfoster
174 * Replacing references to malloc.h with the standard stdlib.h
175 * (See ANSI or K&R 2nd Ed)
177 * Revision 1.24 2001/11/05 21:41:43 steudten
178 * Add changes to be a real daemon just for unix os.
179 * (change cwd to /, detach from controlling tty, set
180 * process group and session leader to the own process.
182 * Add some fatal-error log message for failed malloc().
183 * Add '-d' if compiled with 'configure --with-debug' to
184 * enable debug output.
186 * Revision 1.23 2001/10/29 03:48:10 david__schmidt
187 * OS/2 native needed a snprintf() routine. Added one to miscutil, brackedted
188 * by and __OS2__ ifdef.
190 * Revision 1.22 2001/10/26 17:39:38 oes
191 * Moved ijb_isspace and ijb_tolower to project.h
193 * Revision 1.21 2001/10/23 21:27:50 jongfoster
194 * Standardising error codes in string_append
195 * make_path() no longer adds '\\' if the dir already ends in '\\' (this
196 * is just copying a UNIX-specific fix to the Windows-specific part)
198 * Revision 1.20 2001/10/22 15:33:56 david__schmidt
199 * Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
200 * filters.c. Added a FIXME in front of the offending code. I'll gladly
201 * put in a better/more robust fix for all parties if one is presented...
202 * It seems that just returning 200 instead of 404 would pretty much fix
203 * it for everyone, but I don't know all the history of the problem.
205 * Revision 1.19 2001/10/14 22:02:57 jongfoster
206 * New function string_append() which is like strsav(), but running
207 * out of memory isn't automatically FATAL.
209 * Revision 1.18 2001/09/20 13:33:43 steudten
211 * change long to int as return value in hash_string(). Remember the wraparound
212 * for int = long = sizeof(4) - thats maybe not what we want.
214 * Revision 1.17 2001/09/13 20:51:29 jongfoster
215 * Fixing potential problems with characters >=128 in simplematch()
216 * This was also a compiler warning.
218 * Revision 1.16 2001/09/10 10:56:59 oes
219 * Silenced compiler warnings
221 * Revision 1.15 2001/07/13 14:02:24 oes
222 * Removed vim-settings
224 * Revision 1.14 2001/06/29 21:45:41 oes
225 * Indentation, CRLF->LF, Tab-> Space
227 * Revision 1.13 2001/06/29 13:32:14 oes
228 * Removed logentry from cancelled commit
230 * Revision 1.12 2001/06/09 10:55:28 jongfoster
231 * Changing BUFSIZ ==> BUFFER_SIZE
233 * Revision 1.11 2001/06/07 23:09:19 jongfoster
234 * Cosmetic indentation changes.
236 * Revision 1.10 2001/06/07 14:51:38 joergs
237 * make_path() no longer adds '/' if the dir already ends in '/'.
239 * Revision 1.9 2001/06/07 14:43:17 swa
240 * slight mistake in make_path, unix path style is /.
242 * Revision 1.8 2001/06/05 22:32:01 jongfoster
243 * New function make_path() to splice directory and file names together.
245 * Revision 1.7 2001/06/03 19:12:30 oes
246 * introduced bindup()
248 * Revision 1.6 2001/06/01 18:14:49 jongfoster
249 * Changing the calls to strerr() to check HAVE_STRERR (which is defined
250 * in config.h if appropriate) rather than the NO_STRERR macro.
252 * Revision 1.5 2001/06/01 10:31:51 oes
253 * Added character class matching to trivimatch; renamed to simplematch
255 * Revision 1.4 2001/05/31 17:32:31 oes
257 * - Enhanced domain part globbing with infix and prefix asterisk
258 * matching and optional unanchored operation
260 * Revision 1.3 2001/05/29 23:10:09 oes
263 * - Introduced chomp()
264 * - Moved strsav() from showargs to miscutil
266 * Revision 1.2 2001/05/29 09:50:24 jongfoster
267 * Unified blocklist/imagelist/permissionslist.
268 * File format is still under discussion, but the internal changes
271 * Also modified interceptor behaviour:
272 * - We now intercept all URLs beginning with one of the following
273 * prefixes (and *only* these prefixes):
275 * * http://ijbswa.sf.net/config/
276 * * http://ijbswa.sourceforge.net/config/
277 * - New interceptors "home page" - go to http://i.j.b/ to see it.
278 * - Internal changes so that intercepted and fast redirect pages
279 * are not replaced with an image.
280 * - Interceptors now have the option to send a binary page direct
281 * to the client. (i.e. ijb-send-banner uses this)
282 * - Implemented show-url-info interceptor. (Which is why I needed
283 * the above interceptors changes - a typical URL is
284 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
285 * The previous mechanism would not have intercepted that, and
286 * if it had been intercepted then it then it would have replaced
289 * Revision 1.1.1.1 2001/05/15 13:59:00 oes
290 * Initial import of version 2.9.3 source tree
293 *********************************************************************/
299 #include <sys/types.h>
301 #if !defined(_WIN32) && !defined(__OS2__)
303 #endif /* #if !defined(_WIN32) && !defined(__OS2__) */
308 #if !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV)
310 #endif /* !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV) */
313 #include "miscutil.h"
317 const char miscutil_h_rcs[] = MISCUTIL_H_VERSION;
319 /*********************************************************************
323 * Description : Malloc some memory and set it to '\0'.
324 * The way calloc() ought to be -acjc
327 * 1 : size = Size of memory chunk to return.
329 * Returns : Pointer to newly malloc'd memory chunk.
331 *********************************************************************/
332 void *zalloc(size_t size)
336 if ((ret = (void *)malloc(size)) != NULL)
338 memset(ret, 0, size);
347 /*********************************************************************
349 * Function : write_pid_file
351 * Description : Writes a pid file with the pid of the main process
357 *********************************************************************/
358 void write_pid_file(void)
363 * If no --pidfile option was given,
364 * we can live without one.
366 if (pidfile == NULL) return;
368 if ((fp = fopen(pidfile, "w")) == NULL)
370 log_error(LOG_LEVEL_INFO, "can't open pidfile '%s': %E", pidfile);
374 fprintf(fp, "%u\n", (unsigned int) getpid());
380 #endif /* def unix */
383 /*********************************************************************
385 * Function : hash_string
387 * Description : Take a string and compute a (hopefuly) unique numeric
388 * integer value. This has several uses, but being able
389 * to "switch" a string the one of my favorites.
392 * 1 : s : string to be hashed.
394 * Returns : an unsigned long variable with the hashed value.
396 *********************************************************************/
397 unsigned int hash_string( const char* s )
403 h = 5 * h + (unsigned int)*s;
412 /*********************************************************************
416 * Description : For some reason (which is beyond me), gcc and WIN32
417 * don't like strdup. When a "free" is executed on a
418 * strdup'd ptr, it can at times freez up! So I just
419 * replaced it and problem was solved.
422 * 1 : s = string to duplicate
424 * Returns : Pointer to newly malloc'ed copy of the string.
426 *********************************************************************/
427 char *strdup( const char *s )
429 char * result = (char *)malloc( strlen(s)+1 );
439 #endif /* def __MINGW32__ */
443 /*********************************************************************
445 * Function : safe_strerror
447 * Description : Variant of the library routine strerror() which will
448 * work on systems without the library routine, and
449 * which should never return NULL.
452 * 1 : err = the `errno' of the last operation.
454 * Returns : An "English" string of the last `errno'. Allocated
455 * with strdup(), so caller frees. May be NULL if the
456 * system is out of memory.
458 *********************************************************************/
459 char *safe_strerror(int err)
462 char buf[BUFFER_SIZE];
467 #endif /* HAVE_STRERROR */
471 snprintf(buf, sizeof(buf), "(errno = %d)", err);
480 /*********************************************************************
482 * Function : strcmpic
484 * Description : Case insensitive string comparison
487 * 1 : s1 = string 1 to compare
488 * 2 : s2 = string 2 to compare
490 * Returns : 0 if s1==s2, Negative if s1<s2, Positive if s1>s2
492 *********************************************************************/
493 int strcmpic(const char *s1, const char *s2)
500 if ( ( *s1 != *s2 ) && ( ijb_tolower(*s1) != ijb_tolower(*s2) ) )
506 return(ijb_tolower(*s1) - ijb_tolower(*s2));
511 /*********************************************************************
513 * Function : strncmpic
515 * Description : Case insensitive string comparison (upto n characters)
518 * 1 : s1 = string 1 to compare
519 * 2 : s2 = string 2 to compare
520 * 3 : n = maximum characters to compare
522 * Returns : 0 if s1==s2, Negative if s1<s2, Positive if s1>s2
524 *********************************************************************/
525 int strncmpic(const char *s1, const char *s2, size_t n)
527 if (n <= 0) return(0);
533 if ( ( *s1 != *s2 ) && ( ijb_tolower(*s1) != ijb_tolower(*s2) ) )
542 return(ijb_tolower(*s1) - ijb_tolower(*s2));
547 /*********************************************************************
551 * Description : In-situ-eliminate all leading and trailing whitespace
555 * 1 : s : string to be chomped.
557 * Returns : chomped string
559 *********************************************************************/
560 char *chomp(char *string)
565 * strip trailing whitespace
567 p = string + strlen(string);
568 while (p > string && ijb_isspace(*(p-1)))
575 * find end of leading whitespace
578 while (*q && ijb_isspace(*q))
584 * if there was any, move the rest forwards
599 /*********************************************************************
601 * Function : string_append
603 * Description : Reallocate target_string and append text to it.
604 * This makes it easier to append to malloc'd strings.
605 * This is similar to the (removed) strsav(), but
606 * running out of memory isn't catastrophic.
610 * The following style provides sufficient error
611 * checking for this routine, with minimal clutter
612 * in the source code. It is recommended if you
613 * have many calls to this function:
615 * char * s = strdup(...); // don't check for error
616 * string_append(&s, ...); // don't check for error
617 * string_append(&s, ...); // don't check for error
618 * string_append(&s, ...); // don't check for error
619 * if (NULL == s) { ... handle error ... }
623 * char * s = strdup(...); // don't check for error
624 * string_append(&s, ...); // don't check for error
625 * string_append(&s, ...); // don't check for error
626 * if (string_append(&s, ...)) {... handle error ...}
629 * 1 : target_string = Pointer to old text that is to be
630 * extended. *target_string will be free()d by this
631 * routine. target_string must be non-NULL.
632 * If *target_string is NULL, this routine will
633 * do nothing and return with an error - this allows
634 * you to make many calls to this routine and only
635 * check for errors after the last one.
636 * 2 : text_to_append = Text to be appended to old.
639 * Returns : JB_ERR_OK on success, and sets *target_string
640 * to newly malloc'ed appended string. Caller
641 * must free(*target_string).
642 * JB_ERR_MEMORY on out-of-memory. (And free()s
643 * *target_string and sets it to NULL).
644 * JB_ERR_MEMORY if *target_string is NULL.
646 *********************************************************************/
647 jb_err string_append(char **target_string, const char *text_to_append)
653 assert(target_string);
654 assert(text_to_append);
656 if (*target_string == NULL)
658 return JB_ERR_MEMORY;
661 if (*text_to_append == '\0')
666 old_len = strlen(*target_string);
668 new_size = strlen(text_to_append) + old_len + 1;
670 if (NULL == (new_string = realloc(*target_string, new_size)))
672 free(*target_string);
674 *target_string = NULL;
675 return JB_ERR_MEMORY;
678 strlcpy(new_string + old_len, text_to_append, new_size - old_len);
680 *target_string = new_string;
685 /*********************************************************************
687 * Function : string_join
689 * Description : Join two strings together. Frees BOTH the original
690 * strings. If either or both input strings are NULL,
691 * fails as if it had run out of memory.
693 * For comparison, string_append requires that the
694 * second string is non-NULL, and doesn't free it.
696 * Rationale: Too often, we want to do
697 * string_append(s, html_encode(s2)). That assert()s
698 * if s2 is NULL or if html_encode() runs out of memory.
699 * It also leaks memory. Proper checking is cumbersome.
700 * The solution: string_join(s, html_encode(s2)) is safe,
701 * and will free the memory allocated by html_encode().
704 * 1 : target_string = Pointer to old text that is to be
705 * extended. *target_string will be free()d by this
706 * routine. target_string must be non-NULL.
707 * 2 : text_to_append = Text to be appended to old.
709 * Returns : JB_ERR_OK on success, and sets *target_string
710 * to newly malloc'ed appended string. Caller
711 * must free(*target_string).
712 * JB_ERR_MEMORY on out-of-memory, or if
713 * *target_string or text_to_append is NULL. (In
714 * this case, frees *target_string and text_to_append,
715 * sets *target_string to NULL).
717 *********************************************************************/
718 jb_err string_join(char **target_string, char *text_to_append)
722 assert(target_string);
724 if (text_to_append == NULL)
726 freez(*target_string);
727 return JB_ERR_MEMORY;
730 err = string_append(target_string, text_to_append);
732 free(text_to_append);
738 /*********************************************************************
740 * Function : string_toupper
742 * Description : Produce a copy of string with all convertible
743 * characters converted to uppercase.
746 * 1 : string = string to convert
748 * Returns : Uppercase copy of string if possible,
749 * NULL on out-of-memory or if string was NULL.
751 *********************************************************************/
752 char *string_toupper(const char *string)
757 if (!string || ((result = (char *) zalloc(strlen(string) + 1)) == NULL))
767 *p++ = (char)toupper((int) *q++);
775 /*********************************************************************
777 * Function : simplematch
779 * Description : String matching, with a (greedy) '*' wildcard that
780 * stands for zero or more arbitrary characters and
781 * character classes in [], which take both enumerations
785 * 1 : pattern = pattern for matching
786 * 2 : text = text to be matched
788 * Returns : 0 if match, else nonzero
790 *********************************************************************/
791 int simplematch(char *pattern, char *text)
793 unsigned char *pat = (unsigned char *) pattern;
794 unsigned char *txt = (unsigned char *) text;
795 unsigned char *fallback = pat;
798 unsigned char lastchar = 'a';
800 unsigned char charmap[32];
805 /* EOF pattern but !EOF text? */
818 /* '*' in the pattern? */
822 /* The pattern ends afterwards? Speed up the return. */
828 /* Else, set wildcard mode and remember position after '*' */
833 /* Character range specification? */
836 memset(charmap, '\0', sizeof(charmap));
838 while (*++pat != ']')
844 else if (*pat == '-')
846 if ((*++pat == ']') || *pat == '\0')
850 for(i = lastchar; i <= *pat; i++)
852 charmap[i / 8] |= (1 << (i % 8));
857 charmap[*pat / 8] |= (1 << (*pat % 8));
861 } /* -END- if Character range specification */
865 * Char match, or char range match?
869 || ((*pat == ']') && (charmap[*txt / 8] & (1 << (*txt % 8)))) )
879 * No match && no wildcard: No luck
883 else if (pat != fallback)
886 * Increment text pointer if in char range matching
893 * Wildcard mode && nonmatch beyond fallback: Rewind pattern
897 * Restart matching from current text pointer
904 /* Cut off extra '*'s */
905 if(*pat == '*') pat++;
907 /* If this is the pattern's end, fine! */
913 /*********************************************************************
917 * Description : Duplicate the first n characters of a string that may
918 * contain '\0' characters.
921 * 1 : string = string to be duplicated
922 * 2 : len = number of bytes to duplicate
924 * Returns : pointer to copy, or NULL if failiure
926 *********************************************************************/
927 char *bindup(const char *string, size_t len)
931 if (NULL == (duplicate = (char *)malloc(len)))
937 memcpy(duplicate, string, len);
945 /*********************************************************************
947 * Function : make_path
949 * Description : Takes a directory name and a file name, returns
950 * the complete path. Handles windows/unix differences.
951 * If the file name is already an absolute path, or if
952 * the directory name is NULL or empty, it returns
956 * 1 : dir: Name of directory or NULL for none.
957 * 2 : file: Name of file. Should not be NULL or empty.
959 * Returns : "dir/file" (Or on windows, "dir\file").
960 * It allocates the string on the heap. Caller frees.
961 * Returns NULL in error (i.e. NULL file or out of
964 *********************************************************************/
965 char * make_path(const char * dir, const char * file)
976 strncpy(path,dir+2,512);
980 strncpy(path,dir+1,512);
985 strncpy(path,dir,512);
993 if(AddPart(path,file,512))
1001 #else /* ndef AMIGA */
1003 if ((file == NULL) || (*file == '\0'))
1005 return NULL; /* Error */
1008 if ((dir == NULL) || (*dir == '\0') /* No directory specified */
1009 #if defined(_WIN32) || defined(__OS2__)
1010 || (*file == '\\') || (file[1] == ':') /* Absolute path (DOS) */
1011 #else /* ifndef _WIN32 || __OS2__ */
1012 || (*file == '/') /* Absolute path (U*ix) */
1013 #endif /* ifndef _WIN32 || __OS2__ */
1016 return strdup(file);
1021 size_t path_size = strlen(dir) + strlen(file) + 2; /* +2 for trailing (back)slash and \0 */
1024 if ( *dir != '/' && basedir && *basedir )
1027 * Relative path, so start with the base directory.
1029 path_size += strlen(basedir) + 1; /* +1 for the slash */
1030 path = malloc(path_size);
1031 if (!path ) log_error(LOG_LEVEL_FATAL, "malloc failed!");
1032 strlcpy(path, basedir, path_size);
1033 strlcat(path, "/", path_size);
1034 strlcat(path, dir, path_size);
1037 #endif /* defined unix */
1039 path = malloc(path_size);
1040 if (!path ) log_error(LOG_LEVEL_FATAL, "malloc failed!");
1041 strlcpy(path, dir, path_size);
1044 #if defined(_WIN32) || defined(__OS2__)
1045 if(path[strlen(path)-1] != '\\')
1047 strlcat(path, "\\", path_size);
1049 #else /* ifndef _WIN32 || __OS2__ */
1050 if(path[strlen(path)-1] != '/')
1052 strlcat(path, "/", path_size);
1054 #endif /* ifndef _WIN32 || __OS2__ */
1055 strlcat(path, file, path_size);
1059 #endif /* ndef AMIGA */
1063 /*********************************************************************
1065 * Function : pick_from_range
1067 * Description : Pick a positive number out of a given range.
1068 * Should only be used if randomness would be nice,
1069 * but isn't really necessary.
1072 * 1 : range: Highest possible number to pick.
1074 * Returns : Picked number.
1076 *********************************************************************/
1077 long int pick_from_range(long int range)
1081 number = random() % range + 1;
1082 #elif defined(FEATURE_PTHREAD)
1083 pthread_mutex_lock(&rand_mutex);
1084 number = rand() % (long int)(range + 1);
1085 pthread_mutex_unlock(&rand_mutex);
1089 * On Windows and mingw32 srand() has to be called in every
1090 * rand()-using thread, but can cause crashes if it's not
1093 * Currently we don't have mutexes for mingw32, and for
1094 * our purpose this cludge is probably preferable to crashes.
1096 log_error(LOG_LEVEL_INFO, "No thread-safe PRNG available? Using weak \'randomization\' factor.");
1097 number = (range + GetCurrentThreadId() % range) / 2;
1100 * XXX: Which platforms reach this and are there
1101 * better options than just using rand() and hoping
1104 log_error(LOG_LEVEL_INFO, "No thread-safe PRNG available? Header time randomization might cause "
1105 "crashes, predictable results or even combine these fine options.");
1106 number = rand() % (long int)(range + 1);
1107 #endif /* def _WIN32 */
1109 #endif /* (def HAVE_RANDOM) */
1115 #ifndef HAVE_STRLCAT
1116 /*********************************************************************
1118 * Function : privoxy_strlcat
1120 * Description : strlcat(3) look-alike for those without decent libc.
1123 * 1 : destination: C string.
1124 * 2 : source: String to copy.
1125 * 3 : size: Size of destination buffer.
1127 * Returns : The length of the string that strlcat tried to create.
1129 *********************************************************************/
1130 size_t privoxy_strlcat(char *destination, const char *source, const size_t size)
1132 const size_t old_length = strlen(destination);
1133 return old_length + strlcpy(destination + old_length, source, size - old_length);
1135 #endif /* ndef HAVE_STRLCAT */
1138 #if !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV)
1139 /*********************************************************************
1143 * Description : libc replacement function for the inverse of gmtime().
1144 * Copyright (C) 2004 Free Software Foundation, Inc.
1146 * Code originally copied from GnuPG, modifications done
1147 * for Privoxy: style changed, #ifdefs for _WIN32 added
1148 * to have it work on mingw32.
1150 * XXX: It's very unlikely to happen, but if the malloc()
1151 * call fails the time zone will be permanently set to UTC.
1154 * 1 : tm: Broken-down time struct.
1156 * Returns : tm converted into time_t seconds.
1158 *********************************************************************/
1159 time_t timegm(struct tm *tm)
1164 zone = getenv("TZ");
1167 answer = mktime(tm);
1172 old_zone = malloc(3 + strlen(zone) + 1);
1175 strcpy(old_zone, "TZ=");
1176 strcat(old_zone, zone);
1180 #endif /* def _WIN32 */
1185 #ifdef HAVE_UNSETENV
1187 #elif defined(_WIN32)
1197 #endif /* !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV) */
1200 #ifndef HAVE_SNPRINTF
1202 * What follows is a portable snprintf routine, written by Mark Martinec.
1203 * See: http://www.ijs.si/software/snprintf/
1206 - a portable implementation of snprintf,
1207 including vsnprintf.c, asnprintf, vasnprintf, asprintf, vasprintf
1209 snprintf is a routine to convert numeric and string arguments to
1210 formatted strings. It is similar to sprintf(3) provided in a system's
1211 C library, yet it requires an additional argument - the buffer size -
1212 and it guarantees never to store anything beyond the given buffer,
1213 regardless of the format or arguments to be formatted. Some newer
1214 operating systems do provide snprintf in their C library, but many do
1215 not or do provide an inadequate (slow or idiosyncratic) version, which
1216 calls for a portable implementation of this routine.
1220 Mark Martinec <mark.martinec@ijs.si>, April 1999, June 2000
1221 Copyright © 1999, Mark Martinec
1225 #define PORTABLE_SNPRINTF_VERSION_MAJOR 2
1226 #define PORTABLE_SNPRINTF_VERSION_MINOR 2
1228 #if defined(NEED_ASPRINTF) || defined(NEED_ASNPRINTF) || defined(NEED_VASPRINTF) || defined(NEED_VASNPRINTF)
1229 # if defined(NEED_SNPRINTF_ONLY)
1230 # undef NEED_SNPRINTF_ONLY
1232 # if !defined(PREFER_PORTABLE_SNPRINTF)
1233 # define PREFER_PORTABLE_SNPRINTF
1237 #if defined(SOLARIS_BUG_COMPATIBLE) && !defined(SOLARIS_COMPATIBLE)
1238 #define SOLARIS_COMPATIBLE
1241 #if defined(HPUX_BUG_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
1242 #define HPUX_COMPATIBLE
1245 #if defined(DIGITAL_UNIX_BUG_COMPATIBLE) && !defined(DIGITAL_UNIX_COMPATIBLE)
1246 #define DIGITAL_UNIX_COMPATIBLE
1249 #if defined(PERL_BUG_COMPATIBLE) && !defined(PERL_COMPATIBLE)
1250 #define PERL_COMPATIBLE
1253 #if defined(LINUX_BUG_COMPATIBLE) && !defined(LINUX_COMPATIBLE)
1254 #define LINUX_COMPATIBLE
1257 #include <sys/types.h>
1268 #define isdigit(c) ((c) >= '0' && (c) <= '9')
1270 /* For copying strings longer or equal to 'breakeven_point'
1271 * it is more efficient to call memcpy() than to do it inline.
1272 * The value depends mostly on the processor architecture,
1273 * but also on the compiler and its optimization capabilities.
1274 * The value is not critical, some small value greater than zero
1275 * will be just fine if you don't care to squeeze every drop
1276 * of performance out of the code.
1278 * Small values favor memcpy, large values favor inline code.
1280 #if defined(__alpha__) || defined(__alpha)
1281 # define breakeven_point 2 /* AXP (DEC Alpha) - gcc or cc or egcs */
1283 #if defined(__i386__) || defined(__i386)
1284 # define breakeven_point 12 /* Intel Pentium/Linux - gcc 2.96 */
1287 # define breakeven_point 10 /* HP-PA - gcc */
1289 #if defined(__sparc__) || defined(__sparc)
1290 # define breakeven_point 33 /* Sun Sparc 5 - gcc 2.8.1 */
1293 /* some other values of possible interest: */
1294 /* #define breakeven_point 8 */ /* VAX 4000 - vaxc */
1295 /* #define breakeven_point 19 */ /* VAX 4000 - gcc 2.7.0 */
1297 #ifndef breakeven_point
1298 # define breakeven_point 6 /* some reasonable one-size-fits-all value */
1301 #define fast_memcpy(d,s,n) \
1302 { register size_t nn = (size_t)(n); \
1303 if (nn >= breakeven_point) memcpy((d), (s), nn); \
1304 else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
1305 register char *dd; register const char *ss; \
1306 for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } }
1308 #define fast_memset(d,c,n) \
1309 { register size_t nn = (size_t)(n); \
1310 if (nn >= breakeven_point) memset((d), (int)(c), nn); \
1311 else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
1312 register char *dd; register const int cc=(int)(c); \
1313 for (dd=(d); nn>0; nn--) *dd++ = cc; } }
1317 #if defined(NEED_ASPRINTF)
1318 int asprintf (char **ptr, const char *fmt, /*args*/ ...);
1320 #if defined(NEED_VASPRINTF)
1321 int vasprintf (char **ptr, const char *fmt, va_list ap);
1323 #if defined(NEED_ASNPRINTF)
1324 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...);
1326 #if defined(NEED_VASNPRINTF)
1327 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap);
1330 #if defined(HAVE_SNPRINTF)
1331 /* declare our portable snprintf routine under name portable_snprintf */
1332 /* declare our portable vsnprintf routine under name portable_vsnprintf */
1334 /* declare our portable routines under names snprintf and vsnprintf */
1335 #define portable_snprintf snprintf
1336 #if !defined(NEED_SNPRINTF_ONLY)
1337 #define portable_vsnprintf vsnprintf
1341 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1342 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...);
1343 #if !defined(NEED_SNPRINTF_ONLY)
1344 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap);
1350 static char credits[] = "\n\
1351 @(#)snprintf.c, v2.2: Mark Martinec, <mark.martinec@ijs.si>\n\
1352 @(#)snprintf.c, v2.2: Copyright 1999, Mark Martinec. Frontier Artistic License applies.\n\
1353 @(#)snprintf.c, v2.2: http://www.ijs.si/software/snprintf/\n";
1355 #if defined(NEED_ASPRINTF)
1356 int asprintf(char **ptr, const char *fmt, /*args*/ ...) {
1362 va_start(ap, fmt); /* measure the required size */
1363 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
1365 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1366 *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
1367 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1371 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1373 assert(str_l2 == str_l);
1379 #if defined(NEED_VASPRINTF)
1380 int vasprintf(char **ptr, const char *fmt, va_list ap) {
1386 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
1387 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1390 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1391 *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
1392 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1394 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1395 assert(str_l2 == str_l);
1401 #if defined(NEED_ASNPRINTF)
1402 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...) {
1407 va_start(ap, fmt); /* measure the required size */
1408 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
1410 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1411 if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1; /* truncate */
1412 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1413 if (str_m == 0) { /* not interested in resulting string, just return size */
1415 *ptr = (char *) malloc(str_m);
1416 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1420 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1422 assert(str_l2 == str_l);
1429 #if defined(NEED_VASNPRINTF)
1430 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap) {
1435 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
1436 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1439 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1440 if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1; /* truncate */
1441 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1442 if (str_m == 0) { /* not interested in resulting string, just return size */
1444 *ptr = (char *) malloc(str_m);
1445 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1447 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1448 assert(str_l2 == str_l);
1456 * If the system does have snprintf and the portable routine is not
1457 * specifically required, this module produces no code for snprintf/vsnprintf.
1459 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1461 #if !defined(NEED_SNPRINTF_ONLY)
1462 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1467 str_l = portable_vsnprintf(str, str_m, fmt, ap);
1473 #if defined(NEED_SNPRINTF_ONLY)
1474 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1476 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) {
1479 #if defined(NEED_SNPRINTF_ONLY)
1483 const char *p = fmt;
1485 /* In contrast with POSIX, the ISO C99 now says
1486 * that str can be NULL and str_m can be 0.
1487 * This is more useful than the old: if (str_m < 1) return -1; */
1489 #if defined(NEED_SNPRINTF_ONLY)
1495 /* if (str_l < str_m) str[str_l++] = *p++; -- this would be sufficient */
1496 /* but the following code achieves better performance for cases
1497 * where format string is long and contains few conversions */
1498 const char *q = strchr(p+1,'%');
1499 size_t n = !q ? strlen(p) : (q-p);
1500 if (str_l < str_m) {
1501 size_t avail = str_m-str_l;
1502 fast_memcpy(str+str_l, p, (n>avail?avail:n));
1506 const char *starting_p;
1507 size_t min_field_width = 0, precision = 0;
1508 int zero_padding = 0, precision_specified = 0, justify_left = 0;
1509 int alternate_form = 0, force_sign = 0;
1510 int space_for_positive = 1; /* If both the ' ' and '+' flags appear,
1511 the ' ' flag should be ignored. */
1512 char length_modifier = '\0'; /* allowed values: \0, h, l, L */
1513 char tmp[32];/* temporary buffer for simple numeric->string conversion */
1515 const char *str_arg; /* string address in case of string argument */
1516 size_t str_arg_l; /* natural field width of arg without padding
1518 unsigned char uchar_arg;
1519 /* unsigned char argument value - only defined for c conversion.
1520 N.B. standard explicitly states the char argument for
1521 the c conversion is unsigned */
1523 size_t number_of_zeros_to_pad = 0;
1524 /* number of zeros to be inserted for numeric conversions
1525 as required by the precision or minimal field width */
1527 size_t zero_padding_insertion_ind = 0;
1528 /* index into tmp where zero padding is to be inserted */
1530 char fmt_spec = '\0';
1531 /* current conversion specifier character */
1533 str_arg = credits;/* just to make compiler happy (defined but not used)*/
1535 starting_p = p; p++; /* skip '%' */
1537 while (*p == '0' || *p == '-' || *p == '+' ||
1538 *p == ' ' || *p == '#' || *p == '\'') {
1540 case '0': zero_padding = 1; break;
1541 case '-': justify_left = 1; break;
1542 case '+': force_sign = 1; space_for_positive = 0; break;
1543 case ' ': force_sign = 1;
1544 /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */
1545 #ifdef PERL_COMPATIBLE
1546 /* ... but in Perl the last of ' ' and '+' applies */
1547 space_for_positive = 1;
1550 case '#': alternate_form = 1; break;
1555 /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
1557 /* parse field width */
1560 p++; j = va_arg(ap, int);
1561 if (j >= 0) min_field_width = j;
1562 else { min_field_width = -j; justify_left = 1; }
1563 } else if (isdigit((int)(*p))) {
1564 /* size_t could be wider than unsigned int;
1565 make sure we treat argument like common implementations do */
1566 unsigned int uj = *p++ - '0';
1567 while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1568 min_field_width = uj;
1570 /* parse precision */
1572 p++; precision_specified = 1;
1574 int j = va_arg(ap, int);
1576 if (j >= 0) precision = j;
1578 precision_specified = 0; precision = 0;
1580 * Solaris 2.6 man page claims that in this case the precision
1581 * should be set to 0. Digital Unix 4.0, HPUX 10 and BSD man page
1582 * claim that this case should be treated as unspecified precision,
1583 * which is what we do here.
1586 } else if (isdigit((int)(*p))) {
1587 /* size_t could be wider than unsigned int;
1588 make sure we treat argument like common implementations do */
1589 unsigned int uj = *p++ - '0';
1590 while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1594 /* parse 'h', 'l' and 'll' length modifiers */
1595 if (*p == 'h' || *p == 'l') {
1596 length_modifier = *p; p++;
1597 if (length_modifier == 'l' && *p == 'l') { /* double l = long long */
1598 #ifdef SNPRINTF_LONGLONG_SUPPORT
1599 length_modifier = '2'; /* double l encoded as '2' */
1601 length_modifier = 'l'; /* treat it as a single 'l' */
1607 /* common synonyms: */
1609 case 'i': fmt_spec = 'd'; break;
1610 case 'D': fmt_spec = 'd'; length_modifier = 'l'; break;
1611 case 'U': fmt_spec = 'u'; length_modifier = 'l'; break;
1612 case 'O': fmt_spec = 'o'; length_modifier = 'l'; break;
1615 /* get parameter value, do initial processing */
1617 case '%': /* % behaves similar to 's' regarding flags and field widths */
1618 case 'c': /* c behaves similar to 's' regarding flags and field widths */
1620 length_modifier = '\0'; /* wint_t and wchar_t not supported */
1621 /* the result of zero padding flag with non-numeric conversion specifier*/
1622 /* is undefined. Solaris and HPUX 10 does zero padding in this case, */
1623 /* Digital Unix and Linux does not. */
1624 #if !defined(SOLARIS_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
1625 zero_padding = 0; /* turn zero padding off for string conversions */
1632 int j = va_arg(ap, int);
1633 uchar_arg = (unsigned char) j; /* standard demands unsigned char */
1634 str_arg = (const char *) &uchar_arg;
1638 str_arg = va_arg(ap, const char *);
1639 if (!str_arg) str_arg_l = 0;
1640 /* make sure not to address string beyond the specified precision !!! */
1641 else if (!precision_specified) str_arg_l = strlen(str_arg);
1642 /* truncate string if necessary as requested by precision */
1643 else if (precision == 0) str_arg_l = 0;
1645 /* memchr on HP does not like n > 2^31 !!! */
1646 const char *q = memchr(str_arg, '\0',
1647 precision <= 0x7fffffff ? precision : 0x7fffffff);
1648 str_arg_l = !q ? precision : (q-str_arg);
1654 case 'd': case 'u': case 'o': case 'x': case 'X': case 'p': {
1655 /* NOTE: the u, o, x, X and p conversion specifiers imply
1656 the value is unsigned; d implies a signed value */
1659 /* 0 if numeric argument is zero (or if pointer is NULL for 'p'),
1660 +1 if greater than zero (or nonzero for unsigned arguments),
1661 -1 if negative (unsigned argument is never negative) */
1663 int int_arg = 0; unsigned int uint_arg = 0;
1664 /* only defined for length modifier h, or for no length modifiers */
1666 long int long_arg = 0; unsigned long int ulong_arg = 0;
1667 /* only defined for length modifier l */
1669 void *ptr_arg = NULL;
1670 /* pointer argument value -only defined for p conversion */
1672 #ifdef SNPRINTF_LONGLONG_SUPPORT
1673 long long int long_long_arg = 0;
1674 unsigned long long int ulong_long_arg = 0;
1675 /* only defined for length modifier ll */
1677 if (fmt_spec == 'p') {
1678 /* HPUX 10: An l, h, ll or L before any other conversion character
1679 * (other than d, i, u, o, x, or X) is ignored.
1681 * not specified, but seems to behave as HPUX does.
1682 * Solaris: If an h, l, or L appears before any other conversion
1683 * specifier (other than d, i, u, o, x, or X), the behavior
1684 * is undefined. (Actually %hp converts only 16-bits of address
1685 * and %llp treats address as 64-bit data which is incompatible
1686 * with (void *) argument on a 32-bit system).
1688 #ifdef SOLARIS_COMPATIBLE
1689 # ifdef SOLARIS_BUG_COMPATIBLE
1690 /* keep length modifiers even if it represents 'll' */
1692 if (length_modifier == '2') length_modifier = '\0';
1695 length_modifier = '\0';
1697 ptr_arg = va_arg(ap, void *);
1698 if (ptr_arg != NULL) arg_sign = 1;
1699 } else if (fmt_spec == 'd') { /* signed */
1700 switch (length_modifier) {
1703 /* It is non-portable to specify a second argument of char or short
1704 * to va_arg, because arguments seen by the called function
1705 * are not char or short. C converts char and short arguments
1706 * to int before passing them to a function.
1708 int_arg = va_arg(ap, int);
1709 if (int_arg > 0) arg_sign = 1;
1710 else if (int_arg < 0) arg_sign = -1;
1713 long_arg = va_arg(ap, long int);
1714 if (long_arg > 0) arg_sign = 1;
1715 else if (long_arg < 0) arg_sign = -1;
1717 #ifdef SNPRINTF_LONGLONG_SUPPORT
1719 long_long_arg = va_arg(ap, long long int);
1720 if (long_long_arg > 0) arg_sign = 1;
1721 else if (long_long_arg < 0) arg_sign = -1;
1725 } else { /* unsigned */
1726 switch (length_modifier) {
1729 uint_arg = va_arg(ap, unsigned int);
1730 if (uint_arg) arg_sign = 1;
1733 ulong_arg = va_arg(ap, unsigned long int);
1734 if (ulong_arg) arg_sign = 1;
1736 #ifdef SNPRINTF_LONGLONG_SUPPORT
1738 ulong_long_arg = va_arg(ap, unsigned long long int);
1739 if (ulong_long_arg) arg_sign = 1;
1744 str_arg = tmp; str_arg_l = 0;
1746 * For d, i, u, o, x, and X conversions, if precision is specified,
1747 * the '0' flag should be ignored. This is so with Solaris 2.6,
1748 * Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl.
1750 #ifndef PERL_COMPATIBLE
1751 if (precision_specified) zero_padding = 0;
1753 if (fmt_spec == 'd') {
1754 if (force_sign && arg_sign >= 0)
1755 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1756 /* leave negative numbers for sprintf to handle,
1757 to avoid handling tricky cases like (short int)(-32768) */
1758 #ifdef LINUX_COMPATIBLE
1759 } else if (fmt_spec == 'p' && force_sign && arg_sign > 0) {
1760 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1762 } else if (alternate_form) {
1763 if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X') )
1764 { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = fmt_spec; }
1765 /* alternate form should have no effect for p conversion, but ... */
1766 #ifdef HPUX_COMPATIBLE
1767 else if (fmt_spec == 'p'
1768 /* HPUX 10: for an alternate form of p conversion,
1769 * a nonzero result is prefixed by 0x. */
1770 #ifndef HPUX_BUG_COMPATIBLE
1771 /* Actually it uses 0x prefix even for a zero value. */
1774 ) { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = 'x'; }
1777 zero_padding_insertion_ind = str_arg_l;
1778 if (!precision_specified) precision = 1; /* default precision is 1 */
1779 if (precision == 0 && arg_sign == 0
1780 #if defined(HPUX_BUG_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1782 /* HPUX 10 man page claims: With conversion character p the result of
1783 * converting a zero value with a precision of zero is a null string.
1784 * Actually HP returns all zeroes, and Linux returns "(nil)". */
1787 /* converted to null string */
1788 /* When zero value is formatted with an explicit precision 0,
1789 the resulting formatted string is empty (d, i, u, o, x, X, p). */
1791 char f[5]; int f_l = 0;
1792 f[f_l++] = '%'; /* construct a simple format string for sprintf */
1793 if (!length_modifier) { }
1794 else if (length_modifier=='2') { f[f_l++] = 'l'; f[f_l++] = 'l'; }
1795 else f[f_l++] = length_modifier;
1796 f[f_l++] = fmt_spec; f[f_l++] = '\0';
1797 if (fmt_spec == 'p') str_arg_l += sprintf(tmp+str_arg_l, f, ptr_arg);
1798 else if (fmt_spec == 'd') { /* signed */
1799 switch (length_modifier) {
1801 case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, int_arg); break;
1802 case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, long_arg); break;
1803 #ifdef SNPRINTF_LONGLONG_SUPPORT
1804 case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,long_long_arg); break;
1807 } else { /* unsigned */
1808 switch (length_modifier) {
1810 case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, uint_arg); break;
1811 case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, ulong_arg); break;
1812 #ifdef SNPRINTF_LONGLONG_SUPPORT
1813 case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,ulong_long_arg);break;
1817 /* include the optional minus sign and possible "0x"
1818 in the region before the zero padding insertion point */
1819 if (zero_padding_insertion_ind < str_arg_l &&
1820 tmp[zero_padding_insertion_ind] == '-') {
1821 zero_padding_insertion_ind++;
1823 if (zero_padding_insertion_ind+1 < str_arg_l &&
1824 tmp[zero_padding_insertion_ind] == '0' &&
1825 (tmp[zero_padding_insertion_ind+1] == 'x' ||
1826 tmp[zero_padding_insertion_ind+1] == 'X') ) {
1827 zero_padding_insertion_ind += 2;
1830 { size_t num_of_digits = str_arg_l - zero_padding_insertion_ind;
1831 if (alternate_form && fmt_spec == 'o'
1832 #ifdef HPUX_COMPATIBLE /* ("%#.o",0) -> "" */
1835 #ifdef DIGITAL_UNIX_BUG_COMPATIBLE /* ("%#o",0) -> "00" */
1837 /* unless zero is already the first character */
1838 && !(zero_padding_insertion_ind < str_arg_l
1839 && tmp[zero_padding_insertion_ind] == '0')
1841 ) { /* assure leading zero for alternate-form octal numbers */
1842 if (!precision_specified || precision < num_of_digits+1) {
1843 /* precision is increased to force the first character to be zero,
1844 except if a zero value is formatted with an explicit precision
1846 precision = num_of_digits+1; precision_specified = 1;
1849 /* zero padding to specified precision? */
1850 if (num_of_digits < precision)
1851 number_of_zeros_to_pad = precision - num_of_digits;
1853 /* zero padding to specified minimal field width? */
1854 if (!justify_left && zero_padding) {
1855 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1856 if (n > 0) number_of_zeros_to_pad += n;
1860 default: /* unrecognized conversion specifier, keep format string as-is*/
1861 zero_padding = 0; /* turn zero padding off for non-numeric convers. */
1862 #ifndef DIGITAL_UNIX_COMPATIBLE
1863 justify_left = 1; min_field_width = 0; /* reset flags */
1865 #if defined(PERL_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1866 /* keep the entire format string unchanged */
1867 str_arg = starting_p; str_arg_l = p - starting_p;
1868 /* well, not exactly so for Linux, which does something inbetween,
1869 * and I don't feel an urge to imitate it: "%+++++hy" -> "%+y" */
1871 /* discard the unrecognized conversion, just keep *
1872 * the unrecognized conversion character */
1873 str_arg = p; str_arg_l = 0;
1875 if (*p) str_arg_l++; /* include invalid conversion specifier unchanged
1876 if not at end-of-string */
1879 if (*p) p++; /* step over the just processed conversion specifier */
1880 /* insert padding to the left as requested by min_field_width;
1881 this does not include the zero padding in case of numerical conversions*/
1882 if (!justify_left) { /* left padding with blank or zero */
1883 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1885 if (str_l < str_m) {
1886 size_t avail = str_m-str_l;
1887 fast_memset(str+str_l, (zero_padding?'0':' '), (n>avail?avail:n));
1892 /* zero padding as requested by the precision or by the minimal field width
1893 * for numeric conversions required? */
1894 if (number_of_zeros_to_pad <= 0) {
1895 /* will not copy first part of numeric right now, *
1896 * force it to be copied later in its entirety */
1897 zero_padding_insertion_ind = 0;
1899 /* insert first part of numerics (sign or '0x') before zero padding */
1900 int n = zero_padding_insertion_ind;
1902 if (str_l < str_m) {
1903 size_t avail = str_m-str_l;
1904 fast_memcpy(str+str_l, str_arg, (n>avail?avail:n));
1908 /* insert zero padding as requested by the precision or min field width */
1909 n = number_of_zeros_to_pad;
1911 if (str_l < str_m) {
1912 size_t avail = str_m-str_l;
1913 fast_memset(str+str_l, '0', (n>avail?avail:n));
1918 /* insert formatted string
1919 * (or as-is conversion specifier for unknown conversions) */
1920 { int n = str_arg_l - zero_padding_insertion_ind;
1922 if (str_l < str_m) {
1923 size_t avail = str_m-str_l;
1924 fast_memcpy(str+str_l, str_arg+zero_padding_insertion_ind,
1930 /* insert right padding */
1931 if (justify_left) { /* right blank padding to the field width */
1932 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1934 if (str_l < str_m) {
1935 size_t avail = str_m-str_l;
1936 fast_memset(str+str_l, ' ', (n>avail?avail:n));
1943 #if defined(NEED_SNPRINTF_ONLY)
1946 if (str_m > 0) { /* make sure the string is null-terminated
1947 even at the expense of overwriting the last character
1948 (shouldn't happen, but just in case) */
1949 str[str_l <= str_m-1 ? str_l : str_m-1] = '\0';
1951 /* Return the number of characters formatted (excluding trailing null
1952 * character), that is, the number of characters that would have been
1953 * written to the buffer if it were large enough.
1955 * The value of str_l should be returned, but str_l is of unsigned type
1956 * size_t, and snprintf is int, possibly leading to an undetected
1957 * integer overflow, resulting in a negative return value, which is illegal.
1958 * Both XSH5 and ISO C99 (at least the draft) are silent on this issue.
1959 * Should errno be set to EOVERFLOW and EOF returned in this case???
1964 #endif /* ndef HAVE_SNPRINTF */