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-2018 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>
51 #if !defined(_WIN32) && !defined(__OS2__)
53 #endif /* #if !defined(_WIN32) && !defined(__OS2__) */
58 #if !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV)
60 #endif /* !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV) */
66 /*********************************************************************
70 * Description : Returns allocated memory that is initialized
74 * 1 : size = Size of memory chunk to return.
76 * Returns : Pointer to newly alloc'd memory chunk.
78 *********************************************************************/
79 void *zalloc(size_t size)
84 ret = calloc(1, size);
86 #warning calloc appears to be unavailable. Your platform will become unsupported in the future
87 if ((ret = (void *)malloc(size)) != NULL)
98 /*********************************************************************
100 * Function : zalloc_or_die
102 * Description : zalloc wrapper that either succeeds or causes
103 * program termination.
105 * Useful in situations were the string length is
106 * "small" and zalloc() failures couldn't be handled
107 * better anyway. In case of debug builds, failures
108 * trigger an assert().
111 * 1 : size = Size of memory chunk to return.
113 * Returns : Pointer to newly malloc'd memory chunk.
115 *********************************************************************/
116 void *zalloc_or_die(size_t size)
120 buffer = zalloc(size);
123 assert(buffer != NULL);
124 log_error(LOG_LEVEL_FATAL, "Out of memory in zalloc_or_die().");
132 /*********************************************************************
134 * Function : strdup_or_die
136 * Description : strdup wrapper that either succeeds or causes
137 * program termination.
139 * Useful in situations were the string length is
140 * "small" and strdup() failures couldn't be handled
141 * better anyway. In case of debug builds, failures
142 * trigger an assert().
145 * 1 : str = String to duplicate
147 * Returns : Pointer to newly strdup'd copy of the string.
149 *********************************************************************/
150 char *strdup_or_die(const char *str)
154 new_str = strdup(str);
158 assert(new_str != NULL);
159 log_error(LOG_LEVEL_FATAL, "Out of memory in strdup_or_die().");
168 /*********************************************************************
170 * Function : malloc_or_die
172 * Description : malloc wrapper that either succeeds or causes
173 * program termination.
175 * Useful in situations were the buffer size is "small"
176 * and malloc() failures couldn't be handled better
177 * anyway. In case of debug builds, failures trigger
181 * 1 : buffer_size = Size of the space to allocate
183 * Returns : Pointer to newly malloc'd memory
185 *********************************************************************/
186 void *malloc_or_die(size_t buffer_size)
190 if (buffer_size == 0)
192 log_error(LOG_LEVEL_ERROR,
193 "malloc_or_die() called with buffer size 0");
194 assert(buffer_size != 0);
198 new_buf = malloc(buffer_size);
202 assert(new_buf != NULL);
203 log_error(LOG_LEVEL_FATAL, "Out of memory in malloc_or_die().");
213 /*********************************************************************
215 * Function : write_pid_file
217 * Description : Writes a pid file with the pid of the main process.
218 * Exits if the file can't be opened
221 * 1 : pid_file = Path of the pid file that gets created.
225 *********************************************************************/
226 void write_pid_file(const char *pid_file)
230 if ((fp = fopen(pid_file, "w")) == NULL)
232 log_error(LOG_LEVEL_FATAL, "can't open pid file '%s': %E", pid_file);
236 fprintf(fp, "%u\n", (unsigned int) getpid());
242 #endif /* def unix */
245 /*********************************************************************
247 * Function : hash_string
249 * Description : Take a string and compute a (hopefuly) unique numeric
250 * integer value. This is useful to "switch" a string.
253 * 1 : s : string to be hashed.
255 * Returns : The string's hash
257 *********************************************************************/
258 unsigned int hash_string(const char* s)
264 h = 5 * h + (unsigned int)*s;
272 /*********************************************************************
274 * Function : strcmpic
276 * Description : Case insensitive string comparison
279 * 1 : s1 = string 1 to compare
280 * 2 : s2 = string 2 to compare
282 * Returns : 0 if s1==s2, Negative if s1<s2, Positive if s1>s2
284 *********************************************************************/
285 int strcmpic(const char *s1, const char *s2)
292 if ((*s1 != *s2) && (privoxy_tolower(*s1) != privoxy_tolower(*s2)))
298 return(privoxy_tolower(*s1) - privoxy_tolower(*s2));
303 /*********************************************************************
305 * Function : strncmpic
307 * Description : Case insensitive string comparison (up to n characters)
310 * 1 : s1 = string 1 to compare
311 * 2 : s2 = string 2 to compare
312 * 3 : n = maximum characters to compare
314 * Returns : 0 if s1==s2, Negative if s1<s2, Positive if s1>s2
316 *********************************************************************/
317 int strncmpic(const char *s1, const char *s2, size_t n)
319 if (n <= (size_t)0) return(0);
325 if ((*s1 != *s2) && (privoxy_tolower(*s1) != privoxy_tolower(*s2)))
330 if (--n <= (size_t)0) break;
334 return(privoxy_tolower(*s1) - privoxy_tolower(*s2));
339 /*********************************************************************
343 * Description : In-situ-eliminate all leading and trailing whitespace
347 * 1 : s : string to be chomped.
349 * Returns : chomped string
351 *********************************************************************/
352 char *chomp(char *string)
357 * strip trailing whitespace
359 p = string + strlen(string);
360 while (p > string && privoxy_isspace(*(p-1)))
367 * find end of leading whitespace
370 while (*q && privoxy_isspace(*q))
376 * if there was any, move the rest forwards
391 /*********************************************************************
393 * Function : string_append
395 * Description : Reallocate target_string and append text to it.
396 * This makes it easier to append to malloc'd strings.
397 * This is similar to the (removed) strsav(), but
398 * running out of memory isn't catastrophic.
402 * The following style provides sufficient error
403 * checking for this routine, with minimal clutter
404 * in the source code. It is recommended if you
405 * have many calls to this function:
407 * char * s = strdup(...); // don't check for error
408 * string_append(&s, ...); // don't check for error
409 * string_append(&s, ...); // don't check for error
410 * string_append(&s, ...); // don't check for error
411 * if (NULL == s) { ... handle error ... }
415 * char * s = strdup(...); // don't check for error
416 * string_append(&s, ...); // don't check for error
417 * string_append(&s, ...); // don't check for error
418 * if (string_append(&s, ...)) {... handle error ...}
421 * 1 : target_string = Pointer to old text that is to be
422 * extended. *target_string will be free()d by this
423 * routine. target_string must be non-NULL.
424 * If *target_string is NULL, this routine will
425 * do nothing and return with an error - this allows
426 * you to make many calls to this routine and only
427 * check for errors after the last one.
428 * 2 : text_to_append = Text to be appended to old.
431 * Returns : JB_ERR_OK on success, and sets *target_string
432 * to newly malloc'ed appended string. Caller
433 * must free(*target_string).
434 * JB_ERR_MEMORY on out-of-memory. (And free()s
435 * *target_string and sets it to NULL).
436 * JB_ERR_MEMORY if *target_string is NULL.
438 *********************************************************************/
439 jb_err string_append(char **target_string, const char *text_to_append)
445 assert(target_string);
446 assert(text_to_append);
448 if (*target_string == NULL)
450 return JB_ERR_MEMORY;
453 if (*text_to_append == '\0')
458 old_len = strlen(*target_string);
460 new_size = strlen(text_to_append) + old_len + 1;
462 if (NULL == (new_string = realloc(*target_string, new_size)))
464 free(*target_string);
466 *target_string = NULL;
467 return JB_ERR_MEMORY;
470 strlcpy(new_string + old_len, text_to_append, new_size - old_len);
472 *target_string = new_string;
477 /*********************************************************************
479 * Function : string_join
481 * Description : Join two strings together. Frees BOTH the original
482 * strings. If either or both input strings are NULL,
483 * fails as if it had run out of memory.
485 * For comparison, string_append requires that the
486 * second string is non-NULL, and doesn't free it.
488 * Rationale: Too often, we want to do
489 * string_append(s, html_encode(s2)). That assert()s
490 * if s2 is NULL or if html_encode() runs out of memory.
491 * It also leaks memory. Proper checking is cumbersome.
492 * The solution: string_join(s, html_encode(s2)) is safe,
493 * and will free the memory allocated by html_encode().
496 * 1 : target_string = Pointer to old text that is to be
497 * extended. *target_string will be free()d by this
498 * routine. target_string must be non-NULL.
499 * 2 : text_to_append = Text to be appended to old.
501 * Returns : JB_ERR_OK on success, and sets *target_string
502 * to newly malloc'ed appended string. Caller
503 * must free(*target_string).
504 * JB_ERR_MEMORY on out-of-memory, or if
505 * *target_string or text_to_append is NULL. (In
506 * this case, frees *target_string and text_to_append,
507 * sets *target_string to NULL).
509 *********************************************************************/
510 jb_err string_join(char **target_string, char *text_to_append)
514 assert(target_string);
516 if (text_to_append == NULL)
518 freez(*target_string);
519 return JB_ERR_MEMORY;
522 err = string_append(target_string, text_to_append);
524 freez(text_to_append);
530 /*********************************************************************
532 * Function : string_toupper
534 * Description : Produce a copy of string with all convertible
535 * characters converted to uppercase.
538 * 1 : string = string to convert
540 * Returns : Uppercase copy of string if possible,
541 * NULL on out-of-memory or if string was NULL.
543 *********************************************************************/
544 char *string_toupper(const char *string)
549 if (!string || ((result = (char *) zalloc(strlen(string) + 1)) == NULL))
559 *p++ = (char)toupper((int) *q++);
567 /*********************************************************************
569 * Function : string_move
571 * Description : memmove wrapper to move the last part of a string
572 * towards the beginning, overwriting the part in
573 * the middle. strlcpy() can't be used here as the
577 * 1 : dst = Destination to overwrite
578 * 2 : src = Source to move.
582 *********************************************************************/
583 void string_move(char *dst, char *src)
587 /* +1 to copy the terminating nul as well. */
588 memmove(dst, src, strlen(src)+1);
592 /*********************************************************************
596 * Description : Duplicate the first n characters of a string that may
597 * contain '\0' characters.
600 * 1 : string = string to be duplicated
601 * 2 : len = number of bytes to duplicate
603 * Returns : pointer to copy, or NULL if failiure
605 *********************************************************************/
606 char *bindup(const char *string, size_t len)
610 duplicate = (char *)malloc(len);
611 if (NULL != duplicate)
613 memcpy(duplicate, string, len);
621 /*********************************************************************
623 * Function : make_path
625 * Description : Takes a directory name and a file name, returns
626 * the complete path. Handles windows/unix differences.
627 * If the file name is already an absolute path, or if
628 * the directory name is NULL or empty, it returns
632 * 1 : dir: Name of directory or NULL for none.
633 * 2 : file: Name of file. Should not be NULL or empty.
635 * Returns : "dir/file" (Or on windows, "dir\file").
636 * It allocates the string on the heap. Caller frees.
637 * Returns NULL in error (i.e. NULL file or out of
640 *********************************************************************/
641 char * make_path(const char * dir, const char * file)
643 if ((file == NULL) || (*file == '\0'))
645 return NULL; /* Error */
648 if ((dir == NULL) || (*dir == '\0') /* No directory specified */
649 #if defined(_WIN32) || defined(__OS2__)
650 || (*file == '\\') || (file[1] == ':') /* Absolute path (DOS) */
651 #else /* ifndef _WIN32 || __OS2__ */
652 || (*file == '/') /* Absolute path (U*ix) */
653 #endif /* ifndef _WIN32 || __OS2__ */
661 size_t path_size = strlen(dir) + strlen(file) + 2; /* +2 for trailing (back)slash and \0 */
664 if (*dir != '/' && basedir && *basedir)
667 * Relative path, so start with the base directory.
669 path_size += strlen(basedir) + 1; /* +1 for the slash */
670 path = malloc(path_size);
671 if (!path) log_error(LOG_LEVEL_FATAL, "malloc failed!");
672 strlcpy(path, basedir, path_size);
673 strlcat(path, "/", path_size);
674 strlcat(path, dir, path_size);
677 #endif /* defined unix */
679 path = malloc(path_size);
680 if (!path) log_error(LOG_LEVEL_FATAL, "malloc failed!");
681 strlcpy(path, dir, path_size);
684 assert(NULL != path);
685 #if defined(_WIN32) || defined(__OS2__)
686 if (path[strlen(path)-1] != '\\')
688 strlcat(path, "\\", path_size);
690 #else /* ifndef _WIN32 || __OS2__ */
691 if (path[strlen(path)-1] != '/')
693 strlcat(path, "/", path_size);
695 #endif /* ifndef _WIN32 || __OS2__ */
696 strlcat(path, file, path_size);
703 /*********************************************************************
705 * Function : pick_from_range
707 * Description : Pick a positive number out of a given range.
708 * Should only be used if randomness would be nice,
709 * but isn't really necessary.
712 * 1 : range: Highest possible number to pick.
714 * Returns : Picked number.
716 *********************************************************************/
717 long int pick_from_range(long int range)
721 static unsigned long seed = 0;
722 #endif /* def _WIN32 */
727 if (range <= 0) return 0;
729 #ifdef HAVE_ARC4RANDOM
730 number = arc4random() % range + 1;
731 #elif defined(HAVE_RANDOM)
732 number = random() % range + 1;
733 #elif defined(MUTEX_LOCKS_AVAILABLE)
734 privoxy_mutex_lock(&rand_mutex);
738 seed = (unsigned long)(GetCurrentThreadId()+GetTickCount());
741 seed = (unsigned long)((rand() << 16) + rand());
742 #endif /* def _WIN32 */
743 number = (unsigned long)((rand() << 16) + (rand())) % (unsigned long)(range + 1);
744 privoxy_mutex_unlock(&rand_mutex);
747 * XXX: Which platforms reach this and are there
748 * better options than just using rand() and hoping
751 log_error(LOG_LEVEL_INFO, "No thread-safe PRNG available? Header time randomization "
752 "might cause crashes, predictable results or even combine these fine options.");
753 number = rand() % (long int)(range + 1);
755 #endif /* (def HAVE_ARC4RANDOM) */
761 #ifdef USE_PRIVOXY_STRLCPY
762 /*********************************************************************
764 * Function : privoxy_strlcpy
766 * Description : strlcpy(3) look-alike for those without decent libc.
769 * 1 : destination: buffer to copy into.
770 * 2 : source: String to copy.
771 * 3 : size: Size of destination buffer.
773 * Returns : The length of the string that privoxy_strlcpy() tried to create.
775 *********************************************************************/
776 size_t privoxy_strlcpy(char *destination, const char *source, const size_t size)
780 snprintf(destination, size, "%s", source);
782 * Platforms that lack strlcpy() also tend to have
783 * a broken snprintf implementation that doesn't
784 * guarantee nul termination.
786 * XXX: the configure script should detect and reject those.
788 destination[size-1] = '\0';
790 return strlen(source);
792 #endif /* def USE_PRIVOXY_STRLCPY */
796 /*********************************************************************
798 * Function : privoxy_strlcat
800 * Description : strlcat(3) look-alike for those without decent libc.
803 * 1 : destination: C string.
804 * 2 : source: String to copy.
805 * 3 : size: Size of destination buffer.
807 * Returns : The length of the string that privoxy_strlcat() tried to create.
809 *********************************************************************/
810 size_t privoxy_strlcat(char *destination, const char *source, const size_t size)
812 const size_t old_length = strlen(destination);
813 return old_length + strlcpy(destination + old_length, source, size - old_length);
815 #endif /* ndef HAVE_STRLCAT */
818 /*********************************************************************
820 * Function : privoxy_millisleep
822 * Description : Sleep a number of milliseconds
825 * 1 : delay: Number of milliseconds to sleep
827 * Returns : -1 on error, 0 otherwise
829 *********************************************************************/
830 int privoxy_millisleep(unsigned milliseconds)
832 #ifdef HAVE_NANOSLEEP
833 struct timespec rqtp = {0};
834 struct timespec rmtp = {0};
836 rqtp.tv_sec = milliseconds / 1000;
837 rqtp.tv_nsec = (milliseconds % 1000) * 1000 * 1000;
839 return nanosleep(&rqtp, &rmtp);
840 #elif defined (_WIN32)
844 #elif defined(__OS2__)
845 DosSleep(milliseconds * 10);
849 #warning Missing privoxy_milisleep() implementation. delay-response{} will not work.
852 #endif /* def HAVE_NANOSLEEP */
857 #if !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV)
858 /*********************************************************************
862 * Description : libc replacement function for the inverse of gmtime().
863 * Copyright (C) 2004 Free Software Foundation, Inc.
865 * Code originally copied from GnuPG, modifications done
866 * for Privoxy: style changed, #ifdefs for _WIN32 added
867 * to have it work on mingw32.
869 * XXX: It's very unlikely to happen, but if the malloc()
870 * call fails the time zone will be permanently set to UTC.
873 * 1 : tm: Broken-down time struct.
875 * Returns : tm converted into time_t seconds.
877 *********************************************************************/
878 time_t timegm(struct tm *tm)
891 old_zone = malloc(3 + strlen(zone) + 1);
894 strcpy(old_zone, "TZ=");
895 strcat(old_zone, zone);
898 /* http://man7.org/linux/man-pages/man3/putenv.3.html
899 * int putenv(char *string);
900 * The string pointed to by string becomes part of the environment, so altering the
901 * string changes the environment.
902 * In other words, the memory pointed to by *string is used until
903 * a) another call to putenv() with the same e-var name
904 * b) the program exits
906 * Windows e-vars don't work that way, so let's not leak memory.
909 #endif /* def _WIN32 */
916 #elif defined(_WIN32)
926 #endif /* !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV) */
929 #ifndef HAVE_SNPRINTF
931 * What follows is a portable snprintf routine, written by Mark Martinec.
932 * See: http://www.ijs.si/software/snprintf/
935 - a portable implementation of snprintf,
936 including vsnprintf.c, asnprintf, vasnprintf, asprintf, vasprintf
938 snprintf is a routine to convert numeric and string arguments to
939 formatted strings. It is similar to sprintf(3) provided in a system's
940 C library, yet it requires an additional argument - the buffer size -
941 and it guarantees never to store anything beyond the given buffer,
942 regardless of the format or arguments to be formatted. Some newer
943 operating systems do provide snprintf in their C library, but many do
944 not or do provide an inadequate (slow or idiosyncratic) version, which
945 calls for a portable implementation of this routine.
949 Mark Martinec <mark.martinec@ijs.si>, April 1999, June 2000
950 Copyright © 1999, Mark Martinec
954 #define PORTABLE_SNPRINTF_VERSION_MAJOR 2
955 #define PORTABLE_SNPRINTF_VERSION_MINOR 2
957 #if defined(NEED_ASPRINTF) || defined(NEED_ASNPRINTF) || defined(NEED_VASPRINTF) || defined(NEED_VASNPRINTF)
958 # if defined(NEED_SNPRINTF_ONLY)
959 # undef NEED_SNPRINTF_ONLY
961 # if !defined(PREFER_PORTABLE_SNPRINTF)
962 # define PREFER_PORTABLE_SNPRINTF
966 #if defined(SOLARIS_BUG_COMPATIBLE) && !defined(SOLARIS_COMPATIBLE)
967 #define SOLARIS_COMPATIBLE
970 #if defined(HPUX_BUG_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
971 #define HPUX_COMPATIBLE
974 #if defined(DIGITAL_UNIX_BUG_COMPATIBLE) && !defined(DIGITAL_UNIX_COMPATIBLE)
975 #define DIGITAL_UNIX_COMPATIBLE
978 #if defined(PERL_BUG_COMPATIBLE) && !defined(PERL_COMPATIBLE)
979 #define PERL_COMPATIBLE
982 #if defined(LINUX_BUG_COMPATIBLE) && !defined(LINUX_COMPATIBLE)
983 #define LINUX_COMPATIBLE
986 #include <sys/types.h>
997 #define isdigit(c) ((c) >= '0' && (c) <= '9')
999 /* For copying strings longer or equal to 'breakeven_point'
1000 * it is more efficient to call memcpy() than to do it inline.
1001 * The value depends mostly on the processor architecture,
1002 * but also on the compiler and its optimization capabilities.
1003 * The value is not critical, some small value greater than zero
1004 * will be just fine if you don't care to squeeze every drop
1005 * of performance out of the code.
1007 * Small values favor memcpy, large values favor inline code.
1009 #if defined(__alpha__) || defined(__alpha)
1010 # define breakeven_point 2 /* AXP (DEC Alpha) - gcc or cc or egcs */
1012 #if defined(__i386__) || defined(__i386)
1013 # define breakeven_point 12 /* Intel Pentium/Linux - gcc 2.96 */
1016 # define breakeven_point 10 /* HP-PA - gcc */
1018 #if defined(__sparc__) || defined(__sparc)
1019 # define breakeven_point 33 /* Sun Sparc 5 - gcc 2.8.1 */
1022 /* some other values of possible interest: */
1023 /* #define breakeven_point 8 */ /* VAX 4000 - vaxc */
1024 /* #define breakeven_point 19 */ /* VAX 4000 - gcc 2.7.0 */
1026 #ifndef breakeven_point
1027 # define breakeven_point 6 /* some reasonable one-size-fits-all value */
1030 #define fast_memcpy(d,s,n) \
1031 { register size_t nn = (size_t)(n); \
1032 if (nn >= breakeven_point) memcpy((d), (s), nn); \
1033 else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
1034 register char *dd; register const char *ss; \
1035 for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } }
1037 #define fast_memset(d,c,n) \
1038 { register size_t nn = (size_t)(n); \
1039 if (nn >= breakeven_point) memset((d), (int)(c), nn); \
1040 else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
1041 register char *dd; register const int cc=(int)(c); \
1042 for (dd=(d); nn>0; nn--) *dd++ = cc; } }
1046 #if defined(NEED_ASPRINTF)
1047 int asprintf (char **ptr, const char *fmt, /*args*/ ...);
1049 #if defined(NEED_VASPRINTF)
1050 int vasprintf (char **ptr, const char *fmt, va_list ap);
1052 #if defined(NEED_ASNPRINTF)
1053 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...);
1055 #if defined(NEED_VASNPRINTF)
1056 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap);
1059 #if defined(HAVE_SNPRINTF)
1060 /* declare our portable snprintf routine under name portable_snprintf */
1061 /* declare our portable vsnprintf routine under name portable_vsnprintf */
1063 /* declare our portable routines under names snprintf and vsnprintf */
1064 #define portable_snprintf snprintf
1065 #if !defined(NEED_SNPRINTF_ONLY)
1066 #define portable_vsnprintf vsnprintf
1070 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1071 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...);
1072 #if !defined(NEED_SNPRINTF_ONLY)
1073 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap);
1079 static char credits[] = "\n\
1080 @(#)snprintf.c, v2.2: Mark Martinec, <mark.martinec@ijs.si>\n\
1081 @(#)snprintf.c, v2.2: Copyright 1999, Mark Martinec. Frontier Artistic License applies.\n\
1082 @(#)snprintf.c, v2.2: http://www.ijs.si/software/snprintf/\n";
1084 #if defined(NEED_ASPRINTF)
1085 int asprintf(char **ptr, const char *fmt, /*args*/ ...) {
1091 va_start(ap, fmt); /* measure the required size */
1092 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
1094 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1095 *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
1096 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1100 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1102 assert(str_l2 == str_l);
1108 #if defined(NEED_VASPRINTF)
1109 int vasprintf(char **ptr, const char *fmt, va_list ap) {
1115 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
1116 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1119 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1120 *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
1121 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1123 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1124 assert(str_l2 == str_l);
1130 #if defined(NEED_ASNPRINTF)
1131 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...) {
1136 va_start(ap, fmt); /* measure the required size */
1137 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
1139 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1140 if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1; /* truncate */
1141 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1142 if (str_m == 0) { /* not interested in resulting string, just return size */
1144 *ptr = (char *) malloc(str_m);
1145 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1149 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1151 assert(str_l2 == str_l);
1158 #if defined(NEED_VASNPRINTF)
1159 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap) {
1164 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
1165 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1168 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1169 if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1; /* truncate */
1170 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1171 if (str_m == 0) { /* not interested in resulting string, just return size */
1173 *ptr = (char *) malloc(str_m);
1174 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1176 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1177 assert(str_l2 == str_l);
1185 * If the system does have snprintf and the portable routine is not
1186 * specifically required, this module produces no code for snprintf/vsnprintf.
1188 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1190 #if !defined(NEED_SNPRINTF_ONLY)
1191 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1196 str_l = portable_vsnprintf(str, str_m, fmt, ap);
1202 #if defined(NEED_SNPRINTF_ONLY)
1203 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1205 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) {
1208 #if defined(NEED_SNPRINTF_ONLY)
1212 const char *p = fmt;
1214 /* In contrast with POSIX, the ISO C99 now says
1215 * that str can be NULL and str_m can be 0.
1216 * This is more useful than the old: if (str_m < 1) return -1; */
1218 #if defined(NEED_SNPRINTF_ONLY)
1224 /* if (str_l < str_m) str[str_l++] = *p++; -- this would be sufficient */
1225 /* but the following code achieves better performance for cases
1226 * where format string is long and contains few conversions */
1227 const char *q = strchr(p+1,'%');
1228 size_t n = !q ? strlen(p) : (q-p);
1229 if (str_l < str_m) {
1230 size_t avail = str_m-str_l;
1231 fast_memcpy(str+str_l, p, (n>avail?avail:n));
1235 const char *starting_p;
1236 size_t min_field_width = 0, precision = 0;
1237 int zero_padding = 0, precision_specified = 0, justify_left = 0;
1238 int alternate_form = 0, force_sign = 0;
1239 int space_for_positive = 1; /* If both the ' ' and '+' flags appear,
1240 the ' ' flag should be ignored. */
1241 char length_modifier = '\0'; /* allowed values: \0, h, l, L */
1242 char tmp[32];/* temporary buffer for simple numeric->string conversion */
1244 const char *str_arg; /* string address in case of string argument */
1245 size_t str_arg_l; /* natural field width of arg without padding
1247 unsigned char uchar_arg;
1248 /* unsigned char argument value - only defined for c conversion.
1249 N.B. standard explicitly states the char argument for
1250 the c conversion is unsigned */
1252 size_t number_of_zeros_to_pad = 0;
1253 /* number of zeros to be inserted for numeric conversions
1254 as required by the precision or minimal field width */
1256 size_t zero_padding_insertion_ind = 0;
1257 /* index into tmp where zero padding is to be inserted */
1259 char fmt_spec = '\0';
1260 /* current conversion specifier character */
1262 str_arg = credits;/* just to make compiler happy (defined but not used)*/
1264 starting_p = p; p++; /* skip '%' */
1266 while (*p == '0' || *p == '-' || *p == '+' ||
1267 *p == ' ' || *p == '#' || *p == '\'') {
1269 case '0': zero_padding = 1; break;
1270 case '-': justify_left = 1; break;
1271 case '+': force_sign = 1; space_for_positive = 0; break;
1272 case ' ': force_sign = 1;
1273 /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */
1274 #ifdef PERL_COMPATIBLE
1275 /* ... but in Perl the last of ' ' and '+' applies */
1276 space_for_positive = 1;
1279 case '#': alternate_form = 1; break;
1284 /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
1286 /* parse field width */
1289 p++; j = va_arg(ap, int);
1290 if (j >= 0) min_field_width = j;
1291 else { min_field_width = -j; justify_left = 1; }
1292 } else if (isdigit((int)(*p))) {
1293 /* size_t could be wider than unsigned int;
1294 make sure we treat argument like common implementations do */
1295 unsigned int uj = *p++ - '0';
1296 while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1297 min_field_width = uj;
1299 /* parse precision */
1301 p++; precision_specified = 1;
1303 int j = va_arg(ap, int);
1305 if (j >= 0) precision = j;
1307 precision_specified = 0; precision = 0;
1309 * Solaris 2.6 man page claims that in this case the precision
1310 * should be set to 0. Digital Unix 4.0, HPUX 10 and BSD man page
1311 * claim that this case should be treated as unspecified precision,
1312 * which is what we do here.
1315 } else if (isdigit((int)(*p))) {
1316 /* size_t could be wider than unsigned int;
1317 make sure we treat argument like common implementations do */
1318 unsigned int uj = *p++ - '0';
1319 while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1323 /* parse 'h', 'l' and 'll' length modifiers */
1324 if (*p == 'h' || *p == 'l') {
1325 length_modifier = *p; p++;
1326 if (length_modifier == 'l' && *p == 'l') { /* double l = long long */
1327 #ifdef SNPRINTF_LONGLONG_SUPPORT
1328 length_modifier = '2'; /* double l encoded as '2' */
1330 length_modifier = 'l'; /* treat it as a single 'l' */
1336 /* common synonyms: */
1338 case 'i': fmt_spec = 'd'; break;
1339 case 'D': fmt_spec = 'd'; length_modifier = 'l'; break;
1340 case 'U': fmt_spec = 'u'; length_modifier = 'l'; break;
1341 case 'O': fmt_spec = 'o'; length_modifier = 'l'; break;
1344 /* get parameter value, do initial processing */
1346 case '%': /* % behaves similar to 's' regarding flags and field widths */
1347 case 'c': /* c behaves similar to 's' regarding flags and field widths */
1349 length_modifier = '\0'; /* wint_t and wchar_t not supported */
1350 /* the result of zero padding flag with non-numeric conversion specifier*/
1351 /* is undefined. Solaris and HPUX 10 does zero padding in this case, */
1352 /* Digital Unix and Linux does not. */
1353 #if !defined(SOLARIS_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
1354 zero_padding = 0; /* turn zero padding off for string conversions */
1361 int j = va_arg(ap, int);
1362 uchar_arg = (unsigned char) j; /* standard demands unsigned char */
1363 str_arg = (const char *) &uchar_arg;
1367 str_arg = va_arg(ap, const char *);
1368 if (!str_arg) str_arg_l = 0;
1369 /* make sure not to address string beyond the specified precision !!! */
1370 else if (!precision_specified) str_arg_l = strlen(str_arg);
1371 /* truncate string if necessary as requested by precision */
1372 else if (precision == 0) str_arg_l = 0;
1374 /* memchr on HP does not like n > 2^31 !!! */
1375 const char *q = memchr(str_arg, '\0',
1376 precision <= 0x7fffffff ? precision : 0x7fffffff);
1377 str_arg_l = !q ? precision : (q-str_arg);
1383 case 'd': case 'u': case 'o': case 'x': case 'X': case 'p': {
1384 /* NOTE: the u, o, x, X and p conversion specifiers imply
1385 the value is unsigned; d implies a signed value */
1388 /* 0 if numeric argument is zero (or if pointer is NULL for 'p'),
1389 +1 if greater than zero (or nonzero for unsigned arguments),
1390 -1 if negative (unsigned argument is never negative) */
1392 int int_arg = 0; unsigned int uint_arg = 0;
1393 /* only defined for length modifier h, or for no length modifiers */
1395 long int long_arg = 0; unsigned long int ulong_arg = 0;
1396 /* only defined for length modifier l */
1398 void *ptr_arg = NULL;
1399 /* pointer argument value -only defined for p conversion */
1401 #ifdef SNPRINTF_LONGLONG_SUPPORT
1402 long long int long_long_arg = 0;
1403 unsigned long long int ulong_long_arg = 0;
1404 /* only defined for length modifier ll */
1406 if (fmt_spec == 'p') {
1407 /* HPUX 10: An l, h, ll or L before any other conversion character
1408 * (other than d, i, u, o, x, or X) is ignored.
1410 * not specified, but seems to behave as HPUX does.
1411 * Solaris: If an h, l, or L appears before any other conversion
1412 * specifier (other than d, i, u, o, x, or X), the behavior
1413 * is undefined. (Actually %hp converts only 16-bits of address
1414 * and %llp treats address as 64-bit data which is incompatible
1415 * with (void *) argument on a 32-bit system).
1417 #ifdef SOLARIS_COMPATIBLE
1418 # ifdef SOLARIS_BUG_COMPATIBLE
1419 /* keep length modifiers even if it represents 'll' */
1421 if (length_modifier == '2') length_modifier = '\0';
1424 length_modifier = '\0';
1426 ptr_arg = va_arg(ap, void *);
1427 if (ptr_arg != NULL) arg_sign = 1;
1428 } else if (fmt_spec == 'd') { /* signed */
1429 switch (length_modifier) {
1432 /* It is non-portable to specify a second argument of char or short
1433 * to va_arg, because arguments seen by the called function
1434 * are not char or short. C converts char and short arguments
1435 * to int before passing them to a function.
1437 int_arg = va_arg(ap, int);
1438 if (int_arg > 0) arg_sign = 1;
1439 else if (int_arg < 0) arg_sign = -1;
1442 long_arg = va_arg(ap, long int);
1443 if (long_arg > 0) arg_sign = 1;
1444 else if (long_arg < 0) arg_sign = -1;
1446 #ifdef SNPRINTF_LONGLONG_SUPPORT
1448 long_long_arg = va_arg(ap, long long int);
1449 if (long_long_arg > 0) arg_sign = 1;
1450 else if (long_long_arg < 0) arg_sign = -1;
1454 } else { /* unsigned */
1455 switch (length_modifier) {
1458 uint_arg = va_arg(ap, unsigned int);
1459 if (uint_arg) arg_sign = 1;
1462 ulong_arg = va_arg(ap, unsigned long int);
1463 if (ulong_arg) arg_sign = 1;
1465 #ifdef SNPRINTF_LONGLONG_SUPPORT
1467 ulong_long_arg = va_arg(ap, unsigned long long int);
1468 if (ulong_long_arg) arg_sign = 1;
1473 str_arg = tmp; str_arg_l = 0;
1475 * For d, i, u, o, x, and X conversions, if precision is specified,
1476 * the '0' flag should be ignored. This is so with Solaris 2.6,
1477 * Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl.
1479 #ifndef PERL_COMPATIBLE
1480 if (precision_specified) zero_padding = 0;
1482 if (fmt_spec == 'd') {
1483 if (force_sign && arg_sign >= 0)
1484 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1485 /* leave negative numbers for sprintf to handle,
1486 to avoid handling tricky cases like (short int)(-32768) */
1487 #ifdef LINUX_COMPATIBLE
1488 } else if (fmt_spec == 'p' && force_sign && arg_sign > 0) {
1489 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1491 } else if (alternate_form) {
1492 if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X') )
1493 { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = fmt_spec; }
1494 /* alternate form should have no effect for p conversion, but ... */
1495 #ifdef HPUX_COMPATIBLE
1496 else if (fmt_spec == 'p'
1497 /* HPUX 10: for an alternate form of p conversion,
1498 * a nonzero result is prefixed by 0x. */
1499 #ifndef HPUX_BUG_COMPATIBLE
1500 /* Actually it uses 0x prefix even for a zero value. */
1503 ) { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = 'x'; }
1506 zero_padding_insertion_ind = str_arg_l;
1507 if (!precision_specified) precision = 1; /* default precision is 1 */
1508 if (precision == 0 && arg_sign == 0
1509 #if defined(HPUX_BUG_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1511 /* HPUX 10 man page claims: With conversion character p the result of
1512 * converting a zero value with a precision of zero is a null string.
1513 * Actually HP returns all zeroes, and Linux returns "(nil)". */
1516 /* converted to null string */
1517 /* When zero value is formatted with an explicit precision 0,
1518 the resulting formatted string is empty (d, i, u, o, x, X, p). */
1520 char f[5]; int f_l = 0;
1521 f[f_l++] = '%'; /* construct a simple format string for sprintf */
1522 if (!length_modifier) { }
1523 else if (length_modifier=='2') { f[f_l++] = 'l'; f[f_l++] = 'l'; }
1524 else f[f_l++] = length_modifier;
1525 f[f_l++] = fmt_spec; f[f_l++] = '\0';
1526 if (fmt_spec == 'p') str_arg_l += sprintf(tmp+str_arg_l, f, ptr_arg);
1527 else if (fmt_spec == 'd') { /* signed */
1528 switch (length_modifier) {
1530 case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, int_arg); break;
1531 case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, long_arg); break;
1532 #ifdef SNPRINTF_LONGLONG_SUPPORT
1533 case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,long_long_arg); break;
1536 } else { /* unsigned */
1537 switch (length_modifier) {
1539 case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, uint_arg); break;
1540 case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, ulong_arg); break;
1541 #ifdef SNPRINTF_LONGLONG_SUPPORT
1542 case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,ulong_long_arg);break;
1546 /* include the optional minus sign and possible "0x"
1547 in the region before the zero padding insertion point */
1548 if (zero_padding_insertion_ind < str_arg_l &&
1549 tmp[zero_padding_insertion_ind] == '-') {
1550 zero_padding_insertion_ind++;
1552 if (zero_padding_insertion_ind+1 < str_arg_l &&
1553 tmp[zero_padding_insertion_ind] == '0' &&
1554 (tmp[zero_padding_insertion_ind+1] == 'x' ||
1555 tmp[zero_padding_insertion_ind+1] == 'X') ) {
1556 zero_padding_insertion_ind += 2;
1559 { size_t num_of_digits = str_arg_l - zero_padding_insertion_ind;
1560 if (alternate_form && fmt_spec == 'o'
1561 #ifdef HPUX_COMPATIBLE /* ("%#.o",0) -> "" */
1564 #ifdef DIGITAL_UNIX_BUG_COMPATIBLE /* ("%#o",0) -> "00" */
1566 /* unless zero is already the first character */
1567 && !(zero_padding_insertion_ind < str_arg_l
1568 && tmp[zero_padding_insertion_ind] == '0')
1570 ) { /* assure leading zero for alternate-form octal numbers */
1571 if (!precision_specified || precision < num_of_digits+1) {
1572 /* precision is increased to force the first character to be zero,
1573 except if a zero value is formatted with an explicit precision
1575 precision = num_of_digits+1; precision_specified = 1;
1578 /* zero padding to specified precision? */
1579 if (num_of_digits < precision)
1580 number_of_zeros_to_pad = precision - num_of_digits;
1582 /* zero padding to specified minimal field width? */
1583 if (!justify_left && zero_padding) {
1584 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1585 if (n > 0) number_of_zeros_to_pad += n;
1589 default: /* unrecognized conversion specifier, keep format string as-is*/
1590 zero_padding = 0; /* turn zero padding off for non-numeric convers. */
1591 #ifndef DIGITAL_UNIX_COMPATIBLE
1592 justify_left = 1; min_field_width = 0; /* reset flags */
1594 #if defined(PERL_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1595 /* keep the entire format string unchanged */
1596 str_arg = starting_p; str_arg_l = p - starting_p;
1597 /* well, not exactly so for Linux, which does something between,
1598 * and I don't feel an urge to imitate it: "%+++++hy" -> "%+y" */
1600 /* discard the unrecognized conversion, just keep *
1601 * the unrecognized conversion character */
1602 str_arg = p; str_arg_l = 0;
1604 if (*p) str_arg_l++; /* include invalid conversion specifier unchanged
1605 if not at end-of-string */
1608 if (*p) p++; /* step over the just processed conversion specifier */
1609 /* insert padding to the left as requested by min_field_width;
1610 this does not include the zero padding in case of numerical conversions*/
1611 if (!justify_left) { /* left padding with blank or zero */
1612 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1614 if (str_l < str_m) {
1615 size_t avail = str_m-str_l;
1616 fast_memset(str+str_l, (zero_padding?'0':' '), (n>avail?avail:n));
1621 /* zero padding as requested by the precision or by the minimal field width
1622 * for numeric conversions required? */
1623 if (number_of_zeros_to_pad <= 0) {
1624 /* will not copy first part of numeric right now, *
1625 * force it to be copied later in its entirety */
1626 zero_padding_insertion_ind = 0;
1628 /* insert first part of numerics (sign or '0x') before zero padding */
1629 int n = zero_padding_insertion_ind;
1631 if (str_l < str_m) {
1632 size_t avail = str_m-str_l;
1633 fast_memcpy(str+str_l, str_arg, (n>avail?avail:n));
1637 /* insert zero padding as requested by the precision or min field width */
1638 n = number_of_zeros_to_pad;
1640 if (str_l < str_m) {
1641 size_t avail = str_m-str_l;
1642 fast_memset(str+str_l, '0', (n>avail?avail:n));
1647 /* insert formatted string
1648 * (or as-is conversion specifier for unknown conversions) */
1649 { int n = str_arg_l - zero_padding_insertion_ind;
1651 if (str_l < str_m) {
1652 size_t avail = str_m-str_l;
1653 fast_memcpy(str+str_l, str_arg+zero_padding_insertion_ind,
1659 /* insert right padding */
1660 if (justify_left) { /* right blank padding to the field width */
1661 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1663 if (str_l < str_m) {
1664 size_t avail = str_m-str_l;
1665 fast_memset(str+str_l, ' ', (n>avail?avail:n));
1672 #if defined(NEED_SNPRINTF_ONLY)
1675 if (str_m > 0) { /* make sure the string is null-terminated
1676 even at the expense of overwriting the last character
1677 (shouldn't happen, but just in case) */
1678 str[str_l <= str_m-1 ? str_l : str_m-1] = '\0';
1680 /* Return the number of characters formatted (excluding trailing null
1681 * character), that is, the number of characters that would have been
1682 * written to the buffer if it were large enough.
1684 * The value of str_l should be returned, but str_l is of unsigned type
1685 * size_t, and snprintf is int, possibly leading to an undetected
1686 * integer overflow, resulting in a negative return value, which is illegal.
1687 * Both XSH5 and ISO C99 (at least the draft) are silent on this issue.
1688 * Should errno be set to EOVERFLOW and EOF returned in this case???
1693 #endif /* ndef HAVE_SNPRINTF */