1 const char miscutil_rcs[] = "$Id: miscutil.c,v 1.68 2011/09/04 11:10:56 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/miscutil.c,v $
6 * Purpose : zalloc, hash_string, strcmpic, strncmpic, and
7 * MinGW32 strdup functions. These are each too small
8 * to deserve their own file but don't really fit in
11 * Copyright : Written by and Copyright (C) 2001-2011 the
12 * Privoxy team. http://www.privoxy.org/
14 * Based on the Internet Junkbuster originally written
15 * by and Copyright (C) 1997 Anonymous Coders and
16 * Junkbusters Corporation. http://www.junkbusters.com
18 * The timegm replacement function was taken from GnuPG,
19 * Copyright (C) 2004 Free Software Foundation, Inc.
21 * The snprintf replacement function is written by
22 * Mark Martinec who also holds the copyright. It can be
23 * used under the terms of the GPL or the terms of the
24 * "Frontier Artistic License".
26 * This program is free software; you can redistribute it
27 * and/or modify it under the terms of the GNU General
28 * Public License as published by the Free Software
29 * Foundation; either version 2 of the License, or (at
30 * your option) any later version.
32 * This program is distributed in the hope that it will
33 * be useful, but WITHOUT ANY WARRANTY; without even the
34 * implied warranty of MERCHANTABILITY or FITNESS FOR A
35 * PARTICULAR PURPOSE. See the GNU General Public
36 * License for more details.
38 * The GNU General Public License should be included with
39 * this file. If not, you can view it at
40 * http://www.gnu.org/copyleft/gpl.html
41 * or write to the Free Software Foundation, Inc., 59
42 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
44 *********************************************************************/
50 #include <sys/types.h>
52 #if !defined(_WIN32) && !defined(__OS2__)
54 #endif /* #if !defined(_WIN32) && !defined(__OS2__) */
59 #if !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV)
61 #endif /* !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV) */
68 const char miscutil_h_rcs[] = MISCUTIL_H_VERSION;
70 /*********************************************************************
74 * Description : Malloc some memory and set it to '\0'.
77 * 1 : size = Size of memory chunk to return.
79 * Returns : Pointer to newly malloc'd memory chunk.
81 *********************************************************************/
82 void *zalloc(size_t size)
86 if ((ret = (void *)malloc(size)) != NULL)
97 /*********************************************************************
99 * Function : write_pid_file
101 * Description : Writes a pid file with the pid of the main process
107 *********************************************************************/
108 void write_pid_file(void)
113 * If no --pidfile option was given,
114 * we can live without one.
116 if (pidfile == NULL) return;
118 if ((fp = fopen(pidfile, "w")) == NULL)
120 log_error(LOG_LEVEL_INFO, "can't open pidfile '%s': %E", pidfile);
124 fprintf(fp, "%u\n", (unsigned int) getpid());
130 #endif /* def unix */
133 /*********************************************************************
135 * Function : hash_string
137 * Description : Take a string and compute a (hopefuly) unique numeric
138 * integer value. This has several uses, but being able
139 * to "switch" a string the one of my favorites.
142 * 1 : s : string to be hashed.
144 * Returns : an unsigned long variable with the hashed value.
146 *********************************************************************/
147 unsigned int hash_string( const char* s )
153 h = 5 * h + (unsigned int)*s;
161 /*********************************************************************
163 * Function : strcmpic
165 * Description : Case insensitive string comparison
168 * 1 : s1 = string 1 to compare
169 * 2 : s2 = string 2 to compare
171 * Returns : 0 if s1==s2, Negative if s1<s2, Positive if s1>s2
173 *********************************************************************/
174 int strcmpic(const char *s1, const char *s2)
181 if ( ( *s1 != *s2 ) && ( ijb_tolower(*s1) != ijb_tolower(*s2) ) )
187 return(ijb_tolower(*s1) - ijb_tolower(*s2));
192 /*********************************************************************
194 * Function : strncmpic
196 * Description : Case insensitive string comparison (up to n characters)
199 * 1 : s1 = string 1 to compare
200 * 2 : s2 = string 2 to compare
201 * 3 : n = maximum characters to compare
203 * Returns : 0 if s1==s2, Negative if s1<s2, Positive if s1>s2
205 *********************************************************************/
206 int strncmpic(const char *s1, const char *s2, size_t n)
208 if (n <= (size_t)0) return(0);
214 if ( ( *s1 != *s2 ) && ( ijb_tolower(*s1) != ijb_tolower(*s2) ) )
219 if (--n <= (size_t)0) break;
223 return(ijb_tolower(*s1) - ijb_tolower(*s2));
228 /*********************************************************************
232 * Description : In-situ-eliminate all leading and trailing whitespace
236 * 1 : s : string to be chomped.
238 * Returns : chomped string
240 *********************************************************************/
241 char *chomp(char *string)
246 * strip trailing whitespace
248 p = string + strlen(string);
249 while (p > string && ijb_isspace(*(p-1)))
256 * find end of leading whitespace
259 while (*q && ijb_isspace(*q))
265 * if there was any, move the rest forwards
280 /*********************************************************************
282 * Function : string_append
284 * Description : Reallocate target_string and append text to it.
285 * This makes it easier to append to malloc'd strings.
286 * This is similar to the (removed) strsav(), but
287 * running out of memory isn't catastrophic.
291 * The following style provides sufficient error
292 * checking for this routine, with minimal clutter
293 * in the source code. It is recommended if you
294 * have many calls to this function:
296 * char * s = strdup(...); // don't check for error
297 * string_append(&s, ...); // don't check for error
298 * string_append(&s, ...); // don't check for error
299 * string_append(&s, ...); // don't check for error
300 * if (NULL == s) { ... handle error ... }
304 * char * s = strdup(...); // don't check for error
305 * string_append(&s, ...); // don't check for error
306 * string_append(&s, ...); // don't check for error
307 * if (string_append(&s, ...)) {... handle error ...}
310 * 1 : target_string = Pointer to old text that is to be
311 * extended. *target_string will be free()d by this
312 * routine. target_string must be non-NULL.
313 * If *target_string is NULL, this routine will
314 * do nothing and return with an error - this allows
315 * you to make many calls to this routine and only
316 * check for errors after the last one.
317 * 2 : text_to_append = Text to be appended to old.
320 * Returns : JB_ERR_OK on success, and sets *target_string
321 * to newly malloc'ed appended string. Caller
322 * must free(*target_string).
323 * JB_ERR_MEMORY on out-of-memory. (And free()s
324 * *target_string and sets it to NULL).
325 * JB_ERR_MEMORY if *target_string is NULL.
327 *********************************************************************/
328 jb_err string_append(char **target_string, const char *text_to_append)
334 assert(target_string);
335 assert(text_to_append);
337 if (*target_string == NULL)
339 return JB_ERR_MEMORY;
342 if (*text_to_append == '\0')
347 old_len = strlen(*target_string);
349 new_size = strlen(text_to_append) + old_len + 1;
351 if (NULL == (new_string = realloc(*target_string, new_size)))
353 free(*target_string);
355 *target_string = NULL;
356 return JB_ERR_MEMORY;
359 strlcpy(new_string + old_len, text_to_append, new_size - old_len);
361 *target_string = new_string;
366 /*********************************************************************
368 * Function : string_join
370 * Description : Join two strings together. Frees BOTH the original
371 * strings. If either or both input strings are NULL,
372 * fails as if it had run out of memory.
374 * For comparison, string_append requires that the
375 * second string is non-NULL, and doesn't free it.
377 * Rationale: Too often, we want to do
378 * string_append(s, html_encode(s2)). That assert()s
379 * if s2 is NULL or if html_encode() runs out of memory.
380 * It also leaks memory. Proper checking is cumbersome.
381 * The solution: string_join(s, html_encode(s2)) is safe,
382 * and will free the memory allocated by html_encode().
385 * 1 : target_string = Pointer to old text that is to be
386 * extended. *target_string will be free()d by this
387 * routine. target_string must be non-NULL.
388 * 2 : text_to_append = Text to be appended to old.
390 * Returns : JB_ERR_OK on success, and sets *target_string
391 * to newly malloc'ed appended string. Caller
392 * must free(*target_string).
393 * JB_ERR_MEMORY on out-of-memory, or if
394 * *target_string or text_to_append is NULL. (In
395 * this case, frees *target_string and text_to_append,
396 * sets *target_string to NULL).
398 *********************************************************************/
399 jb_err string_join(char **target_string, char *text_to_append)
403 assert(target_string);
405 if (text_to_append == NULL)
407 freez(*target_string);
408 return JB_ERR_MEMORY;
411 err = string_append(target_string, text_to_append);
413 freez(text_to_append);
419 /*********************************************************************
421 * Function : string_toupper
423 * Description : Produce a copy of string with all convertible
424 * characters converted to uppercase.
427 * 1 : string = string to convert
429 * Returns : Uppercase copy of string if possible,
430 * NULL on out-of-memory or if string was NULL.
432 *********************************************************************/
433 char *string_toupper(const char *string)
438 if (!string || ((result = (char *) zalloc(strlen(string) + 1)) == NULL))
448 *p++ = (char)toupper((int) *q++);
456 /*********************************************************************
460 * Description : Duplicate the first n characters of a string that may
461 * contain '\0' characters.
464 * 1 : string = string to be duplicated
465 * 2 : len = number of bytes to duplicate
467 * Returns : pointer to copy, or NULL if failiure
469 *********************************************************************/
470 char *bindup(const char *string, size_t len)
474 if (NULL == (duplicate = (char *)malloc(len)))
480 memcpy(duplicate, string, len);
488 /*********************************************************************
490 * Function : make_path
492 * Description : Takes a directory name and a file name, returns
493 * the complete path. Handles windows/unix differences.
494 * If the file name is already an absolute path, or if
495 * the directory name is NULL or empty, it returns
499 * 1 : dir: Name of directory or NULL for none.
500 * 2 : file: Name of file. Should not be NULL or empty.
502 * Returns : "dir/file" (Or on windows, "dir\file").
503 * It allocates the string on the heap. Caller frees.
504 * Returns NULL in error (i.e. NULL file or out of
507 *********************************************************************/
508 char * make_path(const char * dir, const char * file)
519 strncpy(path,dir+2,512);
523 strncpy(path,dir+1,512);
528 strncpy(path,dir,512);
536 if(AddPart(path,file,512))
544 #else /* ndef AMIGA */
546 if ((file == NULL) || (*file == '\0'))
548 return NULL; /* Error */
551 if ((dir == NULL) || (*dir == '\0') /* No directory specified */
552 #if defined(_WIN32) || defined(__OS2__)
553 || (*file == '\\') || (file[1] == ':') /* Absolute path (DOS) */
554 #else /* ifndef _WIN32 || __OS2__ */
555 || (*file == '/') /* Absolute path (U*ix) */
556 #endif /* ifndef _WIN32 || __OS2__ */
564 size_t path_size = strlen(dir) + strlen(file) + 2; /* +2 for trailing (back)slash and \0 */
567 if ( *dir != '/' && basedir && *basedir )
570 * Relative path, so start with the base directory.
572 path_size += strlen(basedir) + 1; /* +1 for the slash */
573 path = malloc(path_size);
574 if (!path ) log_error(LOG_LEVEL_FATAL, "malloc failed!");
575 strlcpy(path, basedir, path_size);
576 strlcat(path, "/", path_size);
577 strlcat(path, dir, path_size);
580 #endif /* defined unix */
582 path = malloc(path_size);
583 if (!path ) log_error(LOG_LEVEL_FATAL, "malloc failed!");
584 strlcpy(path, dir, path_size);
587 assert(NULL != path);
588 #if defined(_WIN32) || defined(__OS2__)
589 if(path[strlen(path)-1] != '\\')
591 strlcat(path, "\\", path_size);
593 #else /* ifndef _WIN32 || __OS2__ */
594 if(path[strlen(path)-1] != '/')
596 strlcat(path, "/", path_size);
598 #endif /* ifndef _WIN32 || __OS2__ */
599 strlcat(path, file, path_size);
603 #endif /* ndef AMIGA */
607 /*********************************************************************
609 * Function : pick_from_range
611 * Description : Pick a positive number out of a given range.
612 * Should only be used if randomness would be nice,
613 * but isn't really necessary.
616 * 1 : range: Highest possible number to pick.
618 * Returns : Picked number.
620 *********************************************************************/
621 long int pick_from_range(long int range)
625 static unsigned long seed = 0;
626 #endif /* def _WIN32 */
631 if (range <= 0) return 0;
634 number = random() % range + 1;
635 #elif defined(MUTEX_LOCKS_AVAILABLE)
636 privoxy_mutex_lock(&rand_mutex);
640 seed = (unsigned long)(GetCurrentThreadId()+GetTickCount());
643 seed = (unsigned long)((rand() << 16) + rand());
644 #endif /* def _WIN32 */
645 number = (unsigned long)((rand() << 16) + (rand())) % (unsigned long)(range + 1);
646 privoxy_mutex_unlock(&rand_mutex);
649 * XXX: Which platforms reach this and are there
650 * better options than just using rand() and hoping
653 log_error(LOG_LEVEL_INFO, "No thread-safe PRNG available? Header time randomization "
654 "might cause crashes, predictable results or even combine these fine options.");
655 number = rand() % (long int)(range + 1);
657 #endif /* (def HAVE_RANDOM) */
663 #ifdef USE_PRIVOXY_STRLCPY
664 /*********************************************************************
666 * Function : privoxy_strlcpy
668 * Description : strlcpy(3) look-alike for those without decent libc.
671 * 1 : destination: buffer to copy into.
672 * 2 : source: String to copy.
673 * 3 : size: Size of destination buffer.
675 * Returns : The length of the string that privoxy_strlcpy() tried to create.
677 *********************************************************************/
678 size_t privoxy_strlcpy(char *destination, const char *source, const size_t size)
682 snprintf(destination, size, "%s", source);
684 * Platforms that lack strlcpy() also tend to have
685 * a broken snprintf implementation that doesn't
686 * guarantee nul termination.
688 * XXX: the configure script should detect and reject those.
690 destination[size-1] = '\0';
692 return strlen(source);
694 #endif /* def USE_PRIVOXY_STRLCPY */
698 /*********************************************************************
700 * Function : privoxy_strlcat
702 * Description : strlcat(3) look-alike for those without decent libc.
705 * 1 : destination: C string.
706 * 2 : source: String to copy.
707 * 3 : size: Size of destination buffer.
709 * Returns : The length of the string that privoxy_strlcat() tried to create.
711 *********************************************************************/
712 size_t privoxy_strlcat(char *destination, const char *source, const size_t size)
714 const size_t old_length = strlen(destination);
715 return old_length + strlcpy(destination + old_length, source, size - old_length);
717 #endif /* ndef HAVE_STRLCAT */
720 #if !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV)
721 /*********************************************************************
725 * Description : libc replacement function for the inverse of gmtime().
726 * Copyright (C) 2004 Free Software Foundation, Inc.
728 * Code originally copied from GnuPG, modifications done
729 * for Privoxy: style changed, #ifdefs for _WIN32 added
730 * to have it work on mingw32.
732 * XXX: It's very unlikely to happen, but if the malloc()
733 * call fails the time zone will be permanently set to UTC.
736 * 1 : tm: Broken-down time struct.
738 * Returns : tm converted into time_t seconds.
740 *********************************************************************/
741 time_t timegm(struct tm *tm)
754 old_zone = malloc(3 + strlen(zone) + 1);
757 strcpy(old_zone, "TZ=");
758 strcat(old_zone, zone);
762 #endif /* def _WIN32 */
769 #elif defined(_WIN32)
779 #endif /* !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV) */
782 #ifndef HAVE_SNPRINTF
784 * What follows is a portable snprintf routine, written by Mark Martinec.
785 * See: http://www.ijs.si/software/snprintf/
788 - a portable implementation of snprintf,
789 including vsnprintf.c, asnprintf, vasnprintf, asprintf, vasprintf
791 snprintf is a routine to convert numeric and string arguments to
792 formatted strings. It is similar to sprintf(3) provided in a system's
793 C library, yet it requires an additional argument - the buffer size -
794 and it guarantees never to store anything beyond the given buffer,
795 regardless of the format or arguments to be formatted. Some newer
796 operating systems do provide snprintf in their C library, but many do
797 not or do provide an inadequate (slow or idiosyncratic) version, which
798 calls for a portable implementation of this routine.
802 Mark Martinec <mark.martinec@ijs.si>, April 1999, June 2000
803 Copyright © 1999, Mark Martinec
807 #define PORTABLE_SNPRINTF_VERSION_MAJOR 2
808 #define PORTABLE_SNPRINTF_VERSION_MINOR 2
810 #if defined(NEED_ASPRINTF) || defined(NEED_ASNPRINTF) || defined(NEED_VASPRINTF) || defined(NEED_VASNPRINTF)
811 # if defined(NEED_SNPRINTF_ONLY)
812 # undef NEED_SNPRINTF_ONLY
814 # if !defined(PREFER_PORTABLE_SNPRINTF)
815 # define PREFER_PORTABLE_SNPRINTF
819 #if defined(SOLARIS_BUG_COMPATIBLE) && !defined(SOLARIS_COMPATIBLE)
820 #define SOLARIS_COMPATIBLE
823 #if defined(HPUX_BUG_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
824 #define HPUX_COMPATIBLE
827 #if defined(DIGITAL_UNIX_BUG_COMPATIBLE) && !defined(DIGITAL_UNIX_COMPATIBLE)
828 #define DIGITAL_UNIX_COMPATIBLE
831 #if defined(PERL_BUG_COMPATIBLE) && !defined(PERL_COMPATIBLE)
832 #define PERL_COMPATIBLE
835 #if defined(LINUX_BUG_COMPATIBLE) && !defined(LINUX_COMPATIBLE)
836 #define LINUX_COMPATIBLE
839 #include <sys/types.h>
850 #define isdigit(c) ((c) >= '0' && (c) <= '9')
852 /* For copying strings longer or equal to 'breakeven_point'
853 * it is more efficient to call memcpy() than to do it inline.
854 * The value depends mostly on the processor architecture,
855 * but also on the compiler and its optimization capabilities.
856 * The value is not critical, some small value greater than zero
857 * will be just fine if you don't care to squeeze every drop
858 * of performance out of the code.
860 * Small values favor memcpy, large values favor inline code.
862 #if defined(__alpha__) || defined(__alpha)
863 # define breakeven_point 2 /* AXP (DEC Alpha) - gcc or cc or egcs */
865 #if defined(__i386__) || defined(__i386)
866 # define breakeven_point 12 /* Intel Pentium/Linux - gcc 2.96 */
869 # define breakeven_point 10 /* HP-PA - gcc */
871 #if defined(__sparc__) || defined(__sparc)
872 # define breakeven_point 33 /* Sun Sparc 5 - gcc 2.8.1 */
875 /* some other values of possible interest: */
876 /* #define breakeven_point 8 */ /* VAX 4000 - vaxc */
877 /* #define breakeven_point 19 */ /* VAX 4000 - gcc 2.7.0 */
879 #ifndef breakeven_point
880 # define breakeven_point 6 /* some reasonable one-size-fits-all value */
883 #define fast_memcpy(d,s,n) \
884 { register size_t nn = (size_t)(n); \
885 if (nn >= breakeven_point) memcpy((d), (s), nn); \
886 else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
887 register char *dd; register const char *ss; \
888 for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } }
890 #define fast_memset(d,c,n) \
891 { register size_t nn = (size_t)(n); \
892 if (nn >= breakeven_point) memset((d), (int)(c), nn); \
893 else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
894 register char *dd; register const int cc=(int)(c); \
895 for (dd=(d); nn>0; nn--) *dd++ = cc; } }
899 #if defined(NEED_ASPRINTF)
900 int asprintf (char **ptr, const char *fmt, /*args*/ ...);
902 #if defined(NEED_VASPRINTF)
903 int vasprintf (char **ptr, const char *fmt, va_list ap);
905 #if defined(NEED_ASNPRINTF)
906 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...);
908 #if defined(NEED_VASNPRINTF)
909 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap);
912 #if defined(HAVE_SNPRINTF)
913 /* declare our portable snprintf routine under name portable_snprintf */
914 /* declare our portable vsnprintf routine under name portable_vsnprintf */
916 /* declare our portable routines under names snprintf and vsnprintf */
917 #define portable_snprintf snprintf
918 #if !defined(NEED_SNPRINTF_ONLY)
919 #define portable_vsnprintf vsnprintf
923 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
924 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...);
925 #if !defined(NEED_SNPRINTF_ONLY)
926 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap);
932 static char credits[] = "\n\
933 @(#)snprintf.c, v2.2: Mark Martinec, <mark.martinec@ijs.si>\n\
934 @(#)snprintf.c, v2.2: Copyright 1999, Mark Martinec. Frontier Artistic License applies.\n\
935 @(#)snprintf.c, v2.2: http://www.ijs.si/software/snprintf/\n";
937 #if defined(NEED_ASPRINTF)
938 int asprintf(char **ptr, const char *fmt, /*args*/ ...) {
944 va_start(ap, fmt); /* measure the required size */
945 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
947 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
948 *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
949 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
953 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
955 assert(str_l2 == str_l);
961 #if defined(NEED_VASPRINTF)
962 int vasprintf(char **ptr, const char *fmt, va_list ap) {
968 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
969 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
972 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
973 *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
974 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
976 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
977 assert(str_l2 == str_l);
983 #if defined(NEED_ASNPRINTF)
984 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...) {
989 va_start(ap, fmt); /* measure the required size */
990 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
992 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
993 if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1; /* truncate */
994 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
995 if (str_m == 0) { /* not interested in resulting string, just return size */
997 *ptr = (char *) malloc(str_m);
998 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1002 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1004 assert(str_l2 == str_l);
1011 #if defined(NEED_VASNPRINTF)
1012 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap) {
1017 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
1018 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1021 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1022 if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1; /* truncate */
1023 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1024 if (str_m == 0) { /* not interested in resulting string, just return size */
1026 *ptr = (char *) malloc(str_m);
1027 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1029 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1030 assert(str_l2 == str_l);
1038 * If the system does have snprintf and the portable routine is not
1039 * specifically required, this module produces no code for snprintf/vsnprintf.
1041 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1043 #if !defined(NEED_SNPRINTF_ONLY)
1044 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1049 str_l = portable_vsnprintf(str, str_m, fmt, ap);
1055 #if defined(NEED_SNPRINTF_ONLY)
1056 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1058 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) {
1061 #if defined(NEED_SNPRINTF_ONLY)
1065 const char *p = fmt;
1067 /* In contrast with POSIX, the ISO C99 now says
1068 * that str can be NULL and str_m can be 0.
1069 * This is more useful than the old: if (str_m < 1) return -1; */
1071 #if defined(NEED_SNPRINTF_ONLY)
1077 /* if (str_l < str_m) str[str_l++] = *p++; -- this would be sufficient */
1078 /* but the following code achieves better performance for cases
1079 * where format string is long and contains few conversions */
1080 const char *q = strchr(p+1,'%');
1081 size_t n = !q ? strlen(p) : (q-p);
1082 if (str_l < str_m) {
1083 size_t avail = str_m-str_l;
1084 fast_memcpy(str+str_l, p, (n>avail?avail:n));
1088 const char *starting_p;
1089 size_t min_field_width = 0, precision = 0;
1090 int zero_padding = 0, precision_specified = 0, justify_left = 0;
1091 int alternate_form = 0, force_sign = 0;
1092 int space_for_positive = 1; /* If both the ' ' and '+' flags appear,
1093 the ' ' flag should be ignored. */
1094 char length_modifier = '\0'; /* allowed values: \0, h, l, L */
1095 char tmp[32];/* temporary buffer for simple numeric->string conversion */
1097 const char *str_arg; /* string address in case of string argument */
1098 size_t str_arg_l; /* natural field width of arg without padding
1100 unsigned char uchar_arg;
1101 /* unsigned char argument value - only defined for c conversion.
1102 N.B. standard explicitly states the char argument for
1103 the c conversion is unsigned */
1105 size_t number_of_zeros_to_pad = 0;
1106 /* number of zeros to be inserted for numeric conversions
1107 as required by the precision or minimal field width */
1109 size_t zero_padding_insertion_ind = 0;
1110 /* index into tmp where zero padding is to be inserted */
1112 char fmt_spec = '\0';
1113 /* current conversion specifier character */
1115 str_arg = credits;/* just to make compiler happy (defined but not used)*/
1117 starting_p = p; p++; /* skip '%' */
1119 while (*p == '0' || *p == '-' || *p == '+' ||
1120 *p == ' ' || *p == '#' || *p == '\'') {
1122 case '0': zero_padding = 1; break;
1123 case '-': justify_left = 1; break;
1124 case '+': force_sign = 1; space_for_positive = 0; break;
1125 case ' ': force_sign = 1;
1126 /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */
1127 #ifdef PERL_COMPATIBLE
1128 /* ... but in Perl the last of ' ' and '+' applies */
1129 space_for_positive = 1;
1132 case '#': alternate_form = 1; break;
1137 /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
1139 /* parse field width */
1142 p++; j = va_arg(ap, int);
1143 if (j >= 0) min_field_width = j;
1144 else { min_field_width = -j; justify_left = 1; }
1145 } else if (isdigit((int)(*p))) {
1146 /* size_t could be wider than unsigned int;
1147 make sure we treat argument like common implementations do */
1148 unsigned int uj = *p++ - '0';
1149 while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1150 min_field_width = uj;
1152 /* parse precision */
1154 p++; precision_specified = 1;
1156 int j = va_arg(ap, int);
1158 if (j >= 0) precision = j;
1160 precision_specified = 0; precision = 0;
1162 * Solaris 2.6 man page claims that in this case the precision
1163 * should be set to 0. Digital Unix 4.0, HPUX 10 and BSD man page
1164 * claim that this case should be treated as unspecified precision,
1165 * which is what we do here.
1168 } else if (isdigit((int)(*p))) {
1169 /* size_t could be wider than unsigned int;
1170 make sure we treat argument like common implementations do */
1171 unsigned int uj = *p++ - '0';
1172 while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1176 /* parse 'h', 'l' and 'll' length modifiers */
1177 if (*p == 'h' || *p == 'l') {
1178 length_modifier = *p; p++;
1179 if (length_modifier == 'l' && *p == 'l') { /* double l = long long */
1180 #ifdef SNPRINTF_LONGLONG_SUPPORT
1181 length_modifier = '2'; /* double l encoded as '2' */
1183 length_modifier = 'l'; /* treat it as a single 'l' */
1189 /* common synonyms: */
1191 case 'i': fmt_spec = 'd'; break;
1192 case 'D': fmt_spec = 'd'; length_modifier = 'l'; break;
1193 case 'U': fmt_spec = 'u'; length_modifier = 'l'; break;
1194 case 'O': fmt_spec = 'o'; length_modifier = 'l'; break;
1197 /* get parameter value, do initial processing */
1199 case '%': /* % behaves similar to 's' regarding flags and field widths */
1200 case 'c': /* c behaves similar to 's' regarding flags and field widths */
1202 length_modifier = '\0'; /* wint_t and wchar_t not supported */
1203 /* the result of zero padding flag with non-numeric conversion specifier*/
1204 /* is undefined. Solaris and HPUX 10 does zero padding in this case, */
1205 /* Digital Unix and Linux does not. */
1206 #if !defined(SOLARIS_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
1207 zero_padding = 0; /* turn zero padding off for string conversions */
1214 int j = va_arg(ap, int);
1215 uchar_arg = (unsigned char) j; /* standard demands unsigned char */
1216 str_arg = (const char *) &uchar_arg;
1220 str_arg = va_arg(ap, const char *);
1221 if (!str_arg) str_arg_l = 0;
1222 /* make sure not to address string beyond the specified precision !!! */
1223 else if (!precision_specified) str_arg_l = strlen(str_arg);
1224 /* truncate string if necessary as requested by precision */
1225 else if (precision == 0) str_arg_l = 0;
1227 /* memchr on HP does not like n > 2^31 !!! */
1228 const char *q = memchr(str_arg, '\0',
1229 precision <= 0x7fffffff ? precision : 0x7fffffff);
1230 str_arg_l = !q ? precision : (q-str_arg);
1236 case 'd': case 'u': case 'o': case 'x': case 'X': case 'p': {
1237 /* NOTE: the u, o, x, X and p conversion specifiers imply
1238 the value is unsigned; d implies a signed value */
1241 /* 0 if numeric argument is zero (or if pointer is NULL for 'p'),
1242 +1 if greater than zero (or nonzero for unsigned arguments),
1243 -1 if negative (unsigned argument is never negative) */
1245 int int_arg = 0; unsigned int uint_arg = 0;
1246 /* only defined for length modifier h, or for no length modifiers */
1248 long int long_arg = 0; unsigned long int ulong_arg = 0;
1249 /* only defined for length modifier l */
1251 void *ptr_arg = NULL;
1252 /* pointer argument value -only defined for p conversion */
1254 #ifdef SNPRINTF_LONGLONG_SUPPORT
1255 long long int long_long_arg = 0;
1256 unsigned long long int ulong_long_arg = 0;
1257 /* only defined for length modifier ll */
1259 if (fmt_spec == 'p') {
1260 /* HPUX 10: An l, h, ll or L before any other conversion character
1261 * (other than d, i, u, o, x, or X) is ignored.
1263 * not specified, but seems to behave as HPUX does.
1264 * Solaris: If an h, l, or L appears before any other conversion
1265 * specifier (other than d, i, u, o, x, or X), the behavior
1266 * is undefined. (Actually %hp converts only 16-bits of address
1267 * and %llp treats address as 64-bit data which is incompatible
1268 * with (void *) argument on a 32-bit system).
1270 #ifdef SOLARIS_COMPATIBLE
1271 # ifdef SOLARIS_BUG_COMPATIBLE
1272 /* keep length modifiers even if it represents 'll' */
1274 if (length_modifier == '2') length_modifier = '\0';
1277 length_modifier = '\0';
1279 ptr_arg = va_arg(ap, void *);
1280 if (ptr_arg != NULL) arg_sign = 1;
1281 } else if (fmt_spec == 'd') { /* signed */
1282 switch (length_modifier) {
1285 /* It is non-portable to specify a second argument of char or short
1286 * to va_arg, because arguments seen by the called function
1287 * are not char or short. C converts char and short arguments
1288 * to int before passing them to a function.
1290 int_arg = va_arg(ap, int);
1291 if (int_arg > 0) arg_sign = 1;
1292 else if (int_arg < 0) arg_sign = -1;
1295 long_arg = va_arg(ap, long int);
1296 if (long_arg > 0) arg_sign = 1;
1297 else if (long_arg < 0) arg_sign = -1;
1299 #ifdef SNPRINTF_LONGLONG_SUPPORT
1301 long_long_arg = va_arg(ap, long long int);
1302 if (long_long_arg > 0) arg_sign = 1;
1303 else if (long_long_arg < 0) arg_sign = -1;
1307 } else { /* unsigned */
1308 switch (length_modifier) {
1311 uint_arg = va_arg(ap, unsigned int);
1312 if (uint_arg) arg_sign = 1;
1315 ulong_arg = va_arg(ap, unsigned long int);
1316 if (ulong_arg) arg_sign = 1;
1318 #ifdef SNPRINTF_LONGLONG_SUPPORT
1320 ulong_long_arg = va_arg(ap, unsigned long long int);
1321 if (ulong_long_arg) arg_sign = 1;
1326 str_arg = tmp; str_arg_l = 0;
1328 * For d, i, u, o, x, and X conversions, if precision is specified,
1329 * the '0' flag should be ignored. This is so with Solaris 2.6,
1330 * Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl.
1332 #ifndef PERL_COMPATIBLE
1333 if (precision_specified) zero_padding = 0;
1335 if (fmt_spec == 'd') {
1336 if (force_sign && arg_sign >= 0)
1337 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1338 /* leave negative numbers for sprintf to handle,
1339 to avoid handling tricky cases like (short int)(-32768) */
1340 #ifdef LINUX_COMPATIBLE
1341 } else if (fmt_spec == 'p' && force_sign && arg_sign > 0) {
1342 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1344 } else if (alternate_form) {
1345 if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X') )
1346 { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = fmt_spec; }
1347 /* alternate form should have no effect for p conversion, but ... */
1348 #ifdef HPUX_COMPATIBLE
1349 else if (fmt_spec == 'p'
1350 /* HPUX 10: for an alternate form of p conversion,
1351 * a nonzero result is prefixed by 0x. */
1352 #ifndef HPUX_BUG_COMPATIBLE
1353 /* Actually it uses 0x prefix even for a zero value. */
1356 ) { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = 'x'; }
1359 zero_padding_insertion_ind = str_arg_l;
1360 if (!precision_specified) precision = 1; /* default precision is 1 */
1361 if (precision == 0 && arg_sign == 0
1362 #if defined(HPUX_BUG_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1364 /* HPUX 10 man page claims: With conversion character p the result of
1365 * converting a zero value with a precision of zero is a null string.
1366 * Actually HP returns all zeroes, and Linux returns "(nil)". */
1369 /* converted to null string */
1370 /* When zero value is formatted with an explicit precision 0,
1371 the resulting formatted string is empty (d, i, u, o, x, X, p). */
1373 char f[5]; int f_l = 0;
1374 f[f_l++] = '%'; /* construct a simple format string for sprintf */
1375 if (!length_modifier) { }
1376 else if (length_modifier=='2') { f[f_l++] = 'l'; f[f_l++] = 'l'; }
1377 else f[f_l++] = length_modifier;
1378 f[f_l++] = fmt_spec; f[f_l++] = '\0';
1379 if (fmt_spec == 'p') str_arg_l += sprintf(tmp+str_arg_l, f, ptr_arg);
1380 else if (fmt_spec == 'd') { /* signed */
1381 switch (length_modifier) {
1383 case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, int_arg); break;
1384 case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, long_arg); break;
1385 #ifdef SNPRINTF_LONGLONG_SUPPORT
1386 case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,long_long_arg); break;
1389 } else { /* unsigned */
1390 switch (length_modifier) {
1392 case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, uint_arg); break;
1393 case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, ulong_arg); break;
1394 #ifdef SNPRINTF_LONGLONG_SUPPORT
1395 case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,ulong_long_arg);break;
1399 /* include the optional minus sign and possible "0x"
1400 in the region before the zero padding insertion point */
1401 if (zero_padding_insertion_ind < str_arg_l &&
1402 tmp[zero_padding_insertion_ind] == '-') {
1403 zero_padding_insertion_ind++;
1405 if (zero_padding_insertion_ind+1 < str_arg_l &&
1406 tmp[zero_padding_insertion_ind] == '0' &&
1407 (tmp[zero_padding_insertion_ind+1] == 'x' ||
1408 tmp[zero_padding_insertion_ind+1] == 'X') ) {
1409 zero_padding_insertion_ind += 2;
1412 { size_t num_of_digits = str_arg_l - zero_padding_insertion_ind;
1413 if (alternate_form && fmt_spec == 'o'
1414 #ifdef HPUX_COMPATIBLE /* ("%#.o",0) -> "" */
1417 #ifdef DIGITAL_UNIX_BUG_COMPATIBLE /* ("%#o",0) -> "00" */
1419 /* unless zero is already the first character */
1420 && !(zero_padding_insertion_ind < str_arg_l
1421 && tmp[zero_padding_insertion_ind] == '0')
1423 ) { /* assure leading zero for alternate-form octal numbers */
1424 if (!precision_specified || precision < num_of_digits+1) {
1425 /* precision is increased to force the first character to be zero,
1426 except if a zero value is formatted with an explicit precision
1428 precision = num_of_digits+1; precision_specified = 1;
1431 /* zero padding to specified precision? */
1432 if (num_of_digits < precision)
1433 number_of_zeros_to_pad = precision - num_of_digits;
1435 /* zero padding to specified minimal field width? */
1436 if (!justify_left && zero_padding) {
1437 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1438 if (n > 0) number_of_zeros_to_pad += n;
1442 default: /* unrecognized conversion specifier, keep format string as-is*/
1443 zero_padding = 0; /* turn zero padding off for non-numeric convers. */
1444 #ifndef DIGITAL_UNIX_COMPATIBLE
1445 justify_left = 1; min_field_width = 0; /* reset flags */
1447 #if defined(PERL_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1448 /* keep the entire format string unchanged */
1449 str_arg = starting_p; str_arg_l = p - starting_p;
1450 /* well, not exactly so for Linux, which does something between,
1451 * and I don't feel an urge to imitate it: "%+++++hy" -> "%+y" */
1453 /* discard the unrecognized conversion, just keep *
1454 * the unrecognized conversion character */
1455 str_arg = p; str_arg_l = 0;
1457 if (*p) str_arg_l++; /* include invalid conversion specifier unchanged
1458 if not at end-of-string */
1461 if (*p) p++; /* step over the just processed conversion specifier */
1462 /* insert padding to the left as requested by min_field_width;
1463 this does not include the zero padding in case of numerical conversions*/
1464 if (!justify_left) { /* left padding with blank or zero */
1465 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1467 if (str_l < str_m) {
1468 size_t avail = str_m-str_l;
1469 fast_memset(str+str_l, (zero_padding?'0':' '), (n>avail?avail:n));
1474 /* zero padding as requested by the precision or by the minimal field width
1475 * for numeric conversions required? */
1476 if (number_of_zeros_to_pad <= 0) {
1477 /* will not copy first part of numeric right now, *
1478 * force it to be copied later in its entirety */
1479 zero_padding_insertion_ind = 0;
1481 /* insert first part of numerics (sign or '0x') before zero padding */
1482 int n = zero_padding_insertion_ind;
1484 if (str_l < str_m) {
1485 size_t avail = str_m-str_l;
1486 fast_memcpy(str+str_l, str_arg, (n>avail?avail:n));
1490 /* insert zero padding as requested by the precision or min field width */
1491 n = number_of_zeros_to_pad;
1493 if (str_l < str_m) {
1494 size_t avail = str_m-str_l;
1495 fast_memset(str+str_l, '0', (n>avail?avail:n));
1500 /* insert formatted string
1501 * (or as-is conversion specifier for unknown conversions) */
1502 { int n = str_arg_l - zero_padding_insertion_ind;
1504 if (str_l < str_m) {
1505 size_t avail = str_m-str_l;
1506 fast_memcpy(str+str_l, str_arg+zero_padding_insertion_ind,
1512 /* insert right padding */
1513 if (justify_left) { /* right blank padding to the field width */
1514 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1516 if (str_l < str_m) {
1517 size_t avail = str_m-str_l;
1518 fast_memset(str+str_l, ' ', (n>avail?avail:n));
1525 #if defined(NEED_SNPRINTF_ONLY)
1528 if (str_m > 0) { /* make sure the string is null-terminated
1529 even at the expense of overwriting the last character
1530 (shouldn't happen, but just in case) */
1531 str[str_l <= str_m-1 ? str_l : str_m-1] = '\0';
1533 /* Return the number of characters formatted (excluding trailing null
1534 * character), that is, the number of characters that would have been
1535 * written to the buffer if it were large enough.
1537 * The value of str_l should be returned, but str_l is of unsigned type
1538 * size_t, and snprintf is int, possibly leading to an undetected
1539 * integer overflow, resulting in a negative return value, which is illegal.
1540 * Both XSH5 and ISO C99 (at least the draft) are silent on this issue.
1541 * Should errno be set to EOVERFLOW and EOF returned in this case???
1546 #endif /* ndef HAVE_SNPRINTF */