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_64BITUSERPOINTER_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))
210 pad(struct snprintf_state *state, int width, char c)
214 (*state->append_char)(state, c);
220 /* return true if we should use alternatve hex form */
222 use_alternative (int flags, afs_uint64 num, unsigned base)
224 return (flags & alternate_flag) && base == 16 && num != 0;
228 append_number(struct snprintf_state *state,
229 afs_uint64 num, unsigned base, const char *rep,
230 int width, int prec, int flags, int minusp)
234 char nstr[MAXPREC]; /* enough for <192 bit octal integers */
238 /* given precision, ignore zero flag */
244 /* format number as string */
245 nstart = sizeof(nstr);
247 nstr[--nstart] = '\0';
250 nstr[--nstart] = rep[n % base];
255 /* zero value with zero precision should produce no digits */
256 if(prec == 0 && num == 0) {
261 /* figure out what char to use for sign */
264 else if((flags & plus_flag))
266 else if((flags & space_flag))
271 if((flags & alternate_flag) && base == 8) {
272 /* if necessary, increase the precision to
273 make first digit a zero */
275 /* XXX C99 claims (regarding # and %o) that "if the value and
276 precision are both 0, a single 0 is printed", but there is
277 no such wording for %x. This would mean that %#.o would
278 output "0", but %#.x "". This does not make sense, and is
279 also not what other printf implementations are doing. */
281 if(prec <= nlen && nstr[nstart] != '0' && nstr[nstart] != '\0')
286 pad | sign | alt | zero | digits
287 sign | alt | zero | digits | pad minus_flag
288 sign | alt | zero | digits zero_flag */
290 /* if not right justifying or padding with zeros, we need to
291 compute the length of the rest of the string, and then pad with
293 if(!(flags & (minus_flag | zero_flag))) {
299 if(use_alternative(flags, num, base))
306 len += pad(state, width, ' ');
308 if(signchar != '\0') {
309 (*state->append_char)(state, signchar);
312 if(use_alternative(flags, num, base)) {
313 (*state->append_char)(state, '0');
314 (*state->append_char)(state, rep[10] + 23); /* XXX */
317 if(flags & zero_flag) {
318 /* pad to width with zeros */
319 if(prec - nlen > width - len - nlen)
320 len += pad(state, prec - nlen, '0');
322 len += pad(state, width - len - nlen, '0');
324 /* pad to prec with zeros */
325 len += pad(state, prec - nlen, '0');
327 while(nstr[nstart] != '\0') {
328 (*state->append_char)(state, nstr[nstart++]);
332 if(flags & minus_flag)
333 len += pad(state, width - len, ' ');
343 append_string (struct snprintf_state *state,
344 const unsigned char *arg,
352 arg = (const unsigned char*)"(null)";
357 width -= (int)strlen((const char *)arg);
358 if(!(flags & minus_flag))
359 len += pad(state, width, ' ');
362 while (*arg && prec--) {
363 (*state->append_char) (state, *arg++);
368 (*state->append_char) (state, *arg++);
372 if(flags & minus_flag)
373 len += pad(state, width, ' ');
378 append_char(struct snprintf_state *state,
385 while(!(flags & minus_flag) && --width > 0) {
386 (*state->append_char) (state, ' ') ;
389 (*state->append_char) (state, arg);
391 while((flags & minus_flag) && --width > 0) {
392 (*state->append_char) (state, ' ');
400 append_float(struct snprintf_state *state,
408 char fbuf[20], xbuf[MAXPREC + 21];
410 sprintf(fbuf, "%%%s%s.*L%c",
411 (flags & plus_flag) ? "+" : ((flags & space_flag) ? " " : ((flags & minus_flag) ? "-" : "")),
412 (flags & alternate_flag) ? "#" : "", type);
417 sprintf(xbuf, fbuf, prec, arg);
419 len = append_string(state, (unsigned char *)xbuf, width, -1, 0);
424 append_address(struct snprintf_state *state,
436 * value is provided as a network-order unsigned long integer
437 * precision specifies max hostname length, as for %s
438 * if precision is explicitly 0, no hostname lookup is done
439 * if 0fill specified, IPaddr fields are 0-filled to 3 digits
440 * if spsign specified, IPaddr fields are space-filled to 3 digits
446 he = gethostbyaddr((char *)&ia, 4, AF_INET);
449 len = (int)strlen(x);
450 if (prec != -1 && prec < len)
454 if (flags & alternate_flag) {
458 } else if (flags & plus_flag) {
463 len = append_string(state, (unsigned char *)x, width, prec, 0);
467 if (flags & zero_flag) {
468 x = "%03u.%03u.%03u.%03u";
469 } else if (flags & space_flag) {
470 x = "%3u.%3u.%3u.%3u";
474 /* typecast to whatever '%u' is! */
475 sprintf(xbuf, x, (unsigned int)((arg & 0xff000000) >> 24),
476 (unsigned int)((arg & 0x00ff0000) >> 16),
477 (unsigned int)((arg & 0x0000ff00) >> 8),
478 (unsigned int)(arg & 0x000000ff));
479 len = append_string(state, (unsigned char *)xbuf, 0, -1, 0);
486 * This can't be made into a function...
489 #if defined(AFS_NT40_ENV)
491 #define PARSE_INT_FORMAT(res, arg, unsig) \
492 if (long_long_flag) \
493 res = (unsig __int64)va_arg(arg, unsig __int64); \
494 else if (long_flag || addr_flag) \
495 res = (unsig long)va_arg(arg, unsig long); \
496 else if (size_t_flag) \
497 res = (size_t)va_arg(arg, size_t); \
498 else if (short_flag) \
499 res = (unsig short)va_arg(arg, unsig int); \
501 res = (unsig int)va_arg(arg, unsig int)
503 #else /* AFS_NT40_ENV */
505 #define PARSE_INT_FORMAT(res, arg, unsig) \
506 if (long_long_flag) \
507 res = (unsig long long)va_arg(arg, unsig long long); \
508 else if (long_flag || addr_flag) \
509 res = (unsig long)va_arg(arg, unsig long); \
510 else if (size_t_flag) \
511 res = (size_t)va_arg(arg, size_t); \
512 else if (short_flag) \
513 res = (unsig short)va_arg(arg, unsig int); \
515 res = (unsig int)va_arg(arg, unsig int)
520 * zyxprintf - return length, as snprintf
524 xyzprintf (struct snprintf_state *state, const char *char_format, va_list ap)
526 const unsigned char *format = (const unsigned char *)char_format;
530 while((c = *format++)) {
536 int long_long_flag = 0;
542 while((c = *format++)){
550 flags |= alternate_flag;
559 if((flags & space_flag) && (flags & plus_flag))
562 if((flags & minus_flag) && (flags & zero_flag))
568 width = width * 10 + c - '0';
572 width = va_arg(ap, int);
582 prec = prec * 10 + c - '0';
586 prec = va_arg(ap, int);
596 } else if (c == 'z') {
599 } else if (c == 'l') {
606 } else if (c == 'I') {
607 /* This could be either Microsoft I{32,64} notation */
615 } else if (c == '6') {
623 /* Or the OpenAFS special %I meaning network address */
628 } else if (c == 'p') {
631 prec = 2 * sizeof(void *);
632 if (sizeof(void *) == sizeof(afs_uint64))
634 else if (sizeof(void *) == sizeof(afs_uint32))
640 if(c != 'd' && c != 'i' && c != 'I')
641 flags &= ~(plus_flag | space_flag);
645 append_char(state, va_arg(ap, int), width, flags);
649 len += append_string(state,
650 va_arg(ap, unsigned char*),
661 PARSE_INT_FORMAT(arg, ap, signed);
669 len += append_number (state, num, 10, "0123456789",
670 width, prec, flags, minusp);
676 PARSE_INT_FORMAT(arg, ap, unsigned);
678 len += append_number (state, arg, 10, "0123456789",
679 width, prec, flags, 0);
685 PARSE_INT_FORMAT(arg, ap, unsigned);
687 len += append_number (state, arg, 010, "01234567",
688 width, prec, flags, 0);
694 PARSE_INT_FORMAT(arg, ap, unsigned);
696 len += append_number (state, arg, 0x10, "0123456789abcdef",
697 width, prec, flags, 0);
703 PARSE_INT_FORMAT(arg, ap, unsigned);
705 len += append_number (state, arg, 0x10, "0123456789ABCDEF",
706 width, prec, flags, 0);
710 #ifdef AFS_64BITUSERPOINTER_ENV
711 afs_uint64 arg = (afs_uint64)va_arg(ap, void*);
713 afs_uint64 arg = (unsigned long)va_arg(ap, void*);
715 len += append_number (state, arg, 0x10, "0123456789ABCDEF",
716 width, prec, flags, 0);
720 int *arg = va_arg(ap, int*);
721 *arg = (int)(state->s - state->str);
727 PARSE_INT_FORMAT(arg, ap, unsigned);
729 len += append_address (state, (unsigned long)arg, width, prec, flags);
737 double arg = (double)va_arg(ap, double);
739 len += append_float (state, c, arg, width, prec, flags);
746 (*state->append_char)(state, c);
750 (*state->append_char)(state, '%');
751 (*state->append_char)(state, c);
756 (*state->append_char) (state, c);
765 afs_vsnprintf (char *str, size_t sz, const char *format, va_list args)
767 struct snprintf_state state;
769 unsigned char *ustr = (unsigned char *)str;
775 state.theend = ustr + sz - (sz > 0);
776 state.append_char = afs_sn_append_char;
778 ret = xyzprintf (&state, format, args);
779 if (state.s != NULL && sz != 0)
785 afs_snprintf (char *str, size_t sz, const char *format, ...)
790 va_start(args, format);
791 ret = afs_vsnprintf (str, sz, format, args);
799 tmp = (unsigned char *)malloc (sz);
803 va_start(args, format);
804 ret2 = afs_vsprintf (tmp, format, args);
806 if (ret != ret2 || strcmp(str, tmp))
816 afs_vasnprintf (char **ret, size_t max_sz, const char *format, va_list args)
819 struct snprintf_state state;
821 state.max_sz = max_sz;
823 state.str = (unsigned char *)malloc(state.sz);
824 if (state.str == NULL) {
829 state.theend = state.s + state.sz - 1;
830 state.append_char = as_append_char;
832 st = xyzprintf (&state, format, args);
841 tmp = (char *)realloc (state.str, st+1);
853 afs_vasprintf (char **ret, const char *format, va_list args)
855 return afs_vasnprintf (ret, 0, format, args);
859 afs_asprintf (char **ret, const char *format, ...)
864 va_start(args, format);
865 val = afs_vasprintf (ret, format, args);
872 tmp = (unsigned char *)malloc (val + 1);
876 va_start(args, format);
877 ret2 = afs_vsprintf (tmp, format, args);
879 if (val != ret2 || strcmp(*ret, tmp))
889 afs_asnprintf (char **ret, size_t max_sz, const char *format, ...)
894 va_start(args, format);
895 val = afs_vasnprintf (ret, max_sz, format, args);
901 tmp = (unsigned char *)malloc (val + 1);
905 ret2 = afs_vsprintf (tmp, format, args);
906 if (val != ret2 || strcmp(*ret, tmp))
920 vsyslog(int priority, const char *format, va_list args)
923 afs_vsnprintf(buf, sizeof(buf), format, args);
924 syslog(priority, "%s", buf);