3a901a624245c3f973aedf993059e816a682185d
[openafs.git] / src / util / snprintf.c
1 /*
2  * Copyright (c) 1997 - 2004 Kungliga Tekniska Högskolan
3  * (Royal Institute of Technology, Stockholm, Sweden).
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  *
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.
16  *
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.
20  *
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
31  * SUCH DAMAGE.
32  */
33
34 /* snprintf.c - Formatted, length-limited print to a string */
35
36 #include <afsconfig.h>
37 #include <afs/param.h>
38
39
40 #include <sys/types.h>
41 #include <stdlib.h>
42 #include <stdarg.h>
43 #include <stdio.h>
44 #include <ctype.h>
45 #include <string.h>
46 #ifndef AFS_NT40_ENV
47 #include <netinet/in.h>
48 #include <netdb.h>
49 #ifndef HAVE_VSYSLOG
50 #include <syslog.h>
51 #endif
52 #else
53 #include <winsock2.h>
54 #endif
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>
57 #endif
58
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:
65  *
66  *   - Actually obeys the length limit, which (unfortunately) many
67  *     implementations of snprintf do not.
68  *  
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.
73  *
74  *   - The Microsoft integral size modifiers I32 and I64 are 
75  *     supported.  I32 is equivalent to 'l'.
76  *     I64 is equivalent to 'll'.
77  *  
78  *   - Supports all the standard flags (-, 0, +, space, #).  These
79  *     flags are ignored if used when they are not appropriate.
80  *  
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.
84  *  
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
88  *     of 100 digits.
89  *  
90  *   - The 'p' specifier for printing pointers is implemented using
91  *     compile time knowledge.  (AFS_64BITPOINTER_ENV)
92  *
93  *   - Floating-point specifier (%e, %f, %g) are implemented by
94  *     calling the standard sprintf, and thus may be unsafe.
95  *  
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.
100  *
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.
104  *  
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:
109  *  
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.
114  *  
115  *   - If precision is explicitly specified as 0, then the hostname
116  *     lookup is skipped, and dotted-quad notation is always used.
117  *  
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.
127  *  
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.
138  *
139  * A test program exists in src/util/tests/snprintf_tests.c.
140  */
141
142 #define MAXPREC 100 
143
144 enum format_flags {
145     minus_flag     =  1,
146     plus_flag      =  2,
147     space_flag     =  4,
148     alternate_flag =  8,
149     zero_flag      = 16
150 };
151
152 /*
153  * Common state
154  */
155
156 struct snprintf_state {
157     unsigned char *str;
158     unsigned char *s;
159     unsigned char *theend;
160     size_t sz;
161     size_t max_sz;
162     void (*append_char)(struct snprintf_state *, unsigned char);
163     /* XXX - methods */
164 };
165
166 static int
167 afs_sn_reserve (struct snprintf_state *state, size_t n)
168 {
169     return state->s + n > state->theend;
170 }
171
172 static void
173 afs_sn_append_char (struct snprintf_state *state, unsigned char c)
174 {
175     if (!afs_sn_reserve (state, 1))
176         *state->s++ = c;
177 }
178
179 static int
180 as_reserve (struct snprintf_state *state, size_t n)
181 {
182     if (state->s + n > state->theend) {
183         size_t off = state->s - state->str;
184         unsigned char *tmp;
185
186         if (state->max_sz && state->sz >= state->max_sz)
187             return 1;
188
189         state->sz = max(state->sz * 2, state->sz + n);
190         if (state->max_sz)
191             state->sz = min(state->sz, state->max_sz);
192         tmp = (unsigned char *)realloc (state->str, state->sz);
193         if (tmp == NULL)
194             return 1;
195         state->str = tmp;
196         state->s = state->str + off;
197         state->theend = state->str + state->sz - 1;
198     }
199     return 0;
200 }
201
202 static void
203 as_append_char (struct snprintf_state *state, unsigned char c)
204 {
205     if(!as_reserve (state, 1))
206         *state->s++ = c;
207 }
208
209 /* longest integer types */
210
211 #ifdef AFS_64BIT_ENV
212 typedef afs_uint64 u_longest;
213 typedef afs_int64 longest;
214 #else
215 typedef afs_uint32 u_longest;
216 typedef afs_int32 longest;
217 #endif
218
219 static int
220 pad(struct snprintf_state *state, int width, char c)
221 {
222     int len = 0;
223     while(width-- > 0){
224         (*state->append_char)(state,  c);
225         ++len;
226     }
227     return len;
228 }
229
230 /* return true if we should use alternatve hex form */
231 static int
232 use_alternative (int flags, u_longest num, unsigned base)
233 {
234     return (flags & alternate_flag) && base == 16 && num != 0;
235 }
236
237 static int
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)
241 {
242     int len = 0;
243     u_longest n = num;
244     char nstr[MAXPREC]; /* enough for <192 bit octal integers */
245     int nstart, nlen;
246     char signchar;
247
248     /* given precision, ignore zero flag */
249     if(prec != -1)
250         flags &= ~zero_flag;
251     else
252         prec = 1;
253
254     /* format number as string */
255     nstart = sizeof(nstr);
256     nlen = 0;
257     nstr[--nstart] = '\0';
258
259     do {
260         nstr[--nstart] = rep[n % base];
261         ++nlen;
262         n /= base;
263     } while(n);
264
265     /* zero value with zero precision should produce no digits */
266     if(prec == 0 && num == 0) {
267         nlen--;
268         nstart++;
269     }
270
271     /* figure out what char to use for sign */
272     if(minusp)
273         signchar = '-';
274     else if((flags & plus_flag))
275         signchar = '+';
276     else if((flags & space_flag))
277         signchar = ' ';
278     else
279         signchar = '\0';
280
281     if((flags & alternate_flag) && base == 8) {
282         /* if necessary, increase the precision to
283            make first digit a zero */
284
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. */
290         
291         if(prec <= nlen && nstr[nstart] != '0' && nstr[nstart] != '\0')
292             prec = nlen + 1;
293     }
294
295     /* possible formats:
296        pad | sign | alt | zero | digits
297        sign | alt | zero | digits | pad   minus_flag
298        sign | alt | zero | digits zero_flag */
299
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
302        spaces */
303     if(!(flags & (minus_flag | zero_flag))) {
304         if(prec > nlen)
305             width -= prec;
306         else
307             width -= nlen;
308         
309         if(use_alternative(flags, num, base))
310             width -= 2;
311         
312         if(signchar != '\0')
313             width--;
314         
315         /* pad to width */
316         len += pad(state, width, ' ');
317     }
318     if(signchar != '\0') {
319         (*state->append_char)(state, signchar);
320         ++len;
321     }
322     if(use_alternative(flags, num, base)) {
323         (*state->append_char)(state, '0');
324         (*state->append_char)(state, rep[10] + 23); /* XXX */
325         len += 2;
326     }
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');
331         else
332             len += pad(state, width - len - nlen, '0');
333     } else
334         /* pad to prec with zeros */
335         len += pad(state, prec - nlen, '0');
336         
337     while(nstr[nstart] != '\0') {
338         (*state->append_char)(state, nstr[nstart++]);
339         ++len;
340     }
341         
342     if(flags & minus_flag)
343         len += pad(state, width - len, ' ');
344
345     return len;
346 }
347
348 /*
349  * return length
350  */
351
352 static int
353 append_string (struct snprintf_state *state,
354                const unsigned char *arg,
355                int width,
356                int prec,
357                int flags)
358 {
359     int len = 0;
360
361     if(arg == NULL)
362         arg = (const unsigned char*)"(null)";
363
364     if(prec != -1)
365         width -= prec;
366     else
367         width -= (int)strlen((const char *)arg);
368     if(!(flags & minus_flag))
369         len += pad(state, width, ' ');
370
371     if (prec != -1) {
372         while (*arg && prec--) {
373             (*state->append_char) (state, *arg++);
374             ++len;
375         }
376     } else {
377         while (*arg) {
378             (*state->append_char) (state, *arg++);
379             ++len;
380         }
381     }
382     if(flags & minus_flag)
383         len += pad(state, width, ' ');
384     return len;
385 }
386
387 static int
388 append_char(struct snprintf_state *state,
389             unsigned char arg,
390             int width,
391             int flags)
392 {
393     int len = 0;
394
395     while(!(flags & minus_flag) && --width > 0) {
396         (*state->append_char) (state, ' ')    ;
397         ++len;
398     }
399     (*state->append_char) (state, arg);
400     ++len;
401     while((flags & minus_flag) && --width > 0) {
402         (*state->append_char) (state, ' ');
403         ++len;
404     }
405     return 0;
406 }
407
408 #define MAXPREC 100 
409 static int
410 append_float(struct snprintf_state *state,
411              char type,
412              double arg,
413              int width,
414              int prec,
415              int flags)
416 {
417     int len = 0;
418     char fbuf[20], xbuf[MAXPREC + 21];
419
420     sprintf(fbuf, "%%%s%s.*L%c", 
421             (flags & plus_flag) ? "+" : ((flags & space_flag) ? " " : ((flags & minus_flag) ? "-" : "")),
422             (flags & alternate_flag) ? "#" : "", type);
423     if (prec == -1)
424         prec = 6;
425     if (prec > MAXPREC)
426         prec = MAXPREC;
427     sprintf(xbuf, fbuf, prec, arg);
428
429     len = append_string(state, (unsigned char *)xbuf, width, -1, 0);
430     return len;
431 }
432
433 static int
434 append_address(struct snprintf_state *state,
435                afs_uint32 arg,
436                int width,
437                int prec,
438                int flags)
439 {
440     int len = 0;
441     struct hostent * he;
442     struct in_addr ia;
443     char * x, *y;
444
445     /* IP address:
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
451      */
452     ia.s_addr = arg;
453     if (prec == 0)
454         he = 0;
455     else
456         he = gethostbyaddr((char *)&ia, 4, AF_INET);
457     if (he) {
458         x = he->h_name;
459         len = (int)strlen(x);
460         if (prec != -1 && prec < len)
461             width = prec;
462         else 
463             width = len;
464         if (flags & alternate_flag) {
465             for (y = x; *y; y++)
466                 if (isupper(*y))
467                     *y = tolower(*y);
468         } else if (flags & plus_flag) {
469             for (y = x; *y; y++)
470                 if (islower(*y))
471                     *y = toupper(*y);
472         }
473         len = append_string(state, (unsigned char *)x, width, prec, 0);
474     } else {
475         char xbuf[16];
476         arg = ntohl(arg);
477         if (flags & zero_flag) {
478             x = "%03u.%03u.%03u.%03u";
479         } else if (flags & space_flag) {
480             x = "%3u.%3u.%3u.%3u";
481         } else {
482             x = "%u.%u.%u.%u";
483         }
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);
490     }        
491
492     return len;
493 }
494
495 /*
496  * This can't be made into a function...
497  */
498
499 #if defined(AFS_64BIT_ENV)
500 #if defined(AFS_NT40_ENV)
501
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); \
511 else \
512      res = (unsig int)va_arg(arg, unsig int)
513
514 #else /* AFS_NT40_ENV */
515
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); \
525 else \
526      res = (unsig int)va_arg(arg, unsig int)
527 #endif
528
529 #else
530
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); \
538 else \
539      res = (unsig int)va_arg(arg, unsig int)
540
541 #endif
542
543 /*
544  * zyxprintf - return length, as snprintf
545  */
546
547 static int
548 xyzprintf (struct snprintf_state *state, const char *char_format, va_list ap)
549 {
550     const unsigned char *format = (const unsigned char *)char_format;
551     unsigned char c;
552     int len = 0;
553
554     while((c = *format++)) {
555         if (c == '%') {
556             int flags          = 0;
557             int width          = 0;
558             int prec           = -1;
559             int size_t_flag    = 0;
560             int long_long_flag = 0;
561             int long_flag      = 0;
562             int short_flag     = 0;
563             int addr_flag      = 0;
564
565             /* flags */
566             while((c = *format++)){
567                 if(c == '-')
568                     flags |= minus_flag;
569                 else if(c == '+')
570                     flags |= plus_flag;
571                 else if(c == ' ')
572                     flags |= space_flag;
573                 else if(c == '#')
574                     flags |= alternate_flag;
575                 else if(c == '0')
576                     flags |= zero_flag;
577                 else if(c == '\'')
578                     ; /* just ignore */
579                 else
580                     break;
581             }
582
583             if((flags & space_flag) && (flags & plus_flag))
584                 flags ^= space_flag;
585
586             if((flags & minus_flag) && (flags & zero_flag))
587                 flags ^= zero_flag;
588
589             /* width */
590             if (isdigit(c))
591                 do {
592                     width = width * 10 + c - '0';
593                     c = *format++;
594                 } while(isdigit(c));
595             else if(c == '*') {
596                 width = va_arg(ap, int);
597                 c = *format++;
598             }
599
600             /* precision */
601             if (c == '.') {
602                 prec = 0;
603                 c = *format++;
604                 if (isdigit(c))
605                     do {
606                         prec = prec * 10 + c - '0';
607                         c = *format++;
608                     } while(isdigit(c));
609                 else if (c == '*') {
610                     prec = va_arg(ap, int);
611                     c = *format++;
612                 }
613             }
614
615             /* size */
616
617             if (c == 'h') {
618                 short_flag = 1;
619                 c = *format++;
620             } else if (c == 'z') {
621                 size_t_flag = 1;
622                 c = *format++;
623             } else if (c == 'l') {
624                 long_flag = 1;
625                 c = *format++;
626                 if (c == 'l') {
627                     long_long_flag = 1;
628                     c = *format++;
629                 }
630             } else if (c == 'I') {
631                 /* This could be either Microsoft I{32,64} notation */
632                 c = *format++;
633                 if (c == '3') {
634                     long_flag = 1;
635                     c = *format++;
636                     if (c == '2') {
637                         c = *format++;
638                     }
639                 } else if (c == '6') {
640                     long_flag = 1;
641                     c = *format++;
642                     if (c == '4') {
643                         long_long_flag = 1;
644                         c = *format++;
645                     }
646                 } else {
647                     /* Or the OpenAFS special %I meaning network address */
648                     addr_flag = 1;
649                     --format;
650                     c = 'I';
651                 }
652             } else if (c == 'p') {
653                 flags |= zero_flag;
654                 if (prec == -1)
655                     prec = 2 * sizeof(void *);
656                 if (sizeof(void *) == sizeof(afs_uint64))
657                     long_long_flag = 1;
658                 else if (sizeof(void *) == sizeof(afs_uint32))
659                     long_flag = 1;
660                 else 
661                     long_flag = 1;
662             }
663
664             if(c != 'd' && c != 'i' && c != 'I')
665                 flags &= ~(plus_flag | space_flag);
666
667             switch (c) {
668             case 'c' :
669                 append_char(state, va_arg(ap, int), width, flags);
670                 ++len;
671                 break;
672             case 's' :
673                 len += append_string(state,
674                                      va_arg(ap, unsigned char*),
675                                      width,
676                                      prec,
677                                      flags);
678                 break;
679             case 'd' :
680             case 'i' : {
681                 longest arg;
682                 u_longest num;
683                 int minusp = 0;
684
685                 PARSE_INT_FORMAT(arg, ap, signed);
686
687                 if (arg < 0) {
688                     minusp = 1;
689                     num = -arg;
690                 } else
691                     num = arg;
692
693                 len += append_number (state, num, 10, "0123456789",
694                                       width, prec, flags, minusp);
695                 break;
696             }
697             case 'u' : {
698                 u_longest arg;
699
700                 PARSE_INT_FORMAT(arg, ap, unsigned);
701
702                 len += append_number (state, arg, 10, "0123456789",
703                                       width, prec, flags, 0);
704                 break;
705             }
706             case 'o' : {
707                 u_longest arg;
708
709                 PARSE_INT_FORMAT(arg, ap, unsigned);
710
711                 len += append_number (state, arg, 010, "01234567",
712                                       width, prec, flags, 0);
713                 break;
714             }
715             case 'x' : {
716                 u_longest arg;
717
718                 PARSE_INT_FORMAT(arg, ap, unsigned);
719
720                 len += append_number (state, arg, 0x10, "0123456789abcdef",
721                                       width, prec, flags, 0);
722                 break;
723             }
724             case 'X' :{
725                 u_longest arg;
726
727                 PARSE_INT_FORMAT(arg, ap, unsigned);
728
729                 len += append_number (state, arg, 0x10, "0123456789ABCDEF",
730                                       width, prec, flags, 0);
731                 break;
732             }
733             case 'p' : {
734 #ifdef AFS_64BITPOINTER_ENV
735                 u_longest arg = (u_longest)va_arg(ap, void*);
736 #else
737                 u_longest arg = (unsigned long)va_arg(ap, void*);
738 #endif
739                 len += append_number (state, arg, 0x10, "0123456789ABCDEF",
740                                       width, prec, flags, 0);
741                 break;
742             }
743             case 'n' : {
744                 int *arg = va_arg(ap, int*);
745                 *arg = (int)(state->s - state->str);
746                 break;
747             }
748             case 'I' : {
749                 u_longest arg;
750
751                 PARSE_INT_FORMAT(arg, ap, unsigned);
752
753                 len += append_address (state, (unsigned long)arg, width, prec, flags);
754                 break;
755             }
756             case 'e':
757             case 'E':
758             case 'f':
759             case 'g':
760             case 'G': {
761                 double arg = (double)va_arg(ap, double);
762
763                 len += append_float (state, c, arg, width, prec, flags);
764                 break;
765             }
766             case '\0' :
767                 --format;
768                 /* FALLTHROUGH */
769             case '%' :
770                 (*state->append_char)(state, c);
771                 ++len;
772                 break;
773             default :
774                 (*state->append_char)(state, '%');
775                 (*state->append_char)(state, c);
776                 len += 2;
777                 break;
778             }
779         } else {
780             (*state->append_char) (state, c);
781             ++len;
782         }
783     }
784     return len;
785 }
786
787
788 int
789 afs_vsnprintf (char *str, size_t sz, const char *format, va_list args)
790 {
791     struct snprintf_state state;
792     int ret;
793     unsigned char *ustr = (unsigned char *)str;
794
795     state.max_sz = 0;
796     state.sz     = sz;
797     state.str    = ustr;
798     state.s      = ustr;
799     state.theend = ustr + sz - (sz > 0);
800     state.append_char = afs_sn_append_char;
801
802     ret = xyzprintf (&state, format, args);
803     if (state.s != NULL && sz != 0)
804         *state.s = '\0';
805     return ret;
806 }
807
808 int
809 afs_snprintf (char *str, size_t sz, const char *format, ...)
810 {
811     va_list args;
812     int ret;
813
814     va_start(args, format);
815     ret = afs_vsnprintf (str, sz, format, args);
816     va_end(args);
817
818 #ifdef PARANOIA
819     {
820         int ret2;
821         unsigned char *tmp;
822
823         tmp = (unsigned char *)malloc (sz);
824         if (tmp == NULL)
825             abort ();
826
827         va_start(args, format);
828         ret2 = afs_vsprintf (tmp, format, args);
829         va_end(args);
830         if (ret != ret2 || strcmp(str, tmp))
831             abort ();
832         free (tmp);
833     }
834 #endif
835
836     return ret;
837 }
838
839 int
840 afs_vasnprintf (char **ret, size_t max_sz, const char *format, va_list args)
841 {
842     int st;
843     struct snprintf_state state;
844
845     state.max_sz = max_sz;
846     state.sz     = 1;
847     state.str    = (unsigned char *)malloc(state.sz);
848     if (state.str == NULL) {
849         *ret = NULL;
850         return -1;
851     }
852     state.s = state.str;
853     state.theend = state.s + state.sz - 1;
854     state.append_char = as_append_char;
855
856     st = xyzprintf (&state, format, args);
857     if (st > state.sz) {
858         free (state.str);
859         *ret = NULL;
860         return -1;
861     } else {
862         char *tmp;
863
864         *state.s = '\0';
865         tmp = (char *)realloc (state.str, st+1);
866         if (tmp == NULL) {
867             free (state.str);
868             *ret = NULL;
869             return -1;
870         }
871         *ret = tmp;
872         return st;
873     }
874 }
875
876 int
877 afs_vasprintf (char **ret, const char *format, va_list args)
878 {
879     return afs_vasnprintf (ret, 0, format, args);
880 }
881
882 int
883 afs_asprintf (char **ret, const char *format, ...)
884 {
885     va_list args;
886     int val;
887
888     va_start(args, format);
889     val = afs_vasprintf (ret, format, args);
890     va_end(args);
891
892 #ifdef PARANOIA
893     {
894         int ret2;
895         unsigned char *tmp;
896         tmp = (unsigned char *)malloc (val + 1);
897         if (tmp == NULL)
898             abort ();
899
900         va_start(args, format);
901         ret2 = afs_vsprintf (tmp, format, args);
902         va_end(args);
903         if (val != ret2 || strcmp(*ret, tmp))
904             abort ();
905         free (tmp);
906     }
907 #endif
908
909     return val;
910 }
911
912 int
913 afs_asnprintf (char **ret, size_t max_sz, const char *format, ...)
914 {
915     va_list args;
916     int val;
917
918     va_start(args, format);
919     val = afs_vasnprintf (ret, max_sz, format, args);
920
921 #ifdef PARANOIA
922     {
923         int ret2;
924         unsigned char *tmp;
925         tmp = (unsigned char *)malloc (val + 1);
926         if (tmp == NULL)
927             abort ();
928
929         ret2 = afs_vsprintf (tmp, format, args);
930         if (val != ret2 || strcmp(*ret, tmp))
931             abort ();
932         free (tmp);
933     }
934 #endif
935
936     va_end(args);
937     return val;
938 }
939
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)
941
942 #if defined(AFS_AIX51_ENV) || defined(AFS_NT40_ENV)
943 int
944 vsnprintf(char *p, size_t avail, const char *fmt, va_list ap)
945 #else
946 void
947 vsnprintf(char *p, unsigned int avail, char *fmt, va_list ap)
948 #endif
949 {
950     int result;
951     result = afs_vsnprintf(p, avail, fmt, ap);
952 #if defined(AFS_AIX51_ENV) || defined(AFS_NT40_ENV)
953     return result;
954 #endif
955 }
956 #endif /* AFS_OSF20_ENV || AFS_AIX32_ENV */
957
958 #ifndef AFS_NT40_ENV
959 #ifndef HAVE_VSYSLOG
960 void
961 vsyslog(int priority, const char *format, va_list args)
962 {
963   char buf[1024];
964   afs_vsnprintf(buf, sizeof(buf), format, args);
965   syslog(priority, "%s", buf);
966 }
967 #endif
968
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)
970
971 #ifdef AFS_AIX51_ENV
972 int
973 snprintf(char *p, size_t avail, const char *fmt, ...)
974 #else
975 void
976 snprintf(char *p, unsigned int avail, char *fmt, ...)
977 #endif
978 {
979     va_list ap;
980     int result;
981
982     va_start(ap, fmt);
983     result = afs_vsnprintf(p, avail, fmt, ap);
984     va_end(ap);
985 #ifdef AFS_AIX51_ENV
986     return result;
987 #endif
988 }
989 #endif /* AFS_OSF20_ENV || AFS_AIX32_ENV */
990 #endif /* AFS_NT40_ENV */