1 const char miscutil_rcs[] = "$Id: miscutil.c,v 1.70 2012/03/04 11:48:34 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 is useful to "switch" a string.
141 * 1 : s : string to be hashed.
143 * Returns : The string's hash
145 *********************************************************************/
146 unsigned int hash_string( const char* s )
152 h = 5 * h + (unsigned int)*s;
160 /*********************************************************************
162 * Function : strcmpic
164 * Description : Case insensitive string comparison
167 * 1 : s1 = string 1 to compare
168 * 2 : s2 = string 2 to compare
170 * Returns : 0 if s1==s2, Negative if s1<s2, Positive if s1>s2
172 *********************************************************************/
173 int strcmpic(const char *s1, const char *s2)
180 if ( ( *s1 != *s2 ) && ( ijb_tolower(*s1) != ijb_tolower(*s2) ) )
186 return(ijb_tolower(*s1) - ijb_tolower(*s2));
191 /*********************************************************************
193 * Function : strncmpic
195 * Description : Case insensitive string comparison (up to n characters)
198 * 1 : s1 = string 1 to compare
199 * 2 : s2 = string 2 to compare
200 * 3 : n = maximum characters to compare
202 * Returns : 0 if s1==s2, Negative if s1<s2, Positive if s1>s2
204 *********************************************************************/
205 int strncmpic(const char *s1, const char *s2, size_t n)
207 if (n <= (size_t)0) return(0);
213 if ( ( *s1 != *s2 ) && ( ijb_tolower(*s1) != ijb_tolower(*s2) ) )
218 if (--n <= (size_t)0) break;
222 return(ijb_tolower(*s1) - ijb_tolower(*s2));
227 /*********************************************************************
231 * Description : In-situ-eliminate all leading and trailing whitespace
235 * 1 : s : string to be chomped.
237 * Returns : chomped string
239 *********************************************************************/
240 char *chomp(char *string)
245 * strip trailing whitespace
247 p = string + strlen(string);
248 while (p > string && ijb_isspace(*(p-1)))
255 * find end of leading whitespace
258 while (*q && ijb_isspace(*q))
264 * if there was any, move the rest forwards
279 /*********************************************************************
281 * Function : string_append
283 * Description : Reallocate target_string and append text to it.
284 * This makes it easier to append to malloc'd strings.
285 * This is similar to the (removed) strsav(), but
286 * running out of memory isn't catastrophic.
290 * The following style provides sufficient error
291 * checking for this routine, with minimal clutter
292 * in the source code. It is recommended if you
293 * have many calls to this function:
295 * char * s = strdup(...); // don't check for error
296 * string_append(&s, ...); // don't check for error
297 * string_append(&s, ...); // don't check for error
298 * string_append(&s, ...); // don't check for error
299 * if (NULL == s) { ... handle error ... }
303 * char * s = strdup(...); // don't check for error
304 * string_append(&s, ...); // don't check for error
305 * string_append(&s, ...); // don't check for error
306 * if (string_append(&s, ...)) {... handle error ...}
309 * 1 : target_string = Pointer to old text that is to be
310 * extended. *target_string will be free()d by this
311 * routine. target_string must be non-NULL.
312 * If *target_string is NULL, this routine will
313 * do nothing and return with an error - this allows
314 * you to make many calls to this routine and only
315 * check for errors after the last one.
316 * 2 : text_to_append = Text to be appended to old.
319 * Returns : JB_ERR_OK on success, and sets *target_string
320 * to newly malloc'ed appended string. Caller
321 * must free(*target_string).
322 * JB_ERR_MEMORY on out-of-memory. (And free()s
323 * *target_string and sets it to NULL).
324 * JB_ERR_MEMORY if *target_string is NULL.
326 *********************************************************************/
327 jb_err string_append(char **target_string, const char *text_to_append)
333 assert(target_string);
334 assert(text_to_append);
336 if (*target_string == NULL)
338 return JB_ERR_MEMORY;
341 if (*text_to_append == '\0')
346 old_len = strlen(*target_string);
348 new_size = strlen(text_to_append) + old_len + 1;
350 if (NULL == (new_string = realloc(*target_string, new_size)))
352 free(*target_string);
354 *target_string = NULL;
355 return JB_ERR_MEMORY;
358 strlcpy(new_string + old_len, text_to_append, new_size - old_len);
360 *target_string = new_string;
365 /*********************************************************************
367 * Function : string_join
369 * Description : Join two strings together. Frees BOTH the original
370 * strings. If either or both input strings are NULL,
371 * fails as if it had run out of memory.
373 * For comparison, string_append requires that the
374 * second string is non-NULL, and doesn't free it.
376 * Rationale: Too often, we want to do
377 * string_append(s, html_encode(s2)). That assert()s
378 * if s2 is NULL or if html_encode() runs out of memory.
379 * It also leaks memory. Proper checking is cumbersome.
380 * The solution: string_join(s, html_encode(s2)) is safe,
381 * and will free the memory allocated by html_encode().
384 * 1 : target_string = Pointer to old text that is to be
385 * extended. *target_string will be free()d by this
386 * routine. target_string must be non-NULL.
387 * 2 : text_to_append = Text to be appended to old.
389 * Returns : JB_ERR_OK on success, and sets *target_string
390 * to newly malloc'ed appended string. Caller
391 * must free(*target_string).
392 * JB_ERR_MEMORY on out-of-memory, or if
393 * *target_string or text_to_append is NULL. (In
394 * this case, frees *target_string and text_to_append,
395 * sets *target_string to NULL).
397 *********************************************************************/
398 jb_err string_join(char **target_string, char *text_to_append)
402 assert(target_string);
404 if (text_to_append == NULL)
406 freez(*target_string);
407 return JB_ERR_MEMORY;
410 err = string_append(target_string, text_to_append);
412 freez(text_to_append);
418 /*********************************************************************
420 * Function : string_toupper
422 * Description : Produce a copy of string with all convertible
423 * characters converted to uppercase.
426 * 1 : string = string to convert
428 * Returns : Uppercase copy of string if possible,
429 * NULL on out-of-memory or if string was NULL.
431 *********************************************************************/
432 char *string_toupper(const char *string)
437 if (!string || ((result = (char *) zalloc(strlen(string) + 1)) == NULL))
447 *p++ = (char)toupper((int) *q++);
455 /*********************************************************************
459 * Description : Duplicate the first n characters of a string that may
460 * contain '\0' characters.
463 * 1 : string = string to be duplicated
464 * 2 : len = number of bytes to duplicate
466 * Returns : pointer to copy, or NULL if failiure
468 *********************************************************************/
469 char *bindup(const char *string, size_t len)
473 duplicate = (char *)malloc(len);
474 if (NULL != duplicate)
476 memcpy(duplicate, string, len);
484 /*********************************************************************
486 * Function : make_path
488 * Description : Takes a directory name and a file name, returns
489 * the complete path. Handles windows/unix differences.
490 * If the file name is already an absolute path, or if
491 * the directory name is NULL or empty, it returns
495 * 1 : dir: Name of directory or NULL for none.
496 * 2 : file: Name of file. Should not be NULL or empty.
498 * Returns : "dir/file" (Or on windows, "dir\file").
499 * It allocates the string on the heap. Caller frees.
500 * Returns NULL in error (i.e. NULL file or out of
503 *********************************************************************/
504 char * make_path(const char * dir, const char * file)
515 strncpy(path,dir+2,512);
519 strncpy(path,dir+1,512);
524 strncpy(path,dir,512);
532 if(AddPart(path,file,512))
540 #else /* ndef AMIGA */
542 if ((file == NULL) || (*file == '\0'))
544 return NULL; /* Error */
547 if ((dir == NULL) || (*dir == '\0') /* No directory specified */
548 #if defined(_WIN32) || defined(__OS2__)
549 || (*file == '\\') || (file[1] == ':') /* Absolute path (DOS) */
550 #else /* ifndef _WIN32 || __OS2__ */
551 || (*file == '/') /* Absolute path (U*ix) */
552 #endif /* ifndef _WIN32 || __OS2__ */
560 size_t path_size = strlen(dir) + strlen(file) + 2; /* +2 for trailing (back)slash and \0 */
563 if ( *dir != '/' && basedir && *basedir )
566 * Relative path, so start with the base directory.
568 path_size += strlen(basedir) + 1; /* +1 for the slash */
569 path = malloc(path_size);
570 if (!path ) log_error(LOG_LEVEL_FATAL, "malloc failed!");
571 strlcpy(path, basedir, path_size);
572 strlcat(path, "/", path_size);
573 strlcat(path, dir, path_size);
576 #endif /* defined unix */
578 path = malloc(path_size);
579 if (!path ) log_error(LOG_LEVEL_FATAL, "malloc failed!");
580 strlcpy(path, dir, path_size);
583 assert(NULL != path);
584 #if defined(_WIN32) || defined(__OS2__)
585 if(path[strlen(path)-1] != '\\')
587 strlcat(path, "\\", path_size);
589 #else /* ifndef _WIN32 || __OS2__ */
590 if(path[strlen(path)-1] != '/')
592 strlcat(path, "/", path_size);
594 #endif /* ifndef _WIN32 || __OS2__ */
595 strlcat(path, file, path_size);
599 #endif /* ndef AMIGA */
603 /*********************************************************************
605 * Function : pick_from_range
607 * Description : Pick a positive number out of a given range.
608 * Should only be used if randomness would be nice,
609 * but isn't really necessary.
612 * 1 : range: Highest possible number to pick.
614 * Returns : Picked number.
616 *********************************************************************/
617 long int pick_from_range(long int range)
621 static unsigned long seed = 0;
622 #endif /* def _WIN32 */
627 if (range <= 0) return 0;
630 number = random() % range + 1;
631 #elif defined(MUTEX_LOCKS_AVAILABLE)
632 privoxy_mutex_lock(&rand_mutex);
636 seed = (unsigned long)(GetCurrentThreadId()+GetTickCount());
639 seed = (unsigned long)((rand() << 16) + rand());
640 #endif /* def _WIN32 */
641 number = (unsigned long)((rand() << 16) + (rand())) % (unsigned long)(range + 1);
642 privoxy_mutex_unlock(&rand_mutex);
645 * XXX: Which platforms reach this and are there
646 * better options than just using rand() and hoping
649 log_error(LOG_LEVEL_INFO, "No thread-safe PRNG available? Header time randomization "
650 "might cause crashes, predictable results or even combine these fine options.");
651 number = rand() % (long int)(range + 1);
653 #endif /* (def HAVE_RANDOM) */
659 #ifdef USE_PRIVOXY_STRLCPY
660 /*********************************************************************
662 * Function : privoxy_strlcpy
664 * Description : strlcpy(3) look-alike for those without decent libc.
667 * 1 : destination: buffer to copy into.
668 * 2 : source: String to copy.
669 * 3 : size: Size of destination buffer.
671 * Returns : The length of the string that privoxy_strlcpy() tried to create.
673 *********************************************************************/
674 size_t privoxy_strlcpy(char *destination, const char *source, const size_t size)
678 snprintf(destination, size, "%s", source);
680 * Platforms that lack strlcpy() also tend to have
681 * a broken snprintf implementation that doesn't
682 * guarantee nul termination.
684 * XXX: the configure script should detect and reject those.
686 destination[size-1] = '\0';
688 return strlen(source);
690 #endif /* def USE_PRIVOXY_STRLCPY */
694 /*********************************************************************
696 * Function : privoxy_strlcat
698 * Description : strlcat(3) look-alike for those without decent libc.
701 * 1 : destination: C string.
702 * 2 : source: String to copy.
703 * 3 : size: Size of destination buffer.
705 * Returns : The length of the string that privoxy_strlcat() tried to create.
707 *********************************************************************/
708 size_t privoxy_strlcat(char *destination, const char *source, const size_t size)
710 const size_t old_length = strlen(destination);
711 return old_length + strlcpy(destination + old_length, source, size - old_length);
713 #endif /* ndef HAVE_STRLCAT */
716 #if !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV)
717 /*********************************************************************
721 * Description : libc replacement function for the inverse of gmtime().
722 * Copyright (C) 2004 Free Software Foundation, Inc.
724 * Code originally copied from GnuPG, modifications done
725 * for Privoxy: style changed, #ifdefs for _WIN32 added
726 * to have it work on mingw32.
728 * XXX: It's very unlikely to happen, but if the malloc()
729 * call fails the time zone will be permanently set to UTC.
732 * 1 : tm: Broken-down time struct.
734 * Returns : tm converted into time_t seconds.
736 *********************************************************************/
737 time_t timegm(struct tm *tm)
750 old_zone = malloc(3 + strlen(zone) + 1);
753 strcpy(old_zone, "TZ=");
754 strcat(old_zone, zone);
758 #endif /* def _WIN32 */
765 #elif defined(_WIN32)
775 #endif /* !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV) */
778 #ifndef HAVE_SNPRINTF
780 * What follows is a portable snprintf routine, written by Mark Martinec.
781 * See: http://www.ijs.si/software/snprintf/
784 - a portable implementation of snprintf,
785 including vsnprintf.c, asnprintf, vasnprintf, asprintf, vasprintf
787 snprintf is a routine to convert numeric and string arguments to
788 formatted strings. It is similar to sprintf(3) provided in a system's
789 C library, yet it requires an additional argument - the buffer size -
790 and it guarantees never to store anything beyond the given buffer,
791 regardless of the format or arguments to be formatted. Some newer
792 operating systems do provide snprintf in their C library, but many do
793 not or do provide an inadequate (slow or idiosyncratic) version, which
794 calls for a portable implementation of this routine.
798 Mark Martinec <mark.martinec@ijs.si>, April 1999, June 2000
799 Copyright © 1999, Mark Martinec
803 #define PORTABLE_SNPRINTF_VERSION_MAJOR 2
804 #define PORTABLE_SNPRINTF_VERSION_MINOR 2
806 #if defined(NEED_ASPRINTF) || defined(NEED_ASNPRINTF) || defined(NEED_VASPRINTF) || defined(NEED_VASNPRINTF)
807 # if defined(NEED_SNPRINTF_ONLY)
808 # undef NEED_SNPRINTF_ONLY
810 # if !defined(PREFER_PORTABLE_SNPRINTF)
811 # define PREFER_PORTABLE_SNPRINTF
815 #if defined(SOLARIS_BUG_COMPATIBLE) && !defined(SOLARIS_COMPATIBLE)
816 #define SOLARIS_COMPATIBLE
819 #if defined(HPUX_BUG_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
820 #define HPUX_COMPATIBLE
823 #if defined(DIGITAL_UNIX_BUG_COMPATIBLE) && !defined(DIGITAL_UNIX_COMPATIBLE)
824 #define DIGITAL_UNIX_COMPATIBLE
827 #if defined(PERL_BUG_COMPATIBLE) && !defined(PERL_COMPATIBLE)
828 #define PERL_COMPATIBLE
831 #if defined(LINUX_BUG_COMPATIBLE) && !defined(LINUX_COMPATIBLE)
832 #define LINUX_COMPATIBLE
835 #include <sys/types.h>
846 #define isdigit(c) ((c) >= '0' && (c) <= '9')
848 /* For copying strings longer or equal to 'breakeven_point'
849 * it is more efficient to call memcpy() than to do it inline.
850 * The value depends mostly on the processor architecture,
851 * but also on the compiler and its optimization capabilities.
852 * The value is not critical, some small value greater than zero
853 * will be just fine if you don't care to squeeze every drop
854 * of performance out of the code.
856 * Small values favor memcpy, large values favor inline code.
858 #if defined(__alpha__) || defined(__alpha)
859 # define breakeven_point 2 /* AXP (DEC Alpha) - gcc or cc or egcs */
861 #if defined(__i386__) || defined(__i386)
862 # define breakeven_point 12 /* Intel Pentium/Linux - gcc 2.96 */
865 # define breakeven_point 10 /* HP-PA - gcc */
867 #if defined(__sparc__) || defined(__sparc)
868 # define breakeven_point 33 /* Sun Sparc 5 - gcc 2.8.1 */
871 /* some other values of possible interest: */
872 /* #define breakeven_point 8 */ /* VAX 4000 - vaxc */
873 /* #define breakeven_point 19 */ /* VAX 4000 - gcc 2.7.0 */
875 #ifndef breakeven_point
876 # define breakeven_point 6 /* some reasonable one-size-fits-all value */
879 #define fast_memcpy(d,s,n) \
880 { register size_t nn = (size_t)(n); \
881 if (nn >= breakeven_point) memcpy((d), (s), nn); \
882 else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
883 register char *dd; register const char *ss; \
884 for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } }
886 #define fast_memset(d,c,n) \
887 { register size_t nn = (size_t)(n); \
888 if (nn >= breakeven_point) memset((d), (int)(c), nn); \
889 else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
890 register char *dd; register const int cc=(int)(c); \
891 for (dd=(d); nn>0; nn--) *dd++ = cc; } }
895 #if defined(NEED_ASPRINTF)
896 int asprintf (char **ptr, const char *fmt, /*args*/ ...);
898 #if defined(NEED_VASPRINTF)
899 int vasprintf (char **ptr, const char *fmt, va_list ap);
901 #if defined(NEED_ASNPRINTF)
902 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...);
904 #if defined(NEED_VASNPRINTF)
905 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap);
908 #if defined(HAVE_SNPRINTF)
909 /* declare our portable snprintf routine under name portable_snprintf */
910 /* declare our portable vsnprintf routine under name portable_vsnprintf */
912 /* declare our portable routines under names snprintf and vsnprintf */
913 #define portable_snprintf snprintf
914 #if !defined(NEED_SNPRINTF_ONLY)
915 #define portable_vsnprintf vsnprintf
919 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
920 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...);
921 #if !defined(NEED_SNPRINTF_ONLY)
922 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap);
928 static char credits[] = "\n\
929 @(#)snprintf.c, v2.2: Mark Martinec, <mark.martinec@ijs.si>\n\
930 @(#)snprintf.c, v2.2: Copyright 1999, Mark Martinec. Frontier Artistic License applies.\n\
931 @(#)snprintf.c, v2.2: http://www.ijs.si/software/snprintf/\n";
933 #if defined(NEED_ASPRINTF)
934 int asprintf(char **ptr, const char *fmt, /*args*/ ...) {
940 va_start(ap, fmt); /* measure the required size */
941 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
943 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
944 *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
945 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
949 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
951 assert(str_l2 == str_l);
957 #if defined(NEED_VASPRINTF)
958 int vasprintf(char **ptr, const char *fmt, va_list ap) {
964 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
965 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
968 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
969 *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
970 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
972 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
973 assert(str_l2 == str_l);
979 #if defined(NEED_ASNPRINTF)
980 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...) {
985 va_start(ap, fmt); /* measure the required size */
986 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
988 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
989 if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1; /* truncate */
990 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
991 if (str_m == 0) { /* not interested in resulting string, just return size */
993 *ptr = (char *) malloc(str_m);
994 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
998 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1000 assert(str_l2 == str_l);
1007 #if defined(NEED_VASNPRINTF)
1008 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap) {
1013 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
1014 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1017 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1018 if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1; /* truncate */
1019 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1020 if (str_m == 0) { /* not interested in resulting string, just return size */
1022 *ptr = (char *) malloc(str_m);
1023 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1025 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1026 assert(str_l2 == str_l);
1034 * If the system does have snprintf and the portable routine is not
1035 * specifically required, this module produces no code for snprintf/vsnprintf.
1037 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1039 #if !defined(NEED_SNPRINTF_ONLY)
1040 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1045 str_l = portable_vsnprintf(str, str_m, fmt, ap);
1051 #if defined(NEED_SNPRINTF_ONLY)
1052 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1054 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) {
1057 #if defined(NEED_SNPRINTF_ONLY)
1061 const char *p = fmt;
1063 /* In contrast with POSIX, the ISO C99 now says
1064 * that str can be NULL and str_m can be 0.
1065 * This is more useful than the old: if (str_m < 1) return -1; */
1067 #if defined(NEED_SNPRINTF_ONLY)
1073 /* if (str_l < str_m) str[str_l++] = *p++; -- this would be sufficient */
1074 /* but the following code achieves better performance for cases
1075 * where format string is long and contains few conversions */
1076 const char *q = strchr(p+1,'%');
1077 size_t n = !q ? strlen(p) : (q-p);
1078 if (str_l < str_m) {
1079 size_t avail = str_m-str_l;
1080 fast_memcpy(str+str_l, p, (n>avail?avail:n));
1084 const char *starting_p;
1085 size_t min_field_width = 0, precision = 0;
1086 int zero_padding = 0, precision_specified = 0, justify_left = 0;
1087 int alternate_form = 0, force_sign = 0;
1088 int space_for_positive = 1; /* If both the ' ' and '+' flags appear,
1089 the ' ' flag should be ignored. */
1090 char length_modifier = '\0'; /* allowed values: \0, h, l, L */
1091 char tmp[32];/* temporary buffer for simple numeric->string conversion */
1093 const char *str_arg; /* string address in case of string argument */
1094 size_t str_arg_l; /* natural field width of arg without padding
1096 unsigned char uchar_arg;
1097 /* unsigned char argument value - only defined for c conversion.
1098 N.B. standard explicitly states the char argument for
1099 the c conversion is unsigned */
1101 size_t number_of_zeros_to_pad = 0;
1102 /* number of zeros to be inserted for numeric conversions
1103 as required by the precision or minimal field width */
1105 size_t zero_padding_insertion_ind = 0;
1106 /* index into tmp where zero padding is to be inserted */
1108 char fmt_spec = '\0';
1109 /* current conversion specifier character */
1111 str_arg = credits;/* just to make compiler happy (defined but not used)*/
1113 starting_p = p; p++; /* skip '%' */
1115 while (*p == '0' || *p == '-' || *p == '+' ||
1116 *p == ' ' || *p == '#' || *p == '\'') {
1118 case '0': zero_padding = 1; break;
1119 case '-': justify_left = 1; break;
1120 case '+': force_sign = 1; space_for_positive = 0; break;
1121 case ' ': force_sign = 1;
1122 /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */
1123 #ifdef PERL_COMPATIBLE
1124 /* ... but in Perl the last of ' ' and '+' applies */
1125 space_for_positive = 1;
1128 case '#': alternate_form = 1; break;
1133 /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
1135 /* parse field width */
1138 p++; j = va_arg(ap, int);
1139 if (j >= 0) min_field_width = j;
1140 else { min_field_width = -j; justify_left = 1; }
1141 } else if (isdigit((int)(*p))) {
1142 /* size_t could be wider than unsigned int;
1143 make sure we treat argument like common implementations do */
1144 unsigned int uj = *p++ - '0';
1145 while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1146 min_field_width = uj;
1148 /* parse precision */
1150 p++; precision_specified = 1;
1152 int j = va_arg(ap, int);
1154 if (j >= 0) precision = j;
1156 precision_specified = 0; precision = 0;
1158 * Solaris 2.6 man page claims that in this case the precision
1159 * should be set to 0. Digital Unix 4.0, HPUX 10 and BSD man page
1160 * claim that this case should be treated as unspecified precision,
1161 * which is what we do here.
1164 } else if (isdigit((int)(*p))) {
1165 /* size_t could be wider than unsigned int;
1166 make sure we treat argument like common implementations do */
1167 unsigned int uj = *p++ - '0';
1168 while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1172 /* parse 'h', 'l' and 'll' length modifiers */
1173 if (*p == 'h' || *p == 'l') {
1174 length_modifier = *p; p++;
1175 if (length_modifier == 'l' && *p == 'l') { /* double l = long long */
1176 #ifdef SNPRINTF_LONGLONG_SUPPORT
1177 length_modifier = '2'; /* double l encoded as '2' */
1179 length_modifier = 'l'; /* treat it as a single 'l' */
1185 /* common synonyms: */
1187 case 'i': fmt_spec = 'd'; break;
1188 case 'D': fmt_spec = 'd'; length_modifier = 'l'; break;
1189 case 'U': fmt_spec = 'u'; length_modifier = 'l'; break;
1190 case 'O': fmt_spec = 'o'; length_modifier = 'l'; break;
1193 /* get parameter value, do initial processing */
1195 case '%': /* % behaves similar to 's' regarding flags and field widths */
1196 case 'c': /* c behaves similar to 's' regarding flags and field widths */
1198 length_modifier = '\0'; /* wint_t and wchar_t not supported */
1199 /* the result of zero padding flag with non-numeric conversion specifier*/
1200 /* is undefined. Solaris and HPUX 10 does zero padding in this case, */
1201 /* Digital Unix and Linux does not. */
1202 #if !defined(SOLARIS_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
1203 zero_padding = 0; /* turn zero padding off for string conversions */
1210 int j = va_arg(ap, int);
1211 uchar_arg = (unsigned char) j; /* standard demands unsigned char */
1212 str_arg = (const char *) &uchar_arg;
1216 str_arg = va_arg(ap, const char *);
1217 if (!str_arg) str_arg_l = 0;
1218 /* make sure not to address string beyond the specified precision !!! */
1219 else if (!precision_specified) str_arg_l = strlen(str_arg);
1220 /* truncate string if necessary as requested by precision */
1221 else if (precision == 0) str_arg_l = 0;
1223 /* memchr on HP does not like n > 2^31 !!! */
1224 const char *q = memchr(str_arg, '\0',
1225 precision <= 0x7fffffff ? precision : 0x7fffffff);
1226 str_arg_l = !q ? precision : (q-str_arg);
1232 case 'd': case 'u': case 'o': case 'x': case 'X': case 'p': {
1233 /* NOTE: the u, o, x, X and p conversion specifiers imply
1234 the value is unsigned; d implies a signed value */
1237 /* 0 if numeric argument is zero (or if pointer is NULL for 'p'),
1238 +1 if greater than zero (or nonzero for unsigned arguments),
1239 -1 if negative (unsigned argument is never negative) */
1241 int int_arg = 0; unsigned int uint_arg = 0;
1242 /* only defined for length modifier h, or for no length modifiers */
1244 long int long_arg = 0; unsigned long int ulong_arg = 0;
1245 /* only defined for length modifier l */
1247 void *ptr_arg = NULL;
1248 /* pointer argument value -only defined for p conversion */
1250 #ifdef SNPRINTF_LONGLONG_SUPPORT
1251 long long int long_long_arg = 0;
1252 unsigned long long int ulong_long_arg = 0;
1253 /* only defined for length modifier ll */
1255 if (fmt_spec == 'p') {
1256 /* HPUX 10: An l, h, ll or L before any other conversion character
1257 * (other than d, i, u, o, x, or X) is ignored.
1259 * not specified, but seems to behave as HPUX does.
1260 * Solaris: If an h, l, or L appears before any other conversion
1261 * specifier (other than d, i, u, o, x, or X), the behavior
1262 * is undefined. (Actually %hp converts only 16-bits of address
1263 * and %llp treats address as 64-bit data which is incompatible
1264 * with (void *) argument on a 32-bit system).
1266 #ifdef SOLARIS_COMPATIBLE
1267 # ifdef SOLARIS_BUG_COMPATIBLE
1268 /* keep length modifiers even if it represents 'll' */
1270 if (length_modifier == '2') length_modifier = '\0';
1273 length_modifier = '\0';
1275 ptr_arg = va_arg(ap, void *);
1276 if (ptr_arg != NULL) arg_sign = 1;
1277 } else if (fmt_spec == 'd') { /* signed */
1278 switch (length_modifier) {
1281 /* It is non-portable to specify a second argument of char or short
1282 * to va_arg, because arguments seen by the called function
1283 * are not char or short. C converts char and short arguments
1284 * to int before passing them to a function.
1286 int_arg = va_arg(ap, int);
1287 if (int_arg > 0) arg_sign = 1;
1288 else if (int_arg < 0) arg_sign = -1;
1291 long_arg = va_arg(ap, long int);
1292 if (long_arg > 0) arg_sign = 1;
1293 else if (long_arg < 0) arg_sign = -1;
1295 #ifdef SNPRINTF_LONGLONG_SUPPORT
1297 long_long_arg = va_arg(ap, long long int);
1298 if (long_long_arg > 0) arg_sign = 1;
1299 else if (long_long_arg < 0) arg_sign = -1;
1303 } else { /* unsigned */
1304 switch (length_modifier) {
1307 uint_arg = va_arg(ap, unsigned int);
1308 if (uint_arg) arg_sign = 1;
1311 ulong_arg = va_arg(ap, unsigned long int);
1312 if (ulong_arg) arg_sign = 1;
1314 #ifdef SNPRINTF_LONGLONG_SUPPORT
1316 ulong_long_arg = va_arg(ap, unsigned long long int);
1317 if (ulong_long_arg) arg_sign = 1;
1322 str_arg = tmp; str_arg_l = 0;
1324 * For d, i, u, o, x, and X conversions, if precision is specified,
1325 * the '0' flag should be ignored. This is so with Solaris 2.6,
1326 * Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl.
1328 #ifndef PERL_COMPATIBLE
1329 if (precision_specified) zero_padding = 0;
1331 if (fmt_spec == 'd') {
1332 if (force_sign && arg_sign >= 0)
1333 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1334 /* leave negative numbers for sprintf to handle,
1335 to avoid handling tricky cases like (short int)(-32768) */
1336 #ifdef LINUX_COMPATIBLE
1337 } else if (fmt_spec == 'p' && force_sign && arg_sign > 0) {
1338 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1340 } else if (alternate_form) {
1341 if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X') )
1342 { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = fmt_spec; }
1343 /* alternate form should have no effect for p conversion, but ... */
1344 #ifdef HPUX_COMPATIBLE
1345 else if (fmt_spec == 'p'
1346 /* HPUX 10: for an alternate form of p conversion,
1347 * a nonzero result is prefixed by 0x. */
1348 #ifndef HPUX_BUG_COMPATIBLE
1349 /* Actually it uses 0x prefix even for a zero value. */
1352 ) { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = 'x'; }
1355 zero_padding_insertion_ind = str_arg_l;
1356 if (!precision_specified) precision = 1; /* default precision is 1 */
1357 if (precision == 0 && arg_sign == 0
1358 #if defined(HPUX_BUG_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1360 /* HPUX 10 man page claims: With conversion character p the result of
1361 * converting a zero value with a precision of zero is a null string.
1362 * Actually HP returns all zeroes, and Linux returns "(nil)". */
1365 /* converted to null string */
1366 /* When zero value is formatted with an explicit precision 0,
1367 the resulting formatted string is empty (d, i, u, o, x, X, p). */
1369 char f[5]; int f_l = 0;
1370 f[f_l++] = '%'; /* construct a simple format string for sprintf */
1371 if (!length_modifier) { }
1372 else if (length_modifier=='2') { f[f_l++] = 'l'; f[f_l++] = 'l'; }
1373 else f[f_l++] = length_modifier;
1374 f[f_l++] = fmt_spec; f[f_l++] = '\0';
1375 if (fmt_spec == 'p') str_arg_l += sprintf(tmp+str_arg_l, f, ptr_arg);
1376 else if (fmt_spec == 'd') { /* signed */
1377 switch (length_modifier) {
1379 case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, int_arg); break;
1380 case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, long_arg); break;
1381 #ifdef SNPRINTF_LONGLONG_SUPPORT
1382 case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,long_long_arg); break;
1385 } else { /* unsigned */
1386 switch (length_modifier) {
1388 case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, uint_arg); break;
1389 case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, ulong_arg); break;
1390 #ifdef SNPRINTF_LONGLONG_SUPPORT
1391 case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,ulong_long_arg);break;
1395 /* include the optional minus sign and possible "0x"
1396 in the region before the zero padding insertion point */
1397 if (zero_padding_insertion_ind < str_arg_l &&
1398 tmp[zero_padding_insertion_ind] == '-') {
1399 zero_padding_insertion_ind++;
1401 if (zero_padding_insertion_ind+1 < str_arg_l &&
1402 tmp[zero_padding_insertion_ind] == '0' &&
1403 (tmp[zero_padding_insertion_ind+1] == 'x' ||
1404 tmp[zero_padding_insertion_ind+1] == 'X') ) {
1405 zero_padding_insertion_ind += 2;
1408 { size_t num_of_digits = str_arg_l - zero_padding_insertion_ind;
1409 if (alternate_form && fmt_spec == 'o'
1410 #ifdef HPUX_COMPATIBLE /* ("%#.o",0) -> "" */
1413 #ifdef DIGITAL_UNIX_BUG_COMPATIBLE /* ("%#o",0) -> "00" */
1415 /* unless zero is already the first character */
1416 && !(zero_padding_insertion_ind < str_arg_l
1417 && tmp[zero_padding_insertion_ind] == '0')
1419 ) { /* assure leading zero for alternate-form octal numbers */
1420 if (!precision_specified || precision < num_of_digits+1) {
1421 /* precision is increased to force the first character to be zero,
1422 except if a zero value is formatted with an explicit precision
1424 precision = num_of_digits+1; precision_specified = 1;
1427 /* zero padding to specified precision? */
1428 if (num_of_digits < precision)
1429 number_of_zeros_to_pad = precision - num_of_digits;
1431 /* zero padding to specified minimal field width? */
1432 if (!justify_left && zero_padding) {
1433 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1434 if (n > 0) number_of_zeros_to_pad += n;
1438 default: /* unrecognized conversion specifier, keep format string as-is*/
1439 zero_padding = 0; /* turn zero padding off for non-numeric convers. */
1440 #ifndef DIGITAL_UNIX_COMPATIBLE
1441 justify_left = 1; min_field_width = 0; /* reset flags */
1443 #if defined(PERL_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1444 /* keep the entire format string unchanged */
1445 str_arg = starting_p; str_arg_l = p - starting_p;
1446 /* well, not exactly so for Linux, which does something between,
1447 * and I don't feel an urge to imitate it: "%+++++hy" -> "%+y" */
1449 /* discard the unrecognized conversion, just keep *
1450 * the unrecognized conversion character */
1451 str_arg = p; str_arg_l = 0;
1453 if (*p) str_arg_l++; /* include invalid conversion specifier unchanged
1454 if not at end-of-string */
1457 if (*p) p++; /* step over the just processed conversion specifier */
1458 /* insert padding to the left as requested by min_field_width;
1459 this does not include the zero padding in case of numerical conversions*/
1460 if (!justify_left) { /* left padding with blank or zero */
1461 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1463 if (str_l < str_m) {
1464 size_t avail = str_m-str_l;
1465 fast_memset(str+str_l, (zero_padding?'0':' '), (n>avail?avail:n));
1470 /* zero padding as requested by the precision or by the minimal field width
1471 * for numeric conversions required? */
1472 if (number_of_zeros_to_pad <= 0) {
1473 /* will not copy first part of numeric right now, *
1474 * force it to be copied later in its entirety */
1475 zero_padding_insertion_ind = 0;
1477 /* insert first part of numerics (sign or '0x') before zero padding */
1478 int n = zero_padding_insertion_ind;
1480 if (str_l < str_m) {
1481 size_t avail = str_m-str_l;
1482 fast_memcpy(str+str_l, str_arg, (n>avail?avail:n));
1486 /* insert zero padding as requested by the precision or min field width */
1487 n = number_of_zeros_to_pad;
1489 if (str_l < str_m) {
1490 size_t avail = str_m-str_l;
1491 fast_memset(str+str_l, '0', (n>avail?avail:n));
1496 /* insert formatted string
1497 * (or as-is conversion specifier for unknown conversions) */
1498 { int n = str_arg_l - zero_padding_insertion_ind;
1500 if (str_l < str_m) {
1501 size_t avail = str_m-str_l;
1502 fast_memcpy(str+str_l, str_arg+zero_padding_insertion_ind,
1508 /* insert right padding */
1509 if (justify_left) { /* right blank padding to the field width */
1510 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1512 if (str_l < str_m) {
1513 size_t avail = str_m-str_l;
1514 fast_memset(str+str_l, ' ', (n>avail?avail:n));
1521 #if defined(NEED_SNPRINTF_ONLY)
1524 if (str_m > 0) { /* make sure the string is null-terminated
1525 even at the expense of overwriting the last character
1526 (shouldn't happen, but just in case) */
1527 str[str_l <= str_m-1 ? str_l : str_m-1] = '\0';
1529 /* Return the number of characters formatted (excluding trailing null
1530 * character), that is, the number of characters that would have been
1531 * written to the buffer if it were large enough.
1533 * The value of str_l should be returned, but str_l is of unsigned type
1534 * size_t, and snprintf is int, possibly leading to an undetected
1535 * integer overflow, resulting in a negative return value, which is illegal.
1536 * Both XSH5 and ISO C99 (at least the draft) are silent on this issue.
1537 * Should errno be set to EOVERFLOW and EOF returned in this case???
1542 #endif /* ndef HAVE_SNPRINTF */