2 * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan
3 * (Royal Institute of Technology, Stockholm, Sweden).
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the Institute nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 /* snprintf.c - Formatted, length-limited print to a string */
36 #include <afsconfig.h>
37 #include <afs/param.h>
40 #include <sys/types.h>
47 #include <netinet/in.h>
55 #if defined(AFS_AIX32_ENV) || defined(AFS_SUN_ENV) || defined(AFS_XBSD_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_SGI65_ENV)
56 #include <sys/socket.h>
59 /* This is an enhanced version of the *printf functionality shipped
60 * with Heimdal. In addition to the standard Unix formatting types
61 * this version also supports Microsoft's I32 and I64 type modifiers
62 * and the OpenAFS I type which is used to generate output from
63 * network byte order IPv4 addresses (either dotted notation or
64 * hostname lookups. Implementation details follow:
66 * - Actually obeys the length limit, which (unfortunately) many
67 * implementations of snprintf do not.
69 * - Supports all the standard format specifiers for integers
70 * (d, i, o, u, x, X), floating-point values (f, e, E, g, G),
71 * and strings and characters (c, s, %), plus a few unusual
72 * but useful ones described below.
74 * - The Microsoft integral size modifiers I32 and I64 are
75 * supported. I32 is equivalent to 'l'.
76 * I64 is equivalent to 'll'.
78 * - Supports all the standard flags (-, 0, +, space, #). These
79 * flags are ignored if used when they are not appropriate.
81 * - Supports the standard size modifiers for short (h), long (h),
82 * and double (L) arguments. These modifiers are ignored if used
83 * when they are not appropriate.
85 * - Supports minimum field width and precision, where appropriate,
86 * including the use of '*' to specify a value given as an argument
87 * instead of in the format string. There is a maximum precision
90 * - The 'p' specifier for printing pointers is implemented using
91 * compile time knowledge. (AFS_64BITPOINTER_ENV)
93 * - Floating-point specifier (%e, %f, %g) are implemented by
94 * calling the standard sprintf, and thus may be unsafe.
96 * - The '%...$' notation is used primarily when the format string
97 * is specified by the user, who knows but cannot change the order
98 * of the arguments. Such usage is inherently dangerous and
99 * insecure; thus, it is not supported.
101 * - Passing in a format and an NULL buffer is supported. This
102 * will compute the size of the buffer required by the format
103 * and the provided input parameters.
105 * The custom format specifier '%I' is supported. This specifier
106 * takes as its argument an unsigned long integer containing an
107 * IPv4 address in network byte order. The address is rendered
108 * either as a hostname or as a dotted quad, as follows:
110 * - If precision is nonzero or unspecified, a hostname lookup
111 * is attempted; if it is successful, the hostname is printed.
112 * If the hostname lookup fails, the address is printed in
113 * dotted-quad notation.
115 * - If precision is explicitly specified as 0, then the hostname
116 * lookup is skipped, and dotted-quad notation is always used.
118 * - If a hostname is to be printed:
119 * + The precision controls the maximum number of characters
120 * printed, as with %s.
121 * + If the '#' flag is specified, any letters in the hostname
122 * will be forced to lower case before printing.
123 * + If the '+' flag is specified, any letters in the hostname
124 * will be forced to upper case before printing. If both
125 * '#' and '+' are given, the '+' flag will be ignored.
126 * + The '0' and ' ' flags have no effect.
128 * - If a dotted quad is to be printed:
129 * + The precision has no effect; dotted quads are always
130 * 7 to 12 characters in length, depending on the value
131 * to be printed and the format flags used.
132 * + If the '0' flag is given, each field (byte) of the address
133 * will be padded with '0' on the left to three digits.
134 * + If the ' ' flag is given, each field (byte) of the address
135 * will be padded with spaces on the left to three digits. If
136 * both '0' and ' ' are given, the ' ' flag will be ignored.
137 * + The '#' and '+' flags have no effect.
139 * A test program exists in src/util/tests/snprintf_tests.c.
156 struct snprintf_state {
159 unsigned char *theend;
162 void (*append_char)(struct snprintf_state *, unsigned char);
167 afs_sn_reserve (struct snprintf_state *state, size_t n)
169 return state->s + n > state->theend;
173 afs_sn_append_char (struct snprintf_state *state, unsigned char c)
175 if (!afs_sn_reserve (state, 1))
180 as_reserve (struct snprintf_state *state, size_t n)
182 if (state->s + n > state->theend) {
183 size_t off = state->s - state->str;
186 if (state->max_sz && state->sz >= state->max_sz)
189 state->sz = max(state->sz * 2, state->sz + n);
191 state->sz = min(state->sz, state->max_sz);
192 tmp = (unsigned char *)realloc (state->str, state->sz);
196 state->s = state->str + off;
197 state->theend = state->str + state->sz - 1;
203 as_append_char (struct snprintf_state *state, unsigned char c)
205 if(!as_reserve (state, 1))
209 /* longest integer types */
212 typedef afs_uint64 u_longest;
213 typedef afs_int64 longest;
215 typedef afs_uint32 u_longest;
216 typedef afs_int32 longest;
220 pad(struct snprintf_state *state, int width, char c)
224 (*state->append_char)(state, c);
230 /* return true if we should use alternatve hex form */
232 use_alternative (int flags, u_longest num, unsigned base)
234 return (flags & alternate_flag) && base == 16 && num != 0;
238 append_number(struct snprintf_state *state,
239 u_longest num, unsigned base, const char *rep,
240 int width, int prec, int flags, int minusp)
244 char nstr[MAXPREC]; /* enough for <192 bit octal integers */
248 /* given precision, ignore zero flag */
254 /* format number as string */
255 nstart = sizeof(nstr);
257 nstr[--nstart] = '\0';
260 nstr[--nstart] = rep[n % base];
265 /* zero value with zero precision should produce no digits */
266 if(prec == 0 && num == 0) {
271 /* figure out what char to use for sign */
274 else if((flags & plus_flag))
276 else if((flags & space_flag))
281 if((flags & alternate_flag) && base == 8) {
282 /* if necessary, increase the precision to
283 make first digit a zero */
285 /* XXX C99 claims (regarding # and %o) that "if the value and
286 precision are both 0, a single 0 is printed", but there is
287 no such wording for %x. This would mean that %#.o would
288 output "0", but %#.x "". This does not make sense, and is
289 also not what other printf implementations are doing. */
291 if(prec <= nlen && nstr[nstart] != '0' && nstr[nstart] != '\0')
296 pad | sign | alt | zero | digits
297 sign | alt | zero | digits | pad minus_flag
298 sign | alt | zero | digits zero_flag */
300 /* if not right justifying or padding with zeros, we need to
301 compute the length of the rest of the string, and then pad with
303 if(!(flags & (minus_flag | zero_flag))) {
309 if(use_alternative(flags, num, base))
316 len += pad(state, width, ' ');
318 if(signchar != '\0') {
319 (*state->append_char)(state, signchar);
322 if(use_alternative(flags, num, base)) {
323 (*state->append_char)(state, '0');
324 (*state->append_char)(state, rep[10] + 23); /* XXX */
327 if(flags & zero_flag) {
328 /* pad to width with zeros */
329 if(prec - nlen > width - len - nlen)
330 len += pad(state, prec - nlen, '0');
332 len += pad(state, width - len - nlen, '0');
334 /* pad to prec with zeros */
335 len += pad(state, prec - nlen, '0');
337 while(nstr[nstart] != '\0') {
338 (*state->append_char)(state, nstr[nstart++]);
342 if(flags & minus_flag)
343 len += pad(state, width - len, ' ');
353 append_string (struct snprintf_state *state,
354 const unsigned char *arg,
362 arg = (const unsigned char*)"(null)";
367 width -= (int)strlen((const char *)arg);
368 if(!(flags & minus_flag))
369 len += pad(state, width, ' ');
372 while (*arg && prec--) {
373 (*state->append_char) (state, *arg++);
378 (*state->append_char) (state, *arg++);
382 if(flags & minus_flag)
383 len += pad(state, width, ' ');
388 append_char(struct snprintf_state *state,
395 while(!(flags & minus_flag) && --width > 0) {
396 (*state->append_char) (state, ' ') ;
399 (*state->append_char) (state, arg);
401 while((flags & minus_flag) && --width > 0) {
402 (*state->append_char) (state, ' ');
410 append_float(struct snprintf_state *state,
418 char fbuf[20], xbuf[MAXPREC + 21];
420 sprintf(fbuf, "%%%s%s.*L%c",
421 (flags & plus_flag) ? "+" : ((flags & space_flag) ? " " : ((flags & minus_flag) ? "-" : "")),
422 (flags & alternate_flag) ? "#" : "", type);
427 sprintf(xbuf, fbuf, prec, arg);
429 len = append_string(state, (unsigned char *)xbuf, width, -1, 0);
434 append_address(struct snprintf_state *state,
446 * value is provided as a network-order unsigned long integer
447 * precision specifies max hostname length, as for %s
448 * if precision is explicitly 0, no hostname lookup is done
449 * if 0fill specified, IPaddr fields are 0-filled to 3 digits
450 * if spsign specified, IPaddr fields are space-filled to 3 digits
456 he = gethostbyaddr((char *)&ia, 4, AF_INET);
459 len = (int)strlen(x);
460 if (prec != -1 && prec < len)
464 if (flags & alternate_flag) {
468 } else if (flags & plus_flag) {
473 len = append_string(state, (unsigned char *)x, width, prec, 0);
477 if (flags & zero_flag) {
478 x = "%03u.%03u.%03u.%03u";
479 } else if (flags & space_flag) {
480 x = "%3u.%3u.%3u.%3u";
484 /* typecast to whatever '%u' is! */
485 sprintf(xbuf, x, (unsigned int)((arg & 0xff000000) >> 24),
486 (unsigned int)((arg & 0x00ff0000) >> 16),
487 (unsigned int)((arg & 0x0000ff00) >> 8),
488 (unsigned int)(arg & 0x000000ff));
489 len = append_string(state, (unsigned char *)xbuf, 0, -1, 0);
496 * This can't be made into a function...
499 #if defined(AFS_64BIT_ENV)
500 #if defined(AFS_NT40_ENV)
502 #define PARSE_INT_FORMAT(res, arg, unsig) \
503 if (long_long_flag) \
504 res = (unsig __int64)va_arg(arg, unsig __int64); \
505 else if (long_flag || addr_flag) \
506 res = (unsig long)va_arg(arg, unsig long); \
507 else if (size_t_flag) \
508 res = (size_t)va_arg(arg, size_t); \
509 else if (short_flag) \
510 res = (unsig short)va_arg(arg, unsig int); \
512 res = (unsig int)va_arg(arg, unsig int)
514 #else /* AFS_NT40_ENV */
516 #define PARSE_INT_FORMAT(res, arg, unsig) \
517 if (long_long_flag) \
518 res = (unsig long long)va_arg(arg, unsig long long); \
519 else if (long_flag || addr_flag) \
520 res = (unsig long)va_arg(arg, unsig long); \
521 else if (size_t_flag) \
522 res = (size_t)va_arg(arg, size_t); \
523 else if (short_flag) \
524 res = (unsig short)va_arg(arg, unsig int); \
526 res = (unsig int)va_arg(arg, unsig int)
531 #define PARSE_INT_FORMAT(res, arg, unsig) \
532 if (long_flag || addr_flag) \
533 res = (afs_uint32)va_arg(arg, afs_uint32); \
534 else if (size_t_flag) \
535 res = (size_t)va_arg(arg, size_t); \
536 else if (short_flag) \
537 res = (unsig short)va_arg(arg, unsig int); \
539 res = (unsig int)va_arg(arg, unsig int)
544 * zyxprintf - return length, as snprintf
548 xyzprintf (struct snprintf_state *state, const char *char_format, va_list ap)
550 const unsigned char *format = (const unsigned char *)char_format;
554 while((c = *format++)) {
560 int long_long_flag = 0;
566 while((c = *format++)){
574 flags |= alternate_flag;
583 if((flags & space_flag) && (flags & plus_flag))
586 if((flags & minus_flag) && (flags & zero_flag))
592 width = width * 10 + c - '0';
596 width = va_arg(ap, int);
606 prec = prec * 10 + c - '0';
610 prec = va_arg(ap, int);
620 } else if (c == 'z') {
623 } else if (c == 'l') {
630 } else if (c == 'I') {
631 /* This could be either Microsoft I{32,64} notation */
639 } else if (c == '6') {
647 /* Or the OpenAFS special %I meaning network address */
652 } else if (c == 'p') {
655 prec = 2 * sizeof(void *);
656 if (sizeof(void *) == sizeof(afs_uint64))
658 else if (sizeof(void *) == sizeof(afs_uint32))
664 if(c != 'd' && c != 'i' && c != 'I')
665 flags &= ~(plus_flag | space_flag);
669 append_char(state, va_arg(ap, int), width, flags);
673 len += append_string(state,
674 va_arg(ap, unsigned char*),
685 PARSE_INT_FORMAT(arg, ap, signed);
693 len += append_number (state, num, 10, "0123456789",
694 width, prec, flags, minusp);
700 PARSE_INT_FORMAT(arg, ap, unsigned);
702 len += append_number (state, arg, 10, "0123456789",
703 width, prec, flags, 0);
709 PARSE_INT_FORMAT(arg, ap, unsigned);
711 len += append_number (state, arg, 010, "01234567",
712 width, prec, flags, 0);
718 PARSE_INT_FORMAT(arg, ap, unsigned);
720 len += append_number (state, arg, 0x10, "0123456789abcdef",
721 width, prec, flags, 0);
727 PARSE_INT_FORMAT(arg, ap, unsigned);
729 len += append_number (state, arg, 0x10, "0123456789ABCDEF",
730 width, prec, flags, 0);
734 #ifdef AFS_64BITPOINTER_ENV
735 u_longest arg = (u_longest)va_arg(ap, void*);
737 u_longest arg = (unsigned long)va_arg(ap, void*);
739 len += append_number (state, arg, 0x10, "0123456789ABCDEF",
740 width, prec, flags, 0);
744 int *arg = va_arg(ap, int*);
745 *arg = (int)(state->s - state->str);
751 PARSE_INT_FORMAT(arg, ap, unsigned);
753 len += append_address (state, (unsigned long)arg, width, prec, flags);
761 double arg = (double)va_arg(ap, double);
763 len += append_float (state, c, arg, width, prec, flags);
770 (*state->append_char)(state, c);
774 (*state->append_char)(state, '%');
775 (*state->append_char)(state, c);
780 (*state->append_char) (state, c);
789 afs_vsnprintf (char *str, size_t sz, const char *format, va_list args)
791 struct snprintf_state state;
793 unsigned char *ustr = (unsigned char *)str;
799 state.theend = ustr + sz - (sz > 0);
800 state.append_char = afs_sn_append_char;
802 ret = xyzprintf (&state, format, args);
803 if (state.s != NULL && sz != 0)
809 afs_snprintf (char *str, size_t sz, const char *format, ...)
814 va_start(args, format);
815 ret = afs_vsnprintf (str, sz, format, args);
823 tmp = (unsigned char *)malloc (sz);
827 va_start(args, format);
828 ret2 = afs_vsprintf (tmp, format, args);
830 if (ret != ret2 || strcmp(str, tmp))
840 afs_vasnprintf (char **ret, size_t max_sz, const char *format, va_list args)
843 struct snprintf_state state;
845 state.max_sz = max_sz;
847 state.str = (unsigned char *)malloc(state.sz);
848 if (state.str == NULL) {
853 state.theend = state.s + state.sz - 1;
854 state.append_char = as_append_char;
856 st = xyzprintf (&state, format, args);
865 tmp = (char *)realloc (state.str, st+1);
877 afs_vasprintf (char **ret, const char *format, va_list args)
879 return afs_vasnprintf (ret, 0, format, args);
883 afs_asprintf (char **ret, const char *format, ...)
888 va_start(args, format);
889 val = afs_vasprintf (ret, format, args);
896 tmp = (unsigned char *)malloc (val + 1);
900 va_start(args, format);
901 ret2 = afs_vsprintf (tmp, format, args);
903 if (val != ret2 || strcmp(*ret, tmp))
913 afs_asnprintf (char **ret, size_t max_sz, const char *format, ...)
918 va_start(args, format);
919 val = afs_vasnprintf (ret, max_sz, format, args);
925 tmp = (unsigned char *)malloc (val + 1);
929 ret2 = afs_vsprintf (tmp, format, args);
930 if (val != ret2 || strcmp(*ret, tmp))
940 #if defined(AFS_OSF20_ENV) && !defined(AFS_DUX50_ENV) || defined(AFS_AIX32_ENV) || (defined(AFS_SUN55_ENV) && !defined(AFS_SUN56_ENV)) || !defined(HAVE_VSNPRINTF) || defined(TEST_SNPRINTF)
942 #if defined(AFS_AIX51_ENV) || defined(AFS_NT40_ENV)
944 vsnprintf(char *p, size_t avail, const char *fmt, va_list ap)
947 vsnprintf(char *p, unsigned int avail, char *fmt, va_list ap)
951 result = afs_vsnprintf(p, avail, fmt, ap);
952 #if defined(AFS_AIX51_ENV) || defined(AFS_NT40_ENV)
956 #endif /* AFS_OSF20_ENV || AFS_AIX32_ENV */
961 vsyslog(int priority, const char *format, va_list args)
964 afs_vsnprintf(buf, sizeof(buf), format, args);
965 syslog(priority, "%s", buf);
969 #if defined(AFS_OSF20_ENV) && !defined(AFS_DUX50_ENV) || defined(AFS_AIX32_ENV) || (defined(AFS_SUN55_ENV) && !defined(AFS_SUN56_ENV)) || !defined(HAVE_SNPRINTF)
973 snprintf(char *p, size_t avail, const char *fmt, ...)
976 snprintf(char *p, unsigned int avail, char *fmt, ...)
983 result = afs_vsnprintf(p, avail, fmt, ap);
989 #endif /* AFS_OSF20_ENV || AFS_AIX32_ENV */
990 #endif /* AFS_NT40_ENV */