1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/miscutil.c,v $
5 * Purpose : zalloc, hash_string, strcmpic, strncmpic, and
6 * MinGW32 strdup functions. These are each too small
7 * to deserve their own file but don't really fit in
10 * Copyright : Written by and Copyright (C) 2001-2020 the
11 * Privoxy team. https://www.privoxy.org/
13 * Based on the Internet Junkbuster originally written
14 * by and Copyright (C) 1997 Anonymous Coders and
15 * Junkbusters Corporation. http://www.junkbusters.com
17 * The timegm replacement function was taken from GnuPG,
18 * Copyright (C) 2004 Free Software Foundation, Inc.
20 * The snprintf replacement function is written by
21 * Mark Martinec who also holds the copyright. It can be
22 * used under the terms of the GPL or the terms of the
23 * "Frontier Artistic License".
25 * This program is free software; you can redistribute it
26 * and/or modify it under the terms of the GNU General
27 * Public License as published by the Free Software
28 * Foundation; either version 2 of the License, or (at
29 * your option) any later version.
31 * This program is distributed in the hope that it will
32 * be useful, but WITHOUT ANY WARRANTY; without even the
33 * implied warranty of MERCHANTABILITY or FITNESS FOR A
34 * PARTICULAR PURPOSE. See the GNU General Public
35 * License for more details.
37 * The GNU General Public License should be included with
38 * this file. If not, you can view it at
39 * http://www.gnu.org/copyleft/gpl.html
40 * or write to the Free Software Foundation, Inc., 59
41 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
43 *********************************************************************/
49 #include <sys/types.h>
53 #endif /* #if !defined(_WIN32) */
58 #if !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV)
60 #endif /* !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV) */
67 /*********************************************************************
71 * Description : Returns allocated memory that is initialized
75 * 1 : size = Size of memory chunk to return.
77 * Returns : Pointer to newly alloc'd memory chunk.
79 *********************************************************************/
80 void *zalloc(size_t size)
85 ret = calloc(1, size);
87 #warning calloc appears to be unavailable. Your platform will become unsupported in the future
88 if ((ret = (void *)malloc(size)) != NULL)
99 /*********************************************************************
101 * Function : zalloc_or_die
103 * Description : zalloc wrapper that either succeeds or causes
104 * program termination.
106 * Useful in situations were the string length is
107 * "small" and zalloc() failures couldn't be handled
108 * better anyway. In case of debug builds, failures
109 * trigger an assert().
112 * 1 : size = Size of memory chunk to return.
114 * Returns : Pointer to newly malloc'd memory chunk.
116 *********************************************************************/
117 void *zalloc_or_die(size_t size)
121 buffer = zalloc(size);
124 assert(buffer != NULL);
125 log_error(LOG_LEVEL_FATAL, "Out of memory in zalloc_or_die().");
133 /*********************************************************************
135 * Function : strdup_or_die
137 * Description : strdup wrapper that either succeeds or causes
138 * program termination.
140 * Useful in situations were the string length is
141 * "small" and strdup() failures couldn't be handled
142 * better anyway. In case of debug builds, failures
143 * trigger an assert().
146 * 1 : str = String to duplicate
148 * Returns : Pointer to newly strdup'd copy of the string.
150 *********************************************************************/
151 char *strdup_or_die(const char *str)
155 new_str = strdup(str);
159 assert(new_str != NULL);
160 log_error(LOG_LEVEL_FATAL, "Out of memory in strdup_or_die().");
169 /*********************************************************************
171 * Function : malloc_or_die
173 * Description : malloc wrapper that either succeeds or causes
174 * program termination.
176 * Useful in situations were the buffer size is "small"
177 * and malloc() failures couldn't be handled better
178 * anyway. In case of debug builds, failures trigger
182 * 1 : buffer_size = Size of the space to allocate
184 * Returns : Pointer to newly malloc'd memory
186 *********************************************************************/
187 void *malloc_or_die(size_t buffer_size)
191 if (buffer_size == 0)
193 log_error(LOG_LEVEL_ERROR,
194 "malloc_or_die() called with buffer size 0");
195 assert(buffer_size != 0);
199 new_buf = malloc(buffer_size);
203 assert(new_buf != NULL);
204 log_error(LOG_LEVEL_FATAL, "Out of memory in malloc_or_die().");
214 /*********************************************************************
216 * Function : write_pid_file
218 * Description : Writes a pid file with the pid of the main process.
219 * Exits if the file can't be opened
222 * 1 : pid_file = Path of the pid file that gets created.
226 *********************************************************************/
227 void write_pid_file(const char *pid_file)
231 if ((fp = fopen(pid_file, "w")) == NULL)
233 log_error(LOG_LEVEL_FATAL, "can't open pid file '%s': %E", pid_file);
237 fprintf(fp, "%u\n", (unsigned int) getpid());
243 #endif /* def unix */
246 /*********************************************************************
248 * Function : hash_string
250 * Description : Take a string and compute a (hopefuly) unique numeric
251 * integer value. This is useful to "switch" a string.
254 * 1 : s : string to be hashed.
256 * Returns : The string's hash
258 *********************************************************************/
259 unsigned int hash_string(const char* s)
265 h = 5 * h + (unsigned int)*s;
273 /*********************************************************************
275 * Function : strcmpic
277 * Description : Case insensitive string comparison
280 * 1 : s1 = string 1 to compare
281 * 2 : s2 = string 2 to compare
283 * Returns : 0 if s1==s2, Negative if s1<s2, Positive if s1>s2
285 *********************************************************************/
286 int strcmpic(const char *s1, const char *s2)
293 if ((*s1 != *s2) && (privoxy_tolower(*s1) != privoxy_tolower(*s2)))
299 return(privoxy_tolower(*s1) - privoxy_tolower(*s2));
304 /*********************************************************************
306 * Function : strncmpic
308 * Description : Case insensitive string comparison (up to n characters)
311 * 1 : s1 = string 1 to compare
312 * 2 : s2 = string 2 to compare
313 * 3 : n = maximum characters to compare
315 * Returns : 0 if s1==s2, Negative if s1<s2, Positive if s1>s2
317 *********************************************************************/
318 int strncmpic(const char *s1, const char *s2, size_t n)
320 if (n <= (size_t)0) return(0);
326 if ((*s1 != *s2) && (privoxy_tolower(*s1) != privoxy_tolower(*s2)))
331 if (--n <= (size_t)0) break;
335 return(privoxy_tolower(*s1) - privoxy_tolower(*s2));
340 /*********************************************************************
344 * Description : In-situ-eliminate all leading and trailing whitespace
348 * 1 : s : string to be chomped.
350 * Returns : chomped string
352 *********************************************************************/
353 char *chomp(char *string)
358 * strip trailing whitespace
360 p = string + strlen(string);
361 while (p > string && privoxy_isspace(*(p-1)))
368 * find end of leading whitespace
371 while (*q && privoxy_isspace(*q))
377 * if there was any, move the rest forwards
392 /*********************************************************************
394 * Function : string_append
396 * Description : Reallocate target_string and append text to it.
397 * This makes it easier to append to malloc'd strings.
398 * This is similar to the (removed) strsav(), but
399 * running out of memory isn't catastrophic.
403 * The following style provides sufficient error
404 * checking for this routine, with minimal clutter
405 * in the source code. It is recommended if you
406 * have many calls to this function:
408 * char * s = strdup(...); // don't check for error
409 * string_append(&s, ...); // don't check for error
410 * string_append(&s, ...); // don't check for error
411 * string_append(&s, ...); // don't check for error
412 * if (NULL == s) { ... handle error ... }
416 * char * s = strdup(...); // don't check for error
417 * string_append(&s, ...); // don't check for error
418 * string_append(&s, ...); // don't check for error
419 * if (string_append(&s, ...)) {... handle error ...}
422 * 1 : target_string = Pointer to old text that is to be
423 * extended. *target_string will be free()d by this
424 * routine. target_string must be non-NULL.
425 * If *target_string is NULL, this routine will
426 * do nothing and return with an error - this allows
427 * you to make many calls to this routine and only
428 * check for errors after the last one.
429 * 2 : text_to_append = Text to be appended to old.
432 * Returns : JB_ERR_OK on success, and sets *target_string
433 * to newly malloc'ed appended string. Caller
434 * must free(*target_string).
435 * JB_ERR_MEMORY on out-of-memory. (And free()s
436 * *target_string and sets it to NULL).
437 * JB_ERR_MEMORY if *target_string is NULL.
439 *********************************************************************/
440 jb_err string_append(char **target_string, const char *text_to_append)
446 assert(target_string);
447 assert(text_to_append);
449 if (*target_string == NULL)
451 return JB_ERR_MEMORY;
454 if (*text_to_append == '\0')
459 old_len = strlen(*target_string);
461 new_size = strlen(text_to_append) + old_len + 1;
463 if (NULL == (new_string = realloc(*target_string, new_size)))
465 free(*target_string);
467 *target_string = NULL;
468 return JB_ERR_MEMORY;
471 strlcpy(new_string + old_len, text_to_append, new_size - old_len);
473 *target_string = new_string;
478 /*********************************************************************
480 * Function : string_join
482 * Description : Join two strings together. Frees BOTH the original
483 * strings. If either or both input strings are NULL,
484 * fails as if it had run out of memory.
486 * For comparison, string_append requires that the
487 * second string is non-NULL, and doesn't free it.
489 * Rationale: Too often, we want to do
490 * string_append(s, html_encode(s2)). That assert()s
491 * if s2 is NULL or if html_encode() runs out of memory.
492 * It also leaks memory. Proper checking is cumbersome.
493 * The solution: string_join(s, html_encode(s2)) is safe,
494 * and will free the memory allocated by html_encode().
497 * 1 : target_string = Pointer to old text that is to be
498 * extended. *target_string will be free()d by this
499 * routine. target_string must be non-NULL.
500 * 2 : text_to_append = Text to be appended to old.
502 * Returns : JB_ERR_OK on success, and sets *target_string
503 * to newly malloc'ed appended string. Caller
504 * must free(*target_string).
505 * JB_ERR_MEMORY on out-of-memory, or if
506 * *target_string or text_to_append is NULL. (In
507 * this case, frees *target_string and text_to_append,
508 * sets *target_string to NULL).
510 *********************************************************************/
511 jb_err string_join(char **target_string, char *text_to_append)
515 assert(target_string);
517 if (text_to_append == NULL)
519 freez(*target_string);
520 return JB_ERR_MEMORY;
523 err = string_append(target_string, text_to_append);
525 freez(text_to_append);
531 /*********************************************************************
533 * Function : string_toupper
535 * Description : Produce a copy of string with all convertible
536 * characters converted to uppercase.
539 * 1 : string = string to convert
541 * Returns : Uppercase copy of string if possible,
542 * NULL on out-of-memory or if string was NULL.
544 *********************************************************************/
545 char *string_toupper(const char *string)
550 if (!string || ((result = (char *) zalloc(strlen(string) + 1)) == NULL))
560 *p++ = (char)toupper((int) *q++);
568 /*********************************************************************
570 * Function : string_move
572 * Description : memmove wrapper to move the last part of a string
573 * towards the beginning, overwriting the part in
574 * the middle. strlcpy() can't be used here as the
578 * 1 : dst = Destination to overwrite
579 * 2 : src = Source to move.
583 *********************************************************************/
584 void string_move(char *dst, char *src)
588 /* +1 to copy the terminating nul as well. */
589 memmove(dst, src, strlen(src)+1);
593 /*********************************************************************
597 * Description : Duplicate the first n characters of a string that may
598 * contain '\0' characters.
601 * 1 : string = string to be duplicated
602 * 2 : len = number of bytes to duplicate
604 * Returns : pointer to copy, or NULL if failiure
606 *********************************************************************/
607 char *bindup(const char *string, size_t len)
611 duplicate = (char *)malloc(len);
612 if (NULL != duplicate)
614 memcpy(duplicate, string, len);
622 /*********************************************************************
624 * Function : make_path
626 * Description : Takes a directory name and a file name, returns
627 * the complete path. Handles windows/unix differences.
628 * If the file name is already an absolute path, or if
629 * the directory name is NULL or empty, it returns
633 * 1 : dir: Name of directory or NULL for none.
634 * 2 : file: Name of file. Should not be NULL or empty.
636 * Returns : "dir/file" (Or on windows, "dir\file").
637 * It allocates the string on the heap. Caller frees.
638 * Returns NULL in error (i.e. NULL file or out of
641 *********************************************************************/
642 char * make_path(const char * dir, const char * file)
644 if ((file == NULL) || (*file == '\0'))
646 return NULL; /* Error */
649 if ((dir == NULL) || (*dir == '\0') /* No directory specified */
651 || (*file == '\\') || (file[1] == ':') /* Absolute path (DOS) */
652 #else /* ifndef _WIN32 */
653 || (*file == '/') /* Absolute path (U*ix) */
654 #endif /* ifndef _WIN32 */
662 size_t path_size = strlen(dir) + strlen(file) + 2; /* +2 for trailing (back)slash and \0 */
665 if (*dir != '/' && basedir && *basedir)
668 * Relative path, so start with the base directory.
670 path_size += strlen(basedir) + 1; /* +1 for the slash */
671 path = malloc(path_size);
672 if (!path) log_error(LOG_LEVEL_FATAL, "malloc failed!");
673 strlcpy(path, basedir, path_size);
674 strlcat(path, "/", path_size);
675 strlcat(path, dir, path_size);
678 #endif /* defined unix */
680 path = malloc(path_size);
681 if (!path) log_error(LOG_LEVEL_FATAL, "malloc failed!");
682 strlcpy(path, dir, path_size);
685 assert(NULL != path);
687 if (path[strlen(path)-1] != '\\')
689 strlcat(path, "\\", path_size);
691 #else /* ifndef _WIN32 */
692 if (path[strlen(path)-1] != '/')
694 strlcat(path, "/", path_size);
696 #endif /* ifndef _WIN32 */
697 strlcat(path, file, path_size);
704 /*********************************************************************
706 * Function : pick_from_range
708 * Description : Pick a positive number out of a given range.
709 * Should only be used if randomness would be nice,
710 * but isn't really necessary.
713 * 1 : range: Highest possible number to pick.
715 * Returns : Picked number.
717 *********************************************************************/
718 long int pick_from_range(long int range)
722 static unsigned long seed = 0;
723 #endif /* def _WIN32 */
728 if (range <= 0) return 0;
730 #ifdef HAVE_ARC4RANDOM
731 number = arc4random() % range + 1;
732 #elif defined(HAVE_RANDOM)
733 number = random() % range + 1;
734 #elif defined(MUTEX_LOCKS_AVAILABLE)
735 privoxy_mutex_lock(&rand_mutex);
739 seed = (unsigned long)(GetCurrentThreadId()+GetTickCount());
742 seed = (unsigned long)((rand() << 16) + rand());
743 #endif /* def _WIN32 */
744 number = (unsigned long)((rand() << 16) + (rand())) % (unsigned long)(range + 1);
745 privoxy_mutex_unlock(&rand_mutex);
748 * XXX: Which platforms reach this and are there
749 * better options than just using rand() and hoping
752 log_error(LOG_LEVEL_INFO, "No thread-safe PRNG available? Header time randomization "
753 "might cause crashes, predictable results or even combine these fine options.");
754 number = rand() % (long int)(range + 1);
756 #endif /* (def HAVE_ARC4RANDOM) */
762 #ifdef USE_PRIVOXY_STRLCPY
763 /*********************************************************************
765 * Function : privoxy_strlcpy
767 * Description : strlcpy(3) look-alike for those without decent libc.
770 * 1 : destination: buffer to copy into.
771 * 2 : source: String to copy.
772 * 3 : size: Size of destination buffer.
774 * Returns : The length of the string that privoxy_strlcpy() tried to create.
776 *********************************************************************/
777 size_t privoxy_strlcpy(char *destination, const char *source, const size_t size)
781 snprintf(destination, size, "%s", source);
783 * Platforms that lack strlcpy() also tend to have
784 * a broken snprintf implementation that doesn't
785 * guarantee nul termination.
787 * XXX: the configure script should detect and reject those.
789 destination[size-1] = '\0';
791 return strlen(source);
793 #endif /* def USE_PRIVOXY_STRLCPY */
797 /*********************************************************************
799 * Function : privoxy_strlcat
801 * Description : strlcat(3) look-alike for those without decent libc.
804 * 1 : destination: C string.
805 * 2 : source: String to copy.
806 * 3 : size: Size of destination buffer.
808 * Returns : The length of the string that privoxy_strlcat() tried to create.
810 *********************************************************************/
811 size_t privoxy_strlcat(char *destination, const char *source, const size_t size)
813 const size_t old_length = strlen(destination);
814 return old_length + strlcpy(destination + old_length, source, size - old_length);
816 #endif /* ndef HAVE_STRLCAT */
819 /*********************************************************************
821 * Function : privoxy_millisleep
823 * Description : Sleep a number of milliseconds
826 * 1 : delay: Number of milliseconds to sleep
828 * Returns : -1 on error, 0 otherwise
830 *********************************************************************/
831 int privoxy_millisleep(unsigned milliseconds)
833 #ifdef HAVE_NANOSLEEP
834 struct timespec rqtp = {0};
835 struct timespec rmtp = {0};
837 rqtp.tv_sec = milliseconds / 1000;
838 rqtp.tv_nsec = (milliseconds % 1000) * 1000 * 1000;
840 return nanosleep(&rqtp, &rmtp);
841 #elif defined (_WIN32)
846 #warning Missing privoxy_milisleep() implementation. delay-response{} will not work.
849 #endif /* def HAVE_NANOSLEEP */
854 /*********************************************************************
856 * Function : privoxy_gmtime_r
858 * Description : Behave like gmtime_r() and convert a
859 * time_t to a struct tm.
862 * 1 : time_spec: The time to convert
863 * 2 : result: The struct tm to use as storage
865 * Returns : Pointer to the result or NULL on error.
867 *********************************************************************/
868 struct tm *privoxy_gmtime_r(const time_t *time_spec, struct tm *result)
873 timeptr = gmtime_r(time_spec, result);
874 #elif defined(MUTEX_LOCKS_AVAILABLE)
875 privoxy_mutex_lock(&gmtime_mutex);
876 timeptr = gmtime(time_spec);
878 #warning Using unlocked gmtime()
879 timeptr = gmtime(time_spec);
884 #if !defined(HAVE_GMTIME_R) && defined(MUTEX_LOCKS_AVAILABLE)
885 privoxy_mutex_unlock(&gmtime_mutex);
890 #if !defined(HAVE_GMTIME_R)
893 #ifdef MUTEX_LOCKS_AVAILABLE
894 privoxy_mutex_unlock(&gmtime_mutex);
901 #if !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV)
902 /*********************************************************************
906 * Description : libc replacement function for the inverse of gmtime().
907 * Copyright (C) 2004 Free Software Foundation, Inc.
909 * Code originally copied from GnuPG, modifications done
910 * for Privoxy: style changed, #ifdefs for _WIN32 added
911 * to have it work on mingw32.
913 * XXX: It's very unlikely to happen, but if the malloc()
914 * call fails the time zone will be permanently set to UTC.
917 * 1 : tm: Broken-down time struct.
919 * Returns : tm converted into time_t seconds.
921 *********************************************************************/
922 time_t timegm(struct tm *tm)
935 old_zone = malloc(3 + strlen(zone) + 1);
938 strcpy(old_zone, "TZ=");
939 strcat(old_zone, zone);
942 /* http://man7.org/linux/man-pages/man3/putenv.3.html
943 * int putenv(char *string);
944 * The string pointed to by string becomes part of the environment, so altering the
945 * string changes the environment.
946 * In other words, the memory pointed to by *string is used until
947 * a) another call to putenv() with the same e-var name
948 * b) the program exits
950 * Windows e-vars don't work that way, so let's not leak memory.
953 #endif /* def _WIN32 */
960 #elif defined(_WIN32)
970 #endif /* !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV) */
973 #ifndef HAVE_SNPRINTF
975 * What follows is a portable snprintf routine, written by Mark Martinec.
976 * See: http://www.ijs.si/software/snprintf/
979 - a portable implementation of snprintf,
980 including vsnprintf.c, asnprintf, vasnprintf, asprintf, vasprintf
982 snprintf is a routine to convert numeric and string arguments to
983 formatted strings. It is similar to sprintf(3) provided in a system's
984 C library, yet it requires an additional argument - the buffer size -
985 and it guarantees never to store anything beyond the given buffer,
986 regardless of the format or arguments to be formatted. Some newer
987 operating systems do provide snprintf in their C library, but many do
988 not or do provide an inadequate (slow or idiosyncratic) version, which
989 calls for a portable implementation of this routine.
993 Mark Martinec <mark.martinec@ijs.si>, April 1999, June 2000
994 Copyright © 1999, Mark Martinec
998 #define PORTABLE_SNPRINTF_VERSION_MAJOR 2
999 #define PORTABLE_SNPRINTF_VERSION_MINOR 2
1001 #if defined(NEED_ASPRINTF) || defined(NEED_ASNPRINTF) || defined(NEED_VASPRINTF) || defined(NEED_VASNPRINTF)
1002 # if defined(NEED_SNPRINTF_ONLY)
1003 # undef NEED_SNPRINTF_ONLY
1005 # if !defined(PREFER_PORTABLE_SNPRINTF)
1006 # define PREFER_PORTABLE_SNPRINTF
1010 #if defined(SOLARIS_BUG_COMPATIBLE) && !defined(SOLARIS_COMPATIBLE)
1011 #define SOLARIS_COMPATIBLE
1014 #if defined(HPUX_BUG_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
1015 #define HPUX_COMPATIBLE
1018 #if defined(DIGITAL_UNIX_BUG_COMPATIBLE) && !defined(DIGITAL_UNIX_COMPATIBLE)
1019 #define DIGITAL_UNIX_COMPATIBLE
1022 #if defined(PERL_BUG_COMPATIBLE) && !defined(PERL_COMPATIBLE)
1023 #define PERL_COMPATIBLE
1026 #if defined(LINUX_BUG_COMPATIBLE) && !defined(LINUX_COMPATIBLE)
1027 #define LINUX_COMPATIBLE
1030 #include <sys/types.h>
1041 #define isdigit(c) ((c) >= '0' && (c) <= '9')
1043 /* For copying strings longer or equal to 'breakeven_point'
1044 * it is more efficient to call memcpy() than to do it inline.
1045 * The value depends mostly on the processor architecture,
1046 * but also on the compiler and its optimization capabilities.
1047 * The value is not critical, some small value greater than zero
1048 * will be just fine if you don't care to squeeze every drop
1049 * of performance out of the code.
1051 * Small values favor memcpy, large values favor inline code.
1053 #if defined(__alpha__) || defined(__alpha)
1054 # define breakeven_point 2 /* AXP (DEC Alpha) - gcc or cc or egcs */
1056 #if defined(__i386__) || defined(__i386)
1057 # define breakeven_point 12 /* Intel Pentium/Linux - gcc 2.96 */
1060 # define breakeven_point 10 /* HP-PA - gcc */
1062 #if defined(__sparc__) || defined(__sparc)
1063 # define breakeven_point 33 /* Sun Sparc 5 - gcc 2.8.1 */
1066 /* some other values of possible interest: */
1067 /* #define breakeven_point 8 */ /* VAX 4000 - vaxc */
1068 /* #define breakeven_point 19 */ /* VAX 4000 - gcc 2.7.0 */
1070 #ifndef breakeven_point
1071 # define breakeven_point 6 /* some reasonable one-size-fits-all value */
1074 #define fast_memcpy(d,s,n) \
1075 { register size_t nn = (size_t)(n); \
1076 if (nn >= breakeven_point) memcpy((d), (s), nn); \
1077 else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
1078 register char *dd; register const char *ss; \
1079 for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } }
1081 #define fast_memset(d,c,n) \
1082 { register size_t nn = (size_t)(n); \
1083 if (nn >= breakeven_point) memset((d), (int)(c), nn); \
1084 else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
1085 register char *dd; register const int cc=(int)(c); \
1086 for (dd=(d); nn>0; nn--) *dd++ = cc; } }
1090 #if defined(NEED_ASPRINTF)
1091 int asprintf (char **ptr, const char *fmt, /*args*/ ...);
1093 #if defined(NEED_VASPRINTF)
1094 int vasprintf (char **ptr, const char *fmt, va_list ap);
1096 #if defined(NEED_ASNPRINTF)
1097 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...);
1099 #if defined(NEED_VASNPRINTF)
1100 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap);
1103 #if defined(HAVE_SNPRINTF)
1104 /* declare our portable snprintf routine under name portable_snprintf */
1105 /* declare our portable vsnprintf routine under name portable_vsnprintf */
1107 /* declare our portable routines under names snprintf and vsnprintf */
1108 #define portable_snprintf snprintf
1109 #if !defined(NEED_SNPRINTF_ONLY)
1110 #define portable_vsnprintf vsnprintf
1114 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1115 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...);
1116 #if !defined(NEED_SNPRINTF_ONLY)
1117 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap);
1123 static char credits[] = "\n\
1124 @(#)snprintf.c, v2.2: Mark Martinec, <mark.martinec@ijs.si>\n\
1125 @(#)snprintf.c, v2.2: Copyright 1999, Mark Martinec. Frontier Artistic License applies.\n\
1126 @(#)snprintf.c, v2.2: http://www.ijs.si/software/snprintf/\n";
1128 #if defined(NEED_ASPRINTF)
1129 int asprintf(char **ptr, const char *fmt, /*args*/ ...) {
1135 va_start(ap, fmt); /* measure the required size */
1136 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
1138 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1139 *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
1140 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1144 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1146 assert(str_l2 == str_l);
1152 #if defined(NEED_VASPRINTF)
1153 int vasprintf(char **ptr, const char *fmt, va_list ap) {
1159 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
1160 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1163 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1164 *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
1165 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1167 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1168 assert(str_l2 == str_l);
1174 #if defined(NEED_ASNPRINTF)
1175 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...) {
1180 va_start(ap, fmt); /* measure the required size */
1181 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
1183 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1184 if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1; /* truncate */
1185 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1186 if (str_m == 0) { /* not interested in resulting string, just return size */
1188 *ptr = (char *) malloc(str_m);
1189 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1193 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1195 assert(str_l2 == str_l);
1202 #if defined(NEED_VASNPRINTF)
1203 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap) {
1208 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
1209 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1212 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1213 if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1; /* truncate */
1214 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1215 if (str_m == 0) { /* not interested in resulting string, just return size */
1217 *ptr = (char *) malloc(str_m);
1218 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1220 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1221 assert(str_l2 == str_l);
1229 * If the system does have snprintf and the portable routine is not
1230 * specifically required, this module produces no code for snprintf/vsnprintf.
1232 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1234 #if !defined(NEED_SNPRINTF_ONLY)
1235 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1240 str_l = portable_vsnprintf(str, str_m, fmt, ap);
1246 #if defined(NEED_SNPRINTF_ONLY)
1247 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1249 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) {
1252 #if defined(NEED_SNPRINTF_ONLY)
1256 const char *p = fmt;
1258 /* In contrast with POSIX, the ISO C99 now says
1259 * that str can be NULL and str_m can be 0.
1260 * This is more useful than the old: if (str_m < 1) return -1; */
1262 #if defined(NEED_SNPRINTF_ONLY)
1268 /* if (str_l < str_m) str[str_l++] = *p++; -- this would be sufficient */
1269 /* but the following code achieves better performance for cases
1270 * where format string is long and contains few conversions */
1271 const char *q = strchr(p+1,'%');
1272 size_t n = !q ? strlen(p) : (q-p);
1273 if (str_l < str_m) {
1274 size_t avail = str_m-str_l;
1275 fast_memcpy(str+str_l, p, (n>avail?avail:n));
1279 const char *starting_p;
1280 size_t min_field_width = 0, precision = 0;
1281 int zero_padding = 0, precision_specified = 0, justify_left = 0;
1282 int alternate_form = 0, force_sign = 0;
1283 int space_for_positive = 1; /* If both the ' ' and '+' flags appear,
1284 the ' ' flag should be ignored. */
1285 char length_modifier = '\0'; /* allowed values: \0, h, l, L */
1286 char tmp[32];/* temporary buffer for simple numeric->string conversion */
1288 const char *str_arg; /* string address in case of string argument */
1289 size_t str_arg_l; /* natural field width of arg without padding
1291 unsigned char uchar_arg;
1292 /* unsigned char argument value - only defined for c conversion.
1293 N.B. standard explicitly states the char argument for
1294 the c conversion is unsigned */
1296 size_t number_of_zeros_to_pad = 0;
1297 /* number of zeros to be inserted for numeric conversions
1298 as required by the precision or minimal field width */
1300 size_t zero_padding_insertion_ind = 0;
1301 /* index into tmp where zero padding is to be inserted */
1303 char fmt_spec = '\0';
1304 /* current conversion specifier character */
1306 str_arg = credits;/* just to make compiler happy (defined but not used)*/
1308 starting_p = p; p++; /* skip '%' */
1310 while (*p == '0' || *p == '-' || *p == '+' ||
1311 *p == ' ' || *p == '#' || *p == '\'') {
1313 case '0': zero_padding = 1; break;
1314 case '-': justify_left = 1; break;
1315 case '+': force_sign = 1; space_for_positive = 0; break;
1316 case ' ': force_sign = 1;
1317 /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */
1318 #ifdef PERL_COMPATIBLE
1319 /* ... but in Perl the last of ' ' and '+' applies */
1320 space_for_positive = 1;
1323 case '#': alternate_form = 1; break;
1328 /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
1330 /* parse field width */
1333 p++; j = va_arg(ap, int);
1334 if (j >= 0) min_field_width = j;
1335 else { min_field_width = -j; justify_left = 1; }
1336 } else if (isdigit((int)(*p))) {
1337 /* size_t could be wider than unsigned int;
1338 make sure we treat argument like common implementations do */
1339 unsigned int uj = *p++ - '0';
1340 while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1341 min_field_width = uj;
1343 /* parse precision */
1345 p++; precision_specified = 1;
1347 int j = va_arg(ap, int);
1349 if (j >= 0) precision = j;
1351 precision_specified = 0; precision = 0;
1353 * Solaris 2.6 man page claims that in this case the precision
1354 * should be set to 0. Digital Unix 4.0, HPUX 10 and BSD man page
1355 * claim that this case should be treated as unspecified precision,
1356 * which is what we do here.
1359 } else if (isdigit((int)(*p))) {
1360 /* size_t could be wider than unsigned int;
1361 make sure we treat argument like common implementations do */
1362 unsigned int uj = *p++ - '0';
1363 while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1367 /* parse 'h', 'l' and 'll' length modifiers */
1368 if (*p == 'h' || *p == 'l') {
1369 length_modifier = *p; p++;
1370 if (length_modifier == 'l' && *p == 'l') { /* double l = long long */
1371 #ifdef SNPRINTF_LONGLONG_SUPPORT
1372 length_modifier = '2'; /* double l encoded as '2' */
1374 length_modifier = 'l'; /* treat it as a single 'l' */
1380 /* common synonyms: */
1382 case 'i': fmt_spec = 'd'; break;
1383 case 'D': fmt_spec = 'd'; length_modifier = 'l'; break;
1384 case 'U': fmt_spec = 'u'; length_modifier = 'l'; break;
1385 case 'O': fmt_spec = 'o'; length_modifier = 'l'; break;
1388 /* get parameter value, do initial processing */
1390 case '%': /* % behaves similar to 's' regarding flags and field widths */
1391 case 'c': /* c behaves similar to 's' regarding flags and field widths */
1393 length_modifier = '\0'; /* wint_t and wchar_t not supported */
1394 /* the result of zero padding flag with non-numeric conversion specifier*/
1395 /* is undefined. Solaris and HPUX 10 does zero padding in this case, */
1396 /* Digital Unix and Linux does not. */
1397 #if !defined(SOLARIS_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
1398 zero_padding = 0; /* turn zero padding off for string conversions */
1405 int j = va_arg(ap, int);
1406 uchar_arg = (unsigned char) j; /* standard demands unsigned char */
1407 str_arg = (const char *) &uchar_arg;
1411 str_arg = va_arg(ap, const char *);
1412 if (!str_arg) str_arg_l = 0;
1413 /* make sure not to address string beyond the specified precision !!! */
1414 else if (!precision_specified) str_arg_l = strlen(str_arg);
1415 /* truncate string if necessary as requested by precision */
1416 else if (precision == 0) str_arg_l = 0;
1418 /* memchr on HP does not like n > 2^31 !!! */
1419 const char *q = memchr(str_arg, '\0',
1420 precision <= 0x7fffffff ? precision : 0x7fffffff);
1421 str_arg_l = !q ? precision : (q-str_arg);
1427 case 'd': case 'u': case 'o': case 'x': case 'X': case 'p': {
1428 /* NOTE: the u, o, x, X and p conversion specifiers imply
1429 the value is unsigned; d implies a signed value */
1432 /* 0 if numeric argument is zero (or if pointer is NULL for 'p'),
1433 +1 if greater than zero (or nonzero for unsigned arguments),
1434 -1 if negative (unsigned argument is never negative) */
1436 int int_arg = 0; unsigned int uint_arg = 0;
1437 /* only defined for length modifier h, or for no length modifiers */
1439 long int long_arg = 0; unsigned long int ulong_arg = 0;
1440 /* only defined for length modifier l */
1442 void *ptr_arg = NULL;
1443 /* pointer argument value -only defined for p conversion */
1445 #ifdef SNPRINTF_LONGLONG_SUPPORT
1446 long long int long_long_arg = 0;
1447 unsigned long long int ulong_long_arg = 0;
1448 /* only defined for length modifier ll */
1450 if (fmt_spec == 'p') {
1451 /* HPUX 10: An l, h, ll or L before any other conversion character
1452 * (other than d, i, u, o, x, or X) is ignored.
1454 * not specified, but seems to behave as HPUX does.
1455 * Solaris: If an h, l, or L appears before any other conversion
1456 * specifier (other than d, i, u, o, x, or X), the behavior
1457 * is undefined. (Actually %hp converts only 16-bits of address
1458 * and %llp treats address as 64-bit data which is incompatible
1459 * with (void *) argument on a 32-bit system).
1461 #ifdef SOLARIS_COMPATIBLE
1462 # ifdef SOLARIS_BUG_COMPATIBLE
1463 /* keep length modifiers even if it represents 'll' */
1465 if (length_modifier == '2') length_modifier = '\0';
1468 length_modifier = '\0';
1470 ptr_arg = va_arg(ap, void *);
1471 if (ptr_arg != NULL) arg_sign = 1;
1472 } else if (fmt_spec == 'd') { /* signed */
1473 switch (length_modifier) {
1476 /* It is non-portable to specify a second argument of char or short
1477 * to va_arg, because arguments seen by the called function
1478 * are not char or short. C converts char and short arguments
1479 * to int before passing them to a function.
1481 int_arg = va_arg(ap, int);
1482 if (int_arg > 0) arg_sign = 1;
1483 else if (int_arg < 0) arg_sign = -1;
1486 long_arg = va_arg(ap, long int);
1487 if (long_arg > 0) arg_sign = 1;
1488 else if (long_arg < 0) arg_sign = -1;
1490 #ifdef SNPRINTF_LONGLONG_SUPPORT
1492 long_long_arg = va_arg(ap, long long int);
1493 if (long_long_arg > 0) arg_sign = 1;
1494 else if (long_long_arg < 0) arg_sign = -1;
1498 } else { /* unsigned */
1499 switch (length_modifier) {
1502 uint_arg = va_arg(ap, unsigned int);
1503 if (uint_arg) arg_sign = 1;
1506 ulong_arg = va_arg(ap, unsigned long int);
1507 if (ulong_arg) arg_sign = 1;
1509 #ifdef SNPRINTF_LONGLONG_SUPPORT
1511 ulong_long_arg = va_arg(ap, unsigned long long int);
1512 if (ulong_long_arg) arg_sign = 1;
1517 str_arg = tmp; str_arg_l = 0;
1519 * For d, i, u, o, x, and X conversions, if precision is specified,
1520 * the '0' flag should be ignored. This is so with Solaris 2.6,
1521 * Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl.
1523 #ifndef PERL_COMPATIBLE
1524 if (precision_specified) zero_padding = 0;
1526 if (fmt_spec == 'd') {
1527 if (force_sign && arg_sign >= 0)
1528 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1529 /* leave negative numbers for sprintf to handle,
1530 to avoid handling tricky cases like (short int)(-32768) */
1531 #ifdef LINUX_COMPATIBLE
1532 } else if (fmt_spec == 'p' && force_sign && arg_sign > 0) {
1533 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1535 } else if (alternate_form) {
1536 if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X') )
1537 { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = fmt_spec; }
1538 /* alternate form should have no effect for p conversion, but ... */
1539 #ifdef HPUX_COMPATIBLE
1540 else if (fmt_spec == 'p'
1541 /* HPUX 10: for an alternate form of p conversion,
1542 * a nonzero result is prefixed by 0x. */
1543 #ifndef HPUX_BUG_COMPATIBLE
1544 /* Actually it uses 0x prefix even for a zero value. */
1547 ) { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = 'x'; }
1550 zero_padding_insertion_ind = str_arg_l;
1551 if (!precision_specified) precision = 1; /* default precision is 1 */
1552 if (precision == 0 && arg_sign == 0
1553 #if defined(HPUX_BUG_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1555 /* HPUX 10 man page claims: With conversion character p the result of
1556 * converting a zero value with a precision of zero is a null string.
1557 * Actually HP returns all zeroes, and Linux returns "(nil)". */
1560 /* converted to null string */
1561 /* When zero value is formatted with an explicit precision 0,
1562 the resulting formatted string is empty (d, i, u, o, x, X, p). */
1564 char f[5]; int f_l = 0;
1565 f[f_l++] = '%'; /* construct a simple format string for sprintf */
1566 if (!length_modifier) { }
1567 else if (length_modifier=='2') { f[f_l++] = 'l'; f[f_l++] = 'l'; }
1568 else f[f_l++] = length_modifier;
1569 f[f_l++] = fmt_spec; f[f_l++] = '\0';
1570 if (fmt_spec == 'p') str_arg_l += sprintf(tmp+str_arg_l, f, ptr_arg);
1571 else if (fmt_spec == 'd') { /* signed */
1572 switch (length_modifier) {
1574 case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, int_arg); break;
1575 case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, long_arg); break;
1576 #ifdef SNPRINTF_LONGLONG_SUPPORT
1577 case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,long_long_arg); break;
1580 } else { /* unsigned */
1581 switch (length_modifier) {
1583 case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, uint_arg); break;
1584 case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, ulong_arg); break;
1585 #ifdef SNPRINTF_LONGLONG_SUPPORT
1586 case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,ulong_long_arg);break;
1590 /* include the optional minus sign and possible "0x"
1591 in the region before the zero padding insertion point */
1592 if (zero_padding_insertion_ind < str_arg_l &&
1593 tmp[zero_padding_insertion_ind] == '-') {
1594 zero_padding_insertion_ind++;
1596 if (zero_padding_insertion_ind+1 < str_arg_l &&
1597 tmp[zero_padding_insertion_ind] == '0' &&
1598 (tmp[zero_padding_insertion_ind+1] == 'x' ||
1599 tmp[zero_padding_insertion_ind+1] == 'X') ) {
1600 zero_padding_insertion_ind += 2;
1603 { size_t num_of_digits = str_arg_l - zero_padding_insertion_ind;
1604 if (alternate_form && fmt_spec == 'o'
1605 #ifdef HPUX_COMPATIBLE /* ("%#.o",0) -> "" */
1608 #ifdef DIGITAL_UNIX_BUG_COMPATIBLE /* ("%#o",0) -> "00" */
1610 /* unless zero is already the first character */
1611 && !(zero_padding_insertion_ind < str_arg_l
1612 && tmp[zero_padding_insertion_ind] == '0')
1614 ) { /* assure leading zero for alternate-form octal numbers */
1615 if (!precision_specified || precision < num_of_digits+1) {
1616 /* precision is increased to force the first character to be zero,
1617 except if a zero value is formatted with an explicit precision
1619 precision = num_of_digits+1; precision_specified = 1;
1622 /* zero padding to specified precision? */
1623 if (num_of_digits < precision)
1624 number_of_zeros_to_pad = precision - num_of_digits;
1626 /* zero padding to specified minimal field width? */
1627 if (!justify_left && zero_padding) {
1628 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1629 if (n > 0) number_of_zeros_to_pad += n;
1633 default: /* unrecognized conversion specifier, keep format string as-is*/
1634 zero_padding = 0; /* turn zero padding off for non-numeric convers. */
1635 #ifndef DIGITAL_UNIX_COMPATIBLE
1636 justify_left = 1; min_field_width = 0; /* reset flags */
1638 #if defined(PERL_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1639 /* keep the entire format string unchanged */
1640 str_arg = starting_p; str_arg_l = p - starting_p;
1641 /* well, not exactly so for Linux, which does something between,
1642 * and I don't feel an urge to imitate it: "%+++++hy" -> "%+y" */
1644 /* discard the unrecognized conversion, just keep *
1645 * the unrecognized conversion character */
1646 str_arg = p; str_arg_l = 0;
1648 if (*p) str_arg_l++; /* include invalid conversion specifier unchanged
1649 if not at end-of-string */
1652 if (*p) p++; /* step over the just processed conversion specifier */
1653 /* insert padding to the left as requested by min_field_width;
1654 this does not include the zero padding in case of numerical conversions*/
1655 if (!justify_left) { /* left padding with blank or zero */
1656 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1658 if (str_l < str_m) {
1659 size_t avail = str_m-str_l;
1660 fast_memset(str+str_l, (zero_padding?'0':' '), (n>avail?avail:n));
1665 /* zero padding as requested by the precision or by the minimal field width
1666 * for numeric conversions required? */
1667 if (number_of_zeros_to_pad <= 0) {
1668 /* will not copy first part of numeric right now, *
1669 * force it to be copied later in its entirety */
1670 zero_padding_insertion_ind = 0;
1672 /* insert first part of numerics (sign or '0x') before zero padding */
1673 int n = zero_padding_insertion_ind;
1675 if (str_l < str_m) {
1676 size_t avail = str_m-str_l;
1677 fast_memcpy(str+str_l, str_arg, (n>avail?avail:n));
1681 /* insert zero padding as requested by the precision or min field width */
1682 n = number_of_zeros_to_pad;
1684 if (str_l < str_m) {
1685 size_t avail = str_m-str_l;
1686 fast_memset(str+str_l, '0', (n>avail?avail:n));
1691 /* insert formatted string
1692 * (or as-is conversion specifier for unknown conversions) */
1693 { int n = str_arg_l - zero_padding_insertion_ind;
1695 if (str_l < str_m) {
1696 size_t avail = str_m-str_l;
1697 fast_memcpy(str+str_l, str_arg+zero_padding_insertion_ind,
1703 /* insert right padding */
1704 if (justify_left) { /* right blank padding to the field width */
1705 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1707 if (str_l < str_m) {
1708 size_t avail = str_m-str_l;
1709 fast_memset(str+str_l, ' ', (n>avail?avail:n));
1716 #if defined(NEED_SNPRINTF_ONLY)
1719 if (str_m > 0) { /* make sure the string is null-terminated
1720 even at the expense of overwriting the last character
1721 (shouldn't happen, but just in case) */
1722 str[str_l <= str_m-1 ? str_l : str_m-1] = '\0';
1724 /* Return the number of characters formatted (excluding trailing null
1725 * character), that is, the number of characters that would have been
1726 * written to the buffer if it were large enough.
1728 * The value of str_l should be returned, but str_l is of unsigned type
1729 * size_t, and snprintf is int, possibly leading to an undetected
1730 * integer overflow, resulting in a negative return value, which is illegal.
1731 * Both XSH5 and ISO C99 (at least the draft) are silent on this issue.
1732 * Should errno be set to EOVERFLOW and EOF returned in this case???
1737 #endif /* ndef HAVE_SNPRINTF */