1 const char miscutil_rcs[] = "$Id: miscutil.c,v 1.62 2008/12/04 18:16:41 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.
45 *********************************************************************/
51 #include <sys/types.h>
53 #if !defined(_WIN32) && !defined(__OS2__)
55 #endif /* #if !defined(_WIN32) && !defined(__OS2__) */
60 #if !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV)
62 #endif /* !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV) */
69 const char miscutil_h_rcs[] = MISCUTIL_H_VERSION;
71 /*********************************************************************
75 * Description : Malloc some memory and set it to '\0'.
76 * The way calloc() ought to be -acjc
79 * 1 : size = Size of memory chunk to return.
81 * Returns : Pointer to newly malloc'd memory chunk.
83 *********************************************************************/
84 void *zalloc(size_t size)
88 if ((ret = (void *)malloc(size)) != NULL)
99 /*********************************************************************
101 * Function : write_pid_file
103 * Description : Writes a pid file with the pid of the main process
109 *********************************************************************/
110 void write_pid_file(void)
115 * If no --pidfile option was given,
116 * we can live without one.
118 if (pidfile == NULL) return;
120 if ((fp = fopen(pidfile, "w")) == NULL)
122 log_error(LOG_LEVEL_INFO, "can't open pidfile '%s': %E", pidfile);
126 fprintf(fp, "%u\n", (unsigned int) getpid());
132 #endif /* def unix */
135 /*********************************************************************
137 * Function : hash_string
139 * Description : Take a string and compute a (hopefuly) unique numeric
140 * integer value. This has several uses, but being able
141 * to "switch" a string the one of my favorites.
144 * 1 : s : string to be hashed.
146 * Returns : an unsigned long variable with the hashed value.
148 *********************************************************************/
149 unsigned int hash_string( const char* s )
155 h = 5 * h + (unsigned int)*s;
164 /*********************************************************************
168 * Description : For some reason (which is beyond me), gcc and WIN32
169 * don't like strdup. When a "free" is executed on a
170 * strdup'd ptr, it can at times freez up! So I just
171 * replaced it and problem was solved.
174 * 1 : s = string to duplicate
176 * Returns : Pointer to newly malloc'ed copy of the string.
178 *********************************************************************/
179 char *strdup( const char *s )
181 char * result = (char *)malloc( strlen(s)+1 );
191 #endif /* def __MINGW32__ */
195 /*********************************************************************
197 * Function : safe_strerror
199 * Description : Variant of the library routine strerror() which will
200 * work on systems without the library routine, and
201 * which should never return NULL.
204 * 1 : err = the `errno' of the last operation.
206 * Returns : An "English" string of the last `errno'. Allocated
207 * with strdup(), so caller frees. May be NULL if the
208 * system is out of memory.
210 *********************************************************************/
211 char *safe_strerror(int err)
214 char buf[BUFFER_SIZE];
219 #endif /* HAVE_STRERROR */
223 snprintf(buf, sizeof(buf), "(errno = %d)", err);
232 /*********************************************************************
234 * Function : strcmpic
236 * Description : Case insensitive string comparison
239 * 1 : s1 = string 1 to compare
240 * 2 : s2 = string 2 to compare
242 * Returns : 0 if s1==s2, Negative if s1<s2, Positive if s1>s2
244 *********************************************************************/
245 int strcmpic(const char *s1, const char *s2)
252 if ( ( *s1 != *s2 ) && ( ijb_tolower(*s1) != ijb_tolower(*s2) ) )
258 return(ijb_tolower(*s1) - ijb_tolower(*s2));
263 /*********************************************************************
265 * Function : strncmpic
267 * Description : Case insensitive string comparison (upto n characters)
270 * 1 : s1 = string 1 to compare
271 * 2 : s2 = string 2 to compare
272 * 3 : n = maximum characters to compare
274 * Returns : 0 if s1==s2, Negative if s1<s2, Positive if s1>s2
276 *********************************************************************/
277 int strncmpic(const char *s1, const char *s2, size_t n)
279 if (n <= (size_t)0) return(0);
285 if ( ( *s1 != *s2 ) && ( ijb_tolower(*s1) != ijb_tolower(*s2) ) )
290 if (--n <= (size_t)0) break;
294 return(ijb_tolower(*s1) - ijb_tolower(*s2));
299 /*********************************************************************
303 * Description : In-situ-eliminate all leading and trailing whitespace
307 * 1 : s : string to be chomped.
309 * Returns : chomped string
311 *********************************************************************/
312 char *chomp(char *string)
317 * strip trailing whitespace
319 p = string + strlen(string);
320 while (p > string && ijb_isspace(*(p-1)))
327 * find end of leading whitespace
330 while (*q && ijb_isspace(*q))
336 * if there was any, move the rest forwards
351 /*********************************************************************
353 * Function : string_append
355 * Description : Reallocate target_string and append text to it.
356 * This makes it easier to append to malloc'd strings.
357 * This is similar to the (removed) strsav(), but
358 * running out of memory isn't catastrophic.
362 * The following style provides sufficient error
363 * checking for this routine, with minimal clutter
364 * in the source code. It is recommended if you
365 * have many calls to this function:
367 * char * s = strdup(...); // don't check for error
368 * string_append(&s, ...); // don't check for error
369 * string_append(&s, ...); // don't check for error
370 * string_append(&s, ...); // don't check for error
371 * if (NULL == s) { ... handle error ... }
375 * char * s = strdup(...); // don't check for error
376 * string_append(&s, ...); // don't check for error
377 * string_append(&s, ...); // don't check for error
378 * if (string_append(&s, ...)) {... handle error ...}
381 * 1 : target_string = Pointer to old text that is to be
382 * extended. *target_string will be free()d by this
383 * routine. target_string must be non-NULL.
384 * If *target_string is NULL, this routine will
385 * do nothing and return with an error - this allows
386 * you to make many calls to this routine and only
387 * check for errors after the last one.
388 * 2 : text_to_append = Text to be appended to old.
391 * Returns : JB_ERR_OK on success, and sets *target_string
392 * to newly malloc'ed appended string. Caller
393 * must free(*target_string).
394 * JB_ERR_MEMORY on out-of-memory. (And free()s
395 * *target_string and sets it to NULL).
396 * JB_ERR_MEMORY if *target_string is NULL.
398 *********************************************************************/
399 jb_err string_append(char **target_string, const char *text_to_append)
405 assert(target_string);
406 assert(text_to_append);
408 if (*target_string == NULL)
410 return JB_ERR_MEMORY;
413 if (*text_to_append == '\0')
418 old_len = strlen(*target_string);
420 new_size = strlen(text_to_append) + old_len + 1;
422 if (NULL == (new_string = realloc(*target_string, new_size)))
424 free(*target_string);
426 *target_string = NULL;
427 return JB_ERR_MEMORY;
430 strlcpy(new_string + old_len, text_to_append, new_size - old_len);
432 *target_string = new_string;
437 /*********************************************************************
439 * Function : string_join
441 * Description : Join two strings together. Frees BOTH the original
442 * strings. If either or both input strings are NULL,
443 * fails as if it had run out of memory.
445 * For comparison, string_append requires that the
446 * second string is non-NULL, and doesn't free it.
448 * Rationale: Too often, we want to do
449 * string_append(s, html_encode(s2)). That assert()s
450 * if s2 is NULL or if html_encode() runs out of memory.
451 * It also leaks memory. Proper checking is cumbersome.
452 * The solution: string_join(s, html_encode(s2)) is safe,
453 * and will free the memory allocated by html_encode().
456 * 1 : target_string = Pointer to old text that is to be
457 * extended. *target_string will be free()d by this
458 * routine. target_string must be non-NULL.
459 * 2 : text_to_append = Text to be appended to old.
461 * Returns : JB_ERR_OK on success, and sets *target_string
462 * to newly malloc'ed appended string. Caller
463 * must free(*target_string).
464 * JB_ERR_MEMORY on out-of-memory, or if
465 * *target_string or text_to_append is NULL. (In
466 * this case, frees *target_string and text_to_append,
467 * sets *target_string to NULL).
469 *********************************************************************/
470 jb_err string_join(char **target_string, char *text_to_append)
474 assert(target_string);
476 if (text_to_append == NULL)
478 freez(*target_string);
479 return JB_ERR_MEMORY;
482 err = string_append(target_string, text_to_append);
484 freez(text_to_append);
490 /*********************************************************************
492 * Function : string_toupper
494 * Description : Produce a copy of string with all convertible
495 * characters converted to uppercase.
498 * 1 : string = string to convert
500 * Returns : Uppercase copy of string if possible,
501 * NULL on out-of-memory or if string was NULL.
503 *********************************************************************/
504 char *string_toupper(const char *string)
509 if (!string || ((result = (char *) zalloc(strlen(string) + 1)) == NULL))
519 *p++ = (char)toupper((int) *q++);
527 /*********************************************************************
531 * Description : Duplicate the first n characters of a string that may
532 * contain '\0' characters.
535 * 1 : string = string to be duplicated
536 * 2 : len = number of bytes to duplicate
538 * Returns : pointer to copy, or NULL if failiure
540 *********************************************************************/
541 char *bindup(const char *string, size_t len)
545 if (NULL == (duplicate = (char *)malloc(len)))
551 memcpy(duplicate, string, len);
559 /*********************************************************************
561 * Function : make_path
563 * Description : Takes a directory name and a file name, returns
564 * the complete path. Handles windows/unix differences.
565 * If the file name is already an absolute path, or if
566 * the directory name is NULL or empty, it returns
570 * 1 : dir: Name of directory or NULL for none.
571 * 2 : file: Name of file. Should not be NULL or empty.
573 * Returns : "dir/file" (Or on windows, "dir\file").
574 * It allocates the string on the heap. Caller frees.
575 * Returns NULL in error (i.e. NULL file or out of
578 *********************************************************************/
579 char * make_path(const char * dir, const char * file)
590 strncpy(path,dir+2,512);
594 strncpy(path,dir+1,512);
599 strncpy(path,dir,512);
607 if(AddPart(path,file,512))
615 #else /* ndef AMIGA */
617 if ((file == NULL) || (*file == '\0'))
619 return NULL; /* Error */
622 if ((dir == NULL) || (*dir == '\0') /* No directory specified */
623 #if defined(_WIN32) || defined(__OS2__)
624 || (*file == '\\') || (file[1] == ':') /* Absolute path (DOS) */
625 #else /* ifndef _WIN32 || __OS2__ */
626 || (*file == '/') /* Absolute path (U*ix) */
627 #endif /* ifndef _WIN32 || __OS2__ */
635 size_t path_size = strlen(dir) + strlen(file) + 2; /* +2 for trailing (back)slash and \0 */
638 if ( *dir != '/' && basedir && *basedir )
641 * Relative path, so start with the base directory.
643 path_size += strlen(basedir) + 1; /* +1 for the slash */
644 path = malloc(path_size);
645 if (!path ) log_error(LOG_LEVEL_FATAL, "malloc failed!");
646 strlcpy(path, basedir, path_size);
647 strlcat(path, "/", path_size);
648 strlcat(path, dir, path_size);
651 #endif /* defined unix */
653 path = malloc(path_size);
654 if (!path ) log_error(LOG_LEVEL_FATAL, "malloc failed!");
655 strlcpy(path, dir, path_size);
658 #if defined(_WIN32) || defined(__OS2__)
659 if(path[strlen(path)-1] != '\\')
661 strlcat(path, "\\", path_size);
663 #else /* ifndef _WIN32 || __OS2__ */
664 if(path[strlen(path)-1] != '/')
666 strlcat(path, "/", path_size);
668 #endif /* ifndef _WIN32 || __OS2__ */
669 strlcat(path, file, path_size);
673 #endif /* ndef AMIGA */
677 /*********************************************************************
679 * Function : pick_from_range
681 * Description : Pick a positive number out of a given range.
682 * Should only be used if randomness would be nice,
683 * but isn't really necessary.
686 * 1 : range: Highest possible number to pick.
688 * Returns : Picked number.
690 *********************************************************************/
691 long int pick_from_range(long int range)
695 static unsigned long seed = 0;
696 #endif /* def _WIN32 */
701 if (range <= 0) return 0;
704 number = random() % range + 1;
705 #elif defined(MUTEX_LOCKS_AVAILABLE)
706 privoxy_mutex_lock(&rand_mutex);
710 seed = (unsigned long)(GetCurrentThreadId()+GetTickCount());
713 seed = (unsigned long)((rand() << 16) + rand());
714 #endif /* def _WIN32 */
715 number = (unsigned long)((rand() << 16) + (rand())) % (unsigned long)(range + 1);
716 privoxy_mutex_unlock(&rand_mutex);
719 * XXX: Which platforms reach this and are there
720 * better options than just using rand() and hoping
723 log_error(LOG_LEVEL_INFO, "No thread-safe PRNG available? Header time randomization "
724 "might cause crashes, predictable results or even combine these fine options.");
725 number = rand() % (long int)(range + 1);
727 #endif /* (def HAVE_RANDOM) */
733 #ifdef USE_PRIVOXY_STRLCPY
734 /*********************************************************************
736 * Function : privoxy_strlcpy
738 * Description : strlcpy(3) look-alike for those without decent libc.
741 * 1 : destination: buffer to copy into.
742 * 2 : source: String to copy.
743 * 3 : size: Size of destination buffer.
745 * Returns : The length of the string that privoxy_strlcpy() tried to create.
747 *********************************************************************/
748 size_t privoxy_strlcpy(char *destination, const char *source, const size_t size)
752 snprintf(destination, size, "%s", source);
754 * Platforms that lack strlcpy() also tend to have
755 * a broken snprintf implementation that doesn't
756 * guarantee nul termination.
758 * XXX: the configure script should detect and reject those.
760 destination[size-1] = '\0';
762 return strlen(source);
764 #endif /* def USE_PRIVOXY_STRLCPY */
768 /*********************************************************************
770 * Function : privoxy_strlcat
772 * Description : strlcat(3) look-alike for those without decent libc.
775 * 1 : destination: C string.
776 * 2 : source: String to copy.
777 * 3 : size: Size of destination buffer.
779 * Returns : The length of the string that privoxy_strlcat() tried to create.
781 *********************************************************************/
782 size_t privoxy_strlcat(char *destination, const char *source, const size_t size)
784 const size_t old_length = strlen(destination);
785 return old_length + strlcpy(destination + old_length, source, size - old_length);
787 #endif /* ndef HAVE_STRLCAT */
790 #if !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV)
791 /*********************************************************************
795 * Description : libc replacement function for the inverse of gmtime().
796 * Copyright (C) 2004 Free Software Foundation, Inc.
798 * Code originally copied from GnuPG, modifications done
799 * for Privoxy: style changed, #ifdefs for _WIN32 added
800 * to have it work on mingw32.
802 * XXX: It's very unlikely to happen, but if the malloc()
803 * call fails the time zone will be permanently set to UTC.
806 * 1 : tm: Broken-down time struct.
808 * Returns : tm converted into time_t seconds.
810 *********************************************************************/
811 time_t timegm(struct tm *tm)
824 old_zone = malloc(3 + strlen(zone) + 1);
827 strcpy(old_zone, "TZ=");
828 strcat(old_zone, zone);
832 #endif /* def _WIN32 */
839 #elif defined(_WIN32)
849 #endif /* !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV) */
852 #ifndef HAVE_SNPRINTF
854 * What follows is a portable snprintf routine, written by Mark Martinec.
855 * See: http://www.ijs.si/software/snprintf/
858 - a portable implementation of snprintf,
859 including vsnprintf.c, asnprintf, vasnprintf, asprintf, vasprintf
861 snprintf is a routine to convert numeric and string arguments to
862 formatted strings. It is similar to sprintf(3) provided in a system's
863 C library, yet it requires an additional argument - the buffer size -
864 and it guarantees never to store anything beyond the given buffer,
865 regardless of the format or arguments to be formatted. Some newer
866 operating systems do provide snprintf in their C library, but many do
867 not or do provide an inadequate (slow or idiosyncratic) version, which
868 calls for a portable implementation of this routine.
872 Mark Martinec <mark.martinec@ijs.si>, April 1999, June 2000
873 Copyright © 1999, Mark Martinec
877 #define PORTABLE_SNPRINTF_VERSION_MAJOR 2
878 #define PORTABLE_SNPRINTF_VERSION_MINOR 2
880 #if defined(NEED_ASPRINTF) || defined(NEED_ASNPRINTF) || defined(NEED_VASPRINTF) || defined(NEED_VASNPRINTF)
881 # if defined(NEED_SNPRINTF_ONLY)
882 # undef NEED_SNPRINTF_ONLY
884 # if !defined(PREFER_PORTABLE_SNPRINTF)
885 # define PREFER_PORTABLE_SNPRINTF
889 #if defined(SOLARIS_BUG_COMPATIBLE) && !defined(SOLARIS_COMPATIBLE)
890 #define SOLARIS_COMPATIBLE
893 #if defined(HPUX_BUG_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
894 #define HPUX_COMPATIBLE
897 #if defined(DIGITAL_UNIX_BUG_COMPATIBLE) && !defined(DIGITAL_UNIX_COMPATIBLE)
898 #define DIGITAL_UNIX_COMPATIBLE
901 #if defined(PERL_BUG_COMPATIBLE) && !defined(PERL_COMPATIBLE)
902 #define PERL_COMPATIBLE
905 #if defined(LINUX_BUG_COMPATIBLE) && !defined(LINUX_COMPATIBLE)
906 #define LINUX_COMPATIBLE
909 #include <sys/types.h>
920 #define isdigit(c) ((c) >= '0' && (c) <= '9')
922 /* For copying strings longer or equal to 'breakeven_point'
923 * it is more efficient to call memcpy() than to do it inline.
924 * The value depends mostly on the processor architecture,
925 * but also on the compiler and its optimization capabilities.
926 * The value is not critical, some small value greater than zero
927 * will be just fine if you don't care to squeeze every drop
928 * of performance out of the code.
930 * Small values favor memcpy, large values favor inline code.
932 #if defined(__alpha__) || defined(__alpha)
933 # define breakeven_point 2 /* AXP (DEC Alpha) - gcc or cc or egcs */
935 #if defined(__i386__) || defined(__i386)
936 # define breakeven_point 12 /* Intel Pentium/Linux - gcc 2.96 */
939 # define breakeven_point 10 /* HP-PA - gcc */
941 #if defined(__sparc__) || defined(__sparc)
942 # define breakeven_point 33 /* Sun Sparc 5 - gcc 2.8.1 */
945 /* some other values of possible interest: */
946 /* #define breakeven_point 8 */ /* VAX 4000 - vaxc */
947 /* #define breakeven_point 19 */ /* VAX 4000 - gcc 2.7.0 */
949 #ifndef breakeven_point
950 # define breakeven_point 6 /* some reasonable one-size-fits-all value */
953 #define fast_memcpy(d,s,n) \
954 { register size_t nn = (size_t)(n); \
955 if (nn >= breakeven_point) memcpy((d), (s), nn); \
956 else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
957 register char *dd; register const char *ss; \
958 for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } }
960 #define fast_memset(d,c,n) \
961 { register size_t nn = (size_t)(n); \
962 if (nn >= breakeven_point) memset((d), (int)(c), nn); \
963 else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
964 register char *dd; register const int cc=(int)(c); \
965 for (dd=(d); nn>0; nn--) *dd++ = cc; } }
969 #if defined(NEED_ASPRINTF)
970 int asprintf (char **ptr, const char *fmt, /*args*/ ...);
972 #if defined(NEED_VASPRINTF)
973 int vasprintf (char **ptr, const char *fmt, va_list ap);
975 #if defined(NEED_ASNPRINTF)
976 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...);
978 #if defined(NEED_VASNPRINTF)
979 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap);
982 #if defined(HAVE_SNPRINTF)
983 /* declare our portable snprintf routine under name portable_snprintf */
984 /* declare our portable vsnprintf routine under name portable_vsnprintf */
986 /* declare our portable routines under names snprintf and vsnprintf */
987 #define portable_snprintf snprintf
988 #if !defined(NEED_SNPRINTF_ONLY)
989 #define portable_vsnprintf vsnprintf
993 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
994 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...);
995 #if !defined(NEED_SNPRINTF_ONLY)
996 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap);
1002 static char credits[] = "\n\
1003 @(#)snprintf.c, v2.2: Mark Martinec, <mark.martinec@ijs.si>\n\
1004 @(#)snprintf.c, v2.2: Copyright 1999, Mark Martinec. Frontier Artistic License applies.\n\
1005 @(#)snprintf.c, v2.2: http://www.ijs.si/software/snprintf/\n";
1007 #if defined(NEED_ASPRINTF)
1008 int asprintf(char **ptr, const char *fmt, /*args*/ ...) {
1014 va_start(ap, fmt); /* measure the required size */
1015 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
1017 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1018 *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
1019 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1023 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1025 assert(str_l2 == str_l);
1031 #if defined(NEED_VASPRINTF)
1032 int vasprintf(char **ptr, const char *fmt, va_list ap) {
1038 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
1039 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1042 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1043 *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
1044 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1046 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1047 assert(str_l2 == str_l);
1053 #if defined(NEED_ASNPRINTF)
1054 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...) {
1059 va_start(ap, fmt); /* measure the required size */
1060 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
1062 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1063 if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1; /* truncate */
1064 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1065 if (str_m == 0) { /* not interested in resulting string, just return size */
1067 *ptr = (char *) malloc(str_m);
1068 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1072 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1074 assert(str_l2 == str_l);
1081 #if defined(NEED_VASNPRINTF)
1082 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap) {
1087 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
1088 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1091 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1092 if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1; /* truncate */
1093 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1094 if (str_m == 0) { /* not interested in resulting string, just return size */
1096 *ptr = (char *) malloc(str_m);
1097 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1099 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1100 assert(str_l2 == str_l);
1108 * If the system does have snprintf and the portable routine is not
1109 * specifically required, this module produces no code for snprintf/vsnprintf.
1111 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1113 #if !defined(NEED_SNPRINTF_ONLY)
1114 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1119 str_l = portable_vsnprintf(str, str_m, fmt, ap);
1125 #if defined(NEED_SNPRINTF_ONLY)
1126 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1128 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) {
1131 #if defined(NEED_SNPRINTF_ONLY)
1135 const char *p = fmt;
1137 /* In contrast with POSIX, the ISO C99 now says
1138 * that str can be NULL and str_m can be 0.
1139 * This is more useful than the old: if (str_m < 1) return -1; */
1141 #if defined(NEED_SNPRINTF_ONLY)
1147 /* if (str_l < str_m) str[str_l++] = *p++; -- this would be sufficient */
1148 /* but the following code achieves better performance for cases
1149 * where format string is long and contains few conversions */
1150 const char *q = strchr(p+1,'%');
1151 size_t n = !q ? strlen(p) : (q-p);
1152 if (str_l < str_m) {
1153 size_t avail = str_m-str_l;
1154 fast_memcpy(str+str_l, p, (n>avail?avail:n));
1158 const char *starting_p;
1159 size_t min_field_width = 0, precision = 0;
1160 int zero_padding = 0, precision_specified = 0, justify_left = 0;
1161 int alternate_form = 0, force_sign = 0;
1162 int space_for_positive = 1; /* If both the ' ' and '+' flags appear,
1163 the ' ' flag should be ignored. */
1164 char length_modifier = '\0'; /* allowed values: \0, h, l, L */
1165 char tmp[32];/* temporary buffer for simple numeric->string conversion */
1167 const char *str_arg; /* string address in case of string argument */
1168 size_t str_arg_l; /* natural field width of arg without padding
1170 unsigned char uchar_arg;
1171 /* unsigned char argument value - only defined for c conversion.
1172 N.B. standard explicitly states the char argument for
1173 the c conversion is unsigned */
1175 size_t number_of_zeros_to_pad = 0;
1176 /* number of zeros to be inserted for numeric conversions
1177 as required by the precision or minimal field width */
1179 size_t zero_padding_insertion_ind = 0;
1180 /* index into tmp where zero padding is to be inserted */
1182 char fmt_spec = '\0';
1183 /* current conversion specifier character */
1185 str_arg = credits;/* just to make compiler happy (defined but not used)*/
1187 starting_p = p; p++; /* skip '%' */
1189 while (*p == '0' || *p == '-' || *p == '+' ||
1190 *p == ' ' || *p == '#' || *p == '\'') {
1192 case '0': zero_padding = 1; break;
1193 case '-': justify_left = 1; break;
1194 case '+': force_sign = 1; space_for_positive = 0; break;
1195 case ' ': force_sign = 1;
1196 /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */
1197 #ifdef PERL_COMPATIBLE
1198 /* ... but in Perl the last of ' ' and '+' applies */
1199 space_for_positive = 1;
1202 case '#': alternate_form = 1; break;
1207 /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
1209 /* parse field width */
1212 p++; j = va_arg(ap, int);
1213 if (j >= 0) min_field_width = j;
1214 else { min_field_width = -j; justify_left = 1; }
1215 } else if (isdigit((int)(*p))) {
1216 /* size_t could be wider than unsigned int;
1217 make sure we treat argument like common implementations do */
1218 unsigned int uj = *p++ - '0';
1219 while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1220 min_field_width = uj;
1222 /* parse precision */
1224 p++; precision_specified = 1;
1226 int j = va_arg(ap, int);
1228 if (j >= 0) precision = j;
1230 precision_specified = 0; precision = 0;
1232 * Solaris 2.6 man page claims that in this case the precision
1233 * should be set to 0. Digital Unix 4.0, HPUX 10 and BSD man page
1234 * claim that this case should be treated as unspecified precision,
1235 * which is what we do here.
1238 } else if (isdigit((int)(*p))) {
1239 /* size_t could be wider than unsigned int;
1240 make sure we treat argument like common implementations do */
1241 unsigned int uj = *p++ - '0';
1242 while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1246 /* parse 'h', 'l' and 'll' length modifiers */
1247 if (*p == 'h' || *p == 'l') {
1248 length_modifier = *p; p++;
1249 if (length_modifier == 'l' && *p == 'l') { /* double l = long long */
1250 #ifdef SNPRINTF_LONGLONG_SUPPORT
1251 length_modifier = '2'; /* double l encoded as '2' */
1253 length_modifier = 'l'; /* treat it as a single 'l' */
1259 /* common synonyms: */
1261 case 'i': fmt_spec = 'd'; break;
1262 case 'D': fmt_spec = 'd'; length_modifier = 'l'; break;
1263 case 'U': fmt_spec = 'u'; length_modifier = 'l'; break;
1264 case 'O': fmt_spec = 'o'; length_modifier = 'l'; break;
1267 /* get parameter value, do initial processing */
1269 case '%': /* % behaves similar to 's' regarding flags and field widths */
1270 case 'c': /* c behaves similar to 's' regarding flags and field widths */
1272 length_modifier = '\0'; /* wint_t and wchar_t not supported */
1273 /* the result of zero padding flag with non-numeric conversion specifier*/
1274 /* is undefined. Solaris and HPUX 10 does zero padding in this case, */
1275 /* Digital Unix and Linux does not. */
1276 #if !defined(SOLARIS_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
1277 zero_padding = 0; /* turn zero padding off for string conversions */
1284 int j = va_arg(ap, int);
1285 uchar_arg = (unsigned char) j; /* standard demands unsigned char */
1286 str_arg = (const char *) &uchar_arg;
1290 str_arg = va_arg(ap, const char *);
1291 if (!str_arg) str_arg_l = 0;
1292 /* make sure not to address string beyond the specified precision !!! */
1293 else if (!precision_specified) str_arg_l = strlen(str_arg);
1294 /* truncate string if necessary as requested by precision */
1295 else if (precision == 0) str_arg_l = 0;
1297 /* memchr on HP does not like n > 2^31 !!! */
1298 const char *q = memchr(str_arg, '\0',
1299 precision <= 0x7fffffff ? precision : 0x7fffffff);
1300 str_arg_l = !q ? precision : (q-str_arg);
1306 case 'd': case 'u': case 'o': case 'x': case 'X': case 'p': {
1307 /* NOTE: the u, o, x, X and p conversion specifiers imply
1308 the value is unsigned; d implies a signed value */
1311 /* 0 if numeric argument is zero (or if pointer is NULL for 'p'),
1312 +1 if greater than zero (or nonzero for unsigned arguments),
1313 -1 if negative (unsigned argument is never negative) */
1315 int int_arg = 0; unsigned int uint_arg = 0;
1316 /* only defined for length modifier h, or for no length modifiers */
1318 long int long_arg = 0; unsigned long int ulong_arg = 0;
1319 /* only defined for length modifier l */
1321 void *ptr_arg = NULL;
1322 /* pointer argument value -only defined for p conversion */
1324 #ifdef SNPRINTF_LONGLONG_SUPPORT
1325 long long int long_long_arg = 0;
1326 unsigned long long int ulong_long_arg = 0;
1327 /* only defined for length modifier ll */
1329 if (fmt_spec == 'p') {
1330 /* HPUX 10: An l, h, ll or L before any other conversion character
1331 * (other than d, i, u, o, x, or X) is ignored.
1333 * not specified, but seems to behave as HPUX does.
1334 * Solaris: If an h, l, or L appears before any other conversion
1335 * specifier (other than d, i, u, o, x, or X), the behavior
1336 * is undefined. (Actually %hp converts only 16-bits of address
1337 * and %llp treats address as 64-bit data which is incompatible
1338 * with (void *) argument on a 32-bit system).
1340 #ifdef SOLARIS_COMPATIBLE
1341 # ifdef SOLARIS_BUG_COMPATIBLE
1342 /* keep length modifiers even if it represents 'll' */
1344 if (length_modifier == '2') length_modifier = '\0';
1347 length_modifier = '\0';
1349 ptr_arg = va_arg(ap, void *);
1350 if (ptr_arg != NULL) arg_sign = 1;
1351 } else if (fmt_spec == 'd') { /* signed */
1352 switch (length_modifier) {
1355 /* It is non-portable to specify a second argument of char or short
1356 * to va_arg, because arguments seen by the called function
1357 * are not char or short. C converts char and short arguments
1358 * to int before passing them to a function.
1360 int_arg = va_arg(ap, int);
1361 if (int_arg > 0) arg_sign = 1;
1362 else if (int_arg < 0) arg_sign = -1;
1365 long_arg = va_arg(ap, long int);
1366 if (long_arg > 0) arg_sign = 1;
1367 else if (long_arg < 0) arg_sign = -1;
1369 #ifdef SNPRINTF_LONGLONG_SUPPORT
1371 long_long_arg = va_arg(ap, long long int);
1372 if (long_long_arg > 0) arg_sign = 1;
1373 else if (long_long_arg < 0) arg_sign = -1;
1377 } else { /* unsigned */
1378 switch (length_modifier) {
1381 uint_arg = va_arg(ap, unsigned int);
1382 if (uint_arg) arg_sign = 1;
1385 ulong_arg = va_arg(ap, unsigned long int);
1386 if (ulong_arg) arg_sign = 1;
1388 #ifdef SNPRINTF_LONGLONG_SUPPORT
1390 ulong_long_arg = va_arg(ap, unsigned long long int);
1391 if (ulong_long_arg) arg_sign = 1;
1396 str_arg = tmp; str_arg_l = 0;
1398 * For d, i, u, o, x, and X conversions, if precision is specified,
1399 * the '0' flag should be ignored. This is so with Solaris 2.6,
1400 * Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl.
1402 #ifndef PERL_COMPATIBLE
1403 if (precision_specified) zero_padding = 0;
1405 if (fmt_spec == 'd') {
1406 if (force_sign && arg_sign >= 0)
1407 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1408 /* leave negative numbers for sprintf to handle,
1409 to avoid handling tricky cases like (short int)(-32768) */
1410 #ifdef LINUX_COMPATIBLE
1411 } else if (fmt_spec == 'p' && force_sign && arg_sign > 0) {
1412 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1414 } else if (alternate_form) {
1415 if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X') )
1416 { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = fmt_spec; }
1417 /* alternate form should have no effect for p conversion, but ... */
1418 #ifdef HPUX_COMPATIBLE
1419 else if (fmt_spec == 'p'
1420 /* HPUX 10: for an alternate form of p conversion,
1421 * a nonzero result is prefixed by 0x. */
1422 #ifndef HPUX_BUG_COMPATIBLE
1423 /* Actually it uses 0x prefix even for a zero value. */
1426 ) { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = 'x'; }
1429 zero_padding_insertion_ind = str_arg_l;
1430 if (!precision_specified) precision = 1; /* default precision is 1 */
1431 if (precision == 0 && arg_sign == 0
1432 #if defined(HPUX_BUG_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1434 /* HPUX 10 man page claims: With conversion character p the result of
1435 * converting a zero value with a precision of zero is a null string.
1436 * Actually HP returns all zeroes, and Linux returns "(nil)". */
1439 /* converted to null string */
1440 /* When zero value is formatted with an explicit precision 0,
1441 the resulting formatted string is empty (d, i, u, o, x, X, p). */
1443 char f[5]; int f_l = 0;
1444 f[f_l++] = '%'; /* construct a simple format string for sprintf */
1445 if (!length_modifier) { }
1446 else if (length_modifier=='2') { f[f_l++] = 'l'; f[f_l++] = 'l'; }
1447 else f[f_l++] = length_modifier;
1448 f[f_l++] = fmt_spec; f[f_l++] = '\0';
1449 if (fmt_spec == 'p') str_arg_l += sprintf(tmp+str_arg_l, f, ptr_arg);
1450 else if (fmt_spec == 'd') { /* signed */
1451 switch (length_modifier) {
1453 case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, int_arg); break;
1454 case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, long_arg); break;
1455 #ifdef SNPRINTF_LONGLONG_SUPPORT
1456 case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,long_long_arg); break;
1459 } else { /* unsigned */
1460 switch (length_modifier) {
1462 case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, uint_arg); break;
1463 case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, ulong_arg); break;
1464 #ifdef SNPRINTF_LONGLONG_SUPPORT
1465 case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,ulong_long_arg);break;
1469 /* include the optional minus sign and possible "0x"
1470 in the region before the zero padding insertion point */
1471 if (zero_padding_insertion_ind < str_arg_l &&
1472 tmp[zero_padding_insertion_ind] == '-') {
1473 zero_padding_insertion_ind++;
1475 if (zero_padding_insertion_ind+1 < str_arg_l &&
1476 tmp[zero_padding_insertion_ind] == '0' &&
1477 (tmp[zero_padding_insertion_ind+1] == 'x' ||
1478 tmp[zero_padding_insertion_ind+1] == 'X') ) {
1479 zero_padding_insertion_ind += 2;
1482 { size_t num_of_digits = str_arg_l - zero_padding_insertion_ind;
1483 if (alternate_form && fmt_spec == 'o'
1484 #ifdef HPUX_COMPATIBLE /* ("%#.o",0) -> "" */
1487 #ifdef DIGITAL_UNIX_BUG_COMPATIBLE /* ("%#o",0) -> "00" */
1489 /* unless zero is already the first character */
1490 && !(zero_padding_insertion_ind < str_arg_l
1491 && tmp[zero_padding_insertion_ind] == '0')
1493 ) { /* assure leading zero for alternate-form octal numbers */
1494 if (!precision_specified || precision < num_of_digits+1) {
1495 /* precision is increased to force the first character to be zero,
1496 except if a zero value is formatted with an explicit precision
1498 precision = num_of_digits+1; precision_specified = 1;
1501 /* zero padding to specified precision? */
1502 if (num_of_digits < precision)
1503 number_of_zeros_to_pad = precision - num_of_digits;
1505 /* zero padding to specified minimal field width? */
1506 if (!justify_left && zero_padding) {
1507 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1508 if (n > 0) number_of_zeros_to_pad += n;
1512 default: /* unrecognized conversion specifier, keep format string as-is*/
1513 zero_padding = 0; /* turn zero padding off for non-numeric convers. */
1514 #ifndef DIGITAL_UNIX_COMPATIBLE
1515 justify_left = 1; min_field_width = 0; /* reset flags */
1517 #if defined(PERL_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1518 /* keep the entire format string unchanged */
1519 str_arg = starting_p; str_arg_l = p - starting_p;
1520 /* well, not exactly so for Linux, which does something inbetween,
1521 * and I don't feel an urge to imitate it: "%+++++hy" -> "%+y" */
1523 /* discard the unrecognized conversion, just keep *
1524 * the unrecognized conversion character */
1525 str_arg = p; str_arg_l = 0;
1527 if (*p) str_arg_l++; /* include invalid conversion specifier unchanged
1528 if not at end-of-string */
1531 if (*p) p++; /* step over the just processed conversion specifier */
1532 /* insert padding to the left as requested by min_field_width;
1533 this does not include the zero padding in case of numerical conversions*/
1534 if (!justify_left) { /* left padding with blank or zero */
1535 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1537 if (str_l < str_m) {
1538 size_t avail = str_m-str_l;
1539 fast_memset(str+str_l, (zero_padding?'0':' '), (n>avail?avail:n));
1544 /* zero padding as requested by the precision or by the minimal field width
1545 * for numeric conversions required? */
1546 if (number_of_zeros_to_pad <= 0) {
1547 /* will not copy first part of numeric right now, *
1548 * force it to be copied later in its entirety */
1549 zero_padding_insertion_ind = 0;
1551 /* insert first part of numerics (sign or '0x') before zero padding */
1552 int n = zero_padding_insertion_ind;
1554 if (str_l < str_m) {
1555 size_t avail = str_m-str_l;
1556 fast_memcpy(str+str_l, str_arg, (n>avail?avail:n));
1560 /* insert zero padding as requested by the precision or min field width */
1561 n = number_of_zeros_to_pad;
1563 if (str_l < str_m) {
1564 size_t avail = str_m-str_l;
1565 fast_memset(str+str_l, '0', (n>avail?avail:n));
1570 /* insert formatted string
1571 * (or as-is conversion specifier for unknown conversions) */
1572 { int n = str_arg_l - zero_padding_insertion_ind;
1574 if (str_l < str_m) {
1575 size_t avail = str_m-str_l;
1576 fast_memcpy(str+str_l, str_arg+zero_padding_insertion_ind,
1582 /* insert right padding */
1583 if (justify_left) { /* right blank padding to the field width */
1584 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1586 if (str_l < str_m) {
1587 size_t avail = str_m-str_l;
1588 fast_memset(str+str_l, ' ', (n>avail?avail:n));
1595 #if defined(NEED_SNPRINTF_ONLY)
1598 if (str_m > 0) { /* make sure the string is null-terminated
1599 even at the expense of overwriting the last character
1600 (shouldn't happen, but just in case) */
1601 str[str_l <= str_m-1 ? str_l : str_m-1] = '\0';
1603 /* Return the number of characters formatted (excluding trailing null
1604 * character), that is, the number of characters that would have been
1605 * written to the buffer if it were large enough.
1607 * The value of str_l should be returned, but str_l is of unsigned type
1608 * size_t, and snprintf is int, possibly leading to an undetected
1609 * integer overflow, resulting in a negative return value, which is illegal.
1610 * Both XSH5 and ISO C99 (at least the draft) are silent on this issue.
1611 * Should errno be set to EOVERFLOW and EOF returned in this case???
1616 #endif /* ndef HAVE_SNPRINTF */