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>
42 /* This is an enhanced version of the *printf functionality shipped
43 * with Heimdal. In addition to the standard Unix formatting types
44 * this version also supports Microsoft's I32 and I64 type modifiers
45 * and the OpenAFS I type which is used to generate output from
46 * network byte order IPv4 addresses (either dotted notation or
47 * hostname lookups. Implementation details follow:
49 * - Actually obeys the length limit, which (unfortunately) many
50 * implementations of snprintf do not.
52 * - Supports all the standard format specifiers for integers
53 * (d, i, o, u, x, X), floating-point values (f, e, E, g, G),
54 * and strings and characters (c, s, %), plus a few unusual
55 * but useful ones described below.
57 * - The Microsoft integral size modifiers I32 and I64 are
58 * supported. I32 is equivalent to 'l'.
59 * I64 is equivalent to 'll'.
61 * - Supports all the standard flags (-, 0, +, space, #). These
62 * flags are ignored if used when they are not appropriate.
64 * - Supports the standard size modifiers for short (h), long (h),
65 * and double (L) arguments. These modifiers are ignored if used
66 * when they are not appropriate.
68 * - Supports minimum field width and precision, where appropriate,
69 * including the use of '*' to specify a value given as an argument
70 * instead of in the format string. There is a maximum precision
73 * - The 'p' specifier for printing pointers is implemented using
74 * intptr_t (C99-standard).
76 * - Floating-point specifier (%e, %f, %g) are implemented by
77 * calling the standard sprintf, and thus may be unsafe.
79 * - The '%...$' notation is used primarily when the format string
80 * is specified by the user, who knows but cannot change the order
81 * of the arguments. Such usage is inherently dangerous and
82 * insecure; thus, it is not supported.
84 * - Passing in a format and an NULL buffer is supported. This
85 * will compute the size of the buffer required by the format
86 * and the provided input parameters.
88 * The custom format specifier '%I' is supported. This specifier
89 * takes as its argument an unsigned long integer containing an
90 * IPv4 address in network byte order. The address is rendered
91 * either as a hostname or as a dotted quad, as follows:
93 * - If precision is nonzero or unspecified, a hostname lookup
94 * is attempted; if it is successful, the hostname is printed.
95 * If the hostname lookup fails, the address is printed in
96 * dotted-quad notation.
98 * - If precision is explicitly specified as 0, then the hostname
99 * lookup is skipped, and dotted-quad notation is always used.
101 * - If a hostname is to be printed:
102 * + The precision controls the maximum number of characters
103 * printed, as with %s.
104 * + If the '#' flag is specified, any letters in the hostname
105 * will be forced to lower case before printing.
106 * + If the '+' flag is specified, any letters in the hostname
107 * will be forced to upper case before printing. If both
108 * '#' and '+' are given, the '+' flag will be ignored.
109 * + The '0' and ' ' flags have no effect.
111 * - If a dotted quad is to be printed:
112 * + The precision has no effect; dotted quads are always
113 * 7 to 12 characters in length, depending on the value
114 * to be printed and the format flags used.
115 * + If the '0' flag is given, each field (byte) of the address
116 * will be padded with '0' on the left to three digits.
117 * + If the ' ' flag is given, each field (byte) of the address
118 * will be padded with spaces on the left to three digits. If
119 * both '0' and ' ' are given, the ' ' flag will be ignored.
120 * + The '#' and '+' flags have no effect.
122 * A test program exists in src/util/tests/snprintf_tests.c.
139 struct snprintf_state {
142 unsigned char *theend;
145 void (*append_char)(struct snprintf_state *, unsigned char);
150 afs_sn_reserve (struct snprintf_state *state, size_t n)
152 return state->s + n > state->theend;
156 afs_sn_append_char (struct snprintf_state *state, unsigned char c)
158 if (!afs_sn_reserve (state, 1))
163 as_reserve (struct snprintf_state *state, size_t n)
165 if (state->s + n > state->theend) {
166 size_t off = state->s - state->str;
169 if (state->max_sz && state->sz >= state->max_sz)
172 state->sz = max(state->sz * 2, state->sz + n);
174 state->sz = min(state->sz, state->max_sz);
175 tmp = (unsigned char *)realloc (state->str, state->sz);
179 state->s = state->str + off;
180 state->theend = state->str + state->sz - 1;
186 as_append_char (struct snprintf_state *state, unsigned char c)
188 if(!as_reserve (state, 1))
193 pad(struct snprintf_state *state, int width, char c)
197 (*state->append_char)(state, c);
203 /* return true if we should use alternatve hex form */
205 use_alternative (int flags, afs_uint64 num, unsigned base)
207 return (flags & alternate_flag) && base == 16 && num != 0;
211 append_number(struct snprintf_state *state,
212 afs_uint64 num, unsigned base, const char *rep,
213 int width, int prec, int flags, int minusp)
217 char nstr[MAXPREC]; /* enough for <192 bit octal integers */
221 /* given precision, ignore zero flag */
227 /* format number as string */
228 nstart = sizeof(nstr);
230 nstr[--nstart] = '\0';
233 nstr[--nstart] = rep[n % base];
238 /* zero value with zero precision should produce no digits */
239 if(prec == 0 && num == 0) {
244 /* figure out what char to use for sign */
247 else if((flags & plus_flag))
249 else if((flags & space_flag))
254 if((flags & alternate_flag) && base == 8) {
255 /* if necessary, increase the precision to
256 make first digit a zero */
258 /* XXX C99 claims (regarding # and %o) that "if the value and
259 precision are both 0, a single 0 is printed", but there is
260 no such wording for %x. This would mean that %#.o would
261 output "0", but %#.x "". This does not make sense, and is
262 also not what other printf implementations are doing. */
264 if(prec <= nlen && nstr[nstart] != '0' && nstr[nstart] != '\0')
269 pad | sign | alt | zero | digits
270 sign | alt | zero | digits | pad minus_flag
271 sign | alt | zero | digits zero_flag */
273 /* if not right justifying or padding with zeros, we need to
274 compute the length of the rest of the string, and then pad with
276 if(!(flags & (minus_flag | zero_flag))) {
282 if(use_alternative(flags, num, base))
289 len += pad(state, width, ' ');
291 if(signchar != '\0') {
292 (*state->append_char)(state, signchar);
295 if(use_alternative(flags, num, base)) {
296 (*state->append_char)(state, '0');
297 (*state->append_char)(state, rep[10] + 23); /* XXX */
300 if(flags & zero_flag) {
301 /* pad to width with zeros */
302 if(prec - nlen > width - len - nlen)
303 len += pad(state, prec - nlen, '0');
305 len += pad(state, width - len - nlen, '0');
307 /* pad to prec with zeros */
308 len += pad(state, prec - nlen, '0');
310 while(nstr[nstart] != '\0') {
311 (*state->append_char)(state, nstr[nstart++]);
315 if(flags & minus_flag)
316 len += pad(state, width - len, ' ');
326 append_string (struct snprintf_state *state,
327 const unsigned char *arg,
335 arg = (const unsigned char*)"(null)";
340 width -= (int)strlen((const char *)arg);
341 if(!(flags & minus_flag))
342 len += pad(state, width, ' ');
345 while (*arg && prec--) {
346 (*state->append_char) (state, *arg++);
351 (*state->append_char) (state, *arg++);
355 if(flags & minus_flag)
356 len += pad(state, width, ' ');
361 append_char(struct snprintf_state *state,
368 while(!(flags & minus_flag) && --width > 0) {
369 (*state->append_char) (state, ' ') ;
372 (*state->append_char) (state, arg);
374 while((flags & minus_flag) && --width > 0) {
375 (*state->append_char) (state, ' ');
383 append_float(struct snprintf_state *state,
391 char fbuf[20], xbuf[MAXPREC + 21];
393 sprintf(fbuf, "%%%s%s.*L%c",
394 (flags & plus_flag) ? "+" : ((flags & space_flag) ? " " : ((flags & minus_flag) ? "-" : "")),
395 (flags & alternate_flag) ? "#" : "", type);
400 sprintf(xbuf, fbuf, prec, arg);
402 len = append_string(state, (unsigned char *)xbuf, width, -1, 0);
407 append_address(struct snprintf_state *state,
419 * value is provided as a network-order unsigned long integer
420 * precision specifies max hostname length, as for %s
421 * if precision is explicitly 0, no hostname lookup is done
422 * if 0fill specified, IPaddr fields are 0-filled to 3 digits
423 * if spsign specified, IPaddr fields are space-filled to 3 digits
429 he = gethostbyaddr((char *)&ia, 4, AF_INET);
432 len = (int)strlen(x);
433 if (prec != -1 && prec < len)
437 if (flags & alternate_flag) {
441 } else if (flags & plus_flag) {
446 len = append_string(state, (unsigned char *)x, width, prec, 0);
450 if (flags & zero_flag) {
451 x = "%03u.%03u.%03u.%03u";
452 } else if (flags & space_flag) {
453 x = "%3u.%3u.%3u.%3u";
457 /* typecast to whatever '%u' is! */
458 sprintf(xbuf, x, (unsigned int)((arg & 0xff000000) >> 24),
459 (unsigned int)((arg & 0x00ff0000) >> 16),
460 (unsigned int)((arg & 0x0000ff00) >> 8),
461 (unsigned int)(arg & 0x000000ff));
462 len = append_string(state, (unsigned char *)xbuf, 0, -1, 0);
469 * This can't be made into a function...
472 #if defined(AFS_NT40_ENV)
474 #define PARSE_INT_FORMAT(res, arg, unsig) \
475 if (long_long_flag) \
476 res = (unsig __int64)va_arg(arg, unsig __int64); \
477 else if (long_flag || addr_flag) \
478 res = (unsig long)va_arg(arg, unsig long); \
479 else if (size_t_flag) \
480 res = (size_t)va_arg(arg, size_t); \
481 else if (short_flag) \
482 res = (unsig short)va_arg(arg, unsig int); \
484 res = (unsig int)va_arg(arg, unsig int)
486 #else /* AFS_NT40_ENV */
488 #define PARSE_INT_FORMAT(res, arg, unsig) \
489 if (long_long_flag) \
490 res = (unsig long long)va_arg(arg, unsig long long); \
491 else if (long_flag || addr_flag) \
492 res = (unsig long)va_arg(arg, unsig long); \
493 else if (size_t_flag) \
494 res = (size_t)va_arg(arg, size_t); \
495 else if (short_flag) \
496 res = (unsig short)va_arg(arg, unsig int); \
498 res = (unsig int)va_arg(arg, unsig int)
503 * zyxprintf - return length, as snprintf
507 xyzprintf (struct snprintf_state *state, const char *char_format, va_list ap)
509 const unsigned char *format = (const unsigned char *)char_format;
513 while((c = *format++)) {
519 int long_long_flag = 0;
525 while((c = *format++)){
533 flags |= alternate_flag;
542 if((flags & space_flag) && (flags & plus_flag))
545 if((flags & minus_flag) && (flags & zero_flag))
551 width = width * 10 + c - '0';
555 width = va_arg(ap, int);
565 prec = prec * 10 + c - '0';
569 prec = va_arg(ap, int);
579 } else if (c == 'z') {
582 } else if (c == 'l') {
589 } else if (c == 'I') {
590 /* This could be either Microsoft I{32,64} notation */
598 } else if (c == '6') {
606 /* Or the OpenAFS special %I meaning network address */
611 } else if (c == 'p') {
614 prec = 2 * sizeof(void *);
615 if (sizeof(void *) == sizeof(afs_uint64))
617 else if (sizeof(void *) == sizeof(afs_uint32))
623 if(c != 'd' && c != 'i' && c != 'I')
624 flags &= ~(plus_flag | space_flag);
628 append_char(state, va_arg(ap, int), width, flags);
632 len += append_string(state,
633 va_arg(ap, unsigned char*),
644 PARSE_INT_FORMAT(arg, ap, signed);
652 len += append_number (state, num, 10, "0123456789",
653 width, prec, flags, minusp);
659 PARSE_INT_FORMAT(arg, ap, unsigned);
661 len += append_number (state, arg, 10, "0123456789",
662 width, prec, flags, 0);
668 PARSE_INT_FORMAT(arg, ap, unsigned);
670 len += append_number (state, arg, 010, "01234567",
671 width, prec, flags, 0);
677 PARSE_INT_FORMAT(arg, ap, unsigned);
679 len += append_number (state, arg, 0x10, "0123456789abcdef",
680 width, prec, flags, 0);
686 PARSE_INT_FORMAT(arg, ap, unsigned);
688 len += append_number (state, arg, 0x10, "0123456789ABCDEF",
689 width, prec, flags, 0);
693 afs_uint64 arg = (intptr_t)va_arg(ap, void*);
694 len += append_number (state, arg, 0x10, "0123456789ABCDEF",
695 width, prec, flags, 0);
699 int *arg = va_arg(ap, int*);
700 *arg = (int)(state->s - state->str);
706 PARSE_INT_FORMAT(arg, ap, unsigned);
708 len += append_address (state, (unsigned long)arg, width, prec, flags);
716 double arg = (double)va_arg(ap, double);
718 len += append_float (state, c, arg, width, prec, flags);
725 (*state->append_char)(state, c);
729 (*state->append_char)(state, '%');
730 (*state->append_char)(state, c);
735 (*state->append_char) (state, c);
744 afs_vsnprintf (char *str, size_t sz, const char *format, va_list args)
746 struct snprintf_state state;
748 unsigned char *ustr = (unsigned char *)str;
754 state.theend = ustr + sz - (sz > 0);
755 state.append_char = afs_sn_append_char;
757 ret = xyzprintf (&state, format, args);
758 if (state.s != NULL && sz != 0)
764 afs_snprintf (char *str, size_t sz, const char *format, ...)
769 va_start(args, format);
770 ret = afs_vsnprintf (str, sz, format, args);
778 tmp = (unsigned char *)malloc (sz);
782 va_start(args, format);
783 ret2 = afs_vsprintf (tmp, format, args);
785 if (ret != ret2 || strcmp(str, tmp))
795 afs_vasnprintf (char **ret, size_t max_sz, const char *format, va_list args)
798 struct snprintf_state state;
800 state.max_sz = max_sz;
802 state.str = (unsigned char *)malloc(state.sz);
803 if (state.str == NULL) {
808 state.theend = state.s + state.sz - 1;
809 state.append_char = as_append_char;
811 st = xyzprintf (&state, format, args);
820 tmp = (char *)realloc (state.str, st+1);
832 afs_vasprintf (char **ret, const char *format, va_list args)
834 return afs_vasnprintf (ret, 0, format, args);
838 afs_asprintf (char **ret, const char *format, ...)
843 va_start(args, format);
844 val = afs_vasprintf (ret, format, args);
851 tmp = (unsigned char *)malloc (val + 1);
855 va_start(args, format);
856 ret2 = afs_vsprintf (tmp, format, args);
858 if (val != ret2 || strcmp(*ret, tmp))
868 afs_asnprintf (char **ret, size_t max_sz, const char *format, ...)
873 va_start(args, format);
874 val = afs_vasnprintf (ret, max_sz, format, args);
880 tmp = (unsigned char *)malloc (val + 1);
884 ret2 = afs_vsprintf (tmp, format, args);
885 if (val != ret2 || strcmp(*ret, tmp))
899 vsyslog(int priority, const char *format, va_list args)
902 afs_vsnprintf(buf, sizeof(buf), format, args);
903 syslog(priority, "%s", buf);