util-warning-cleanup-20011005
[openafs.git] / src / util / snprintf.c
1 /* snprintf.c - Formatted, length-limited print to a string */
2
3 #include <afsconfig.h>
4 #include <afs/param.h>
5
6 RCSID("$Header$");
7
8 #if defined(AFS_OSF20_ENV) && !defined(AFS_DUX50_ENV) || defined(AFS_AIX32_ENV) || (defined(AFS_SUN55_ENV) && !defined(AFS_SUN56_ENV))
9 #include <sys/types.h>
10 #include <stdarg.h>
11 #include <stdio.h>
12 #include <ctype.h>
13 #include <netinet/in.h>
14 #include <netdb.h>
15 #if defined(AFS_AIX32_ENV) || defined(AFS_SUN55_ENV)
16 #include <sys/socket.h>
17 #endif
18
19 #define MAXPREC 100
20
21 /* Generate an ASCII representation of an integer <val>, as follows:
22  * <base> indicates the base to be used (2-36)
23  * <uc> is nonzero if letter digits should be uppercase
24  * <prec> is the minimum number of digits
25  * The resulting number is stored in <buf>, which must be long enough
26  * to receive it.  The minimum length is <prec> or ceil(log{base}(val)),
27  * whichever is larger, plus room for a trailing NUL.
28  */
29 static void mkint(char *buf, unsigned long val, int base, int uc, int prec)
30 {
31   int len = 0, dig, i;
32
33   while (val) {
34     dig = val % base;
35     val = (val - dig) / base;
36     if (dig < 10)  dig = dig + '0';
37     else if (uc) dig = dig + 'A' - 10;
38     else         dig = dig + 'a' - 10;
39     buf[len++] = dig;
40   }
41   while (len < prec) buf[len++] = '0';
42   for (i = 0; i < (len + 1) / 2; i++) {
43     dig = buf[i];
44     buf[i] = buf[len - i - 1];
45     buf[len - i - 1] = dig;
46   }
47   buf[len] = 0;
48 }
49
50
51 /* This function is a mostly-complete implementation of snprintf,
52  * with the following features:
53  *
54  *   - Actually obeys the length limit, which (unfortunately) many
55  *     implementations of snprintf do not.
56  *  
57  *   - Supports all the standard format specifiers for integers
58  *     (d, i, o, u, x, X), floating-point values (f, e, E, g, G),
59  *     and strings and characters (c, s, %), plus a few unusual
60  *     but useful ones described below.
61  *  
62  *   - Supports all the standard flags (-, 0, +, space, #).  These
63  *     flags are ignored if used when they are not appropriate.
64  *  
65  *   - Supports the standard size modifiers for short (h), long (h),
66  *     and double (L) arguments.  These modifiers are ignored if used
67  *     when they are not appropriate.
68  *  
69  *   - Supports minimum field width and precision, where appropriate,
70  *     including the use of '*' to specify a value given as an argument
71  *     instead of in the format string.  There is a maximum precision
72  *     of 100 digits.
73  *  
74  *   - At present, the 'p' specifier for printing pointers is not
75  *     implemented, because it is inherently non-portable and thus
76  *     can be implemented correctly only by the compiler's run-time
77  *     library.
78  *
79  *   - Floating-point specifier (%e, %f, %g) are implemented by
80  *     calling the standard sprintf, and thus may be unsafe.
81  *  
82  *   - The '%...$' notation is used primarily when the format string
83  *     is specified by the user, who knows but cannot change the order
84  *     of the arguments.  Such usage is inherently dangerous and
85  *     insecure; thus, it is not supported.
86  *  
87  * The custom format specifier '%I' is supported.  This specifier
88  * takes as its argument an unsigned long integer containing an
89  * IPv4 address in network byte order.  The address is rendered
90  * either as a hostname or as a dotted quad, as follows:
91  *  
92  *   - If precision is nonzero or unspecified, a hostname lookup
93  *     is attempted; if it is successful, the hostname is printed.
94  *     If the hostname lookup fails, the address is printed in
95  *     dotted-quad notation.
96  *  
97  *   - If precision is explicitly specified as 0, then the hostname
98  *     lookup is skipped, and dotted-quad notation is always used.
99  *  
100  *   - If a hostname is to be printed:
101  *     + The precision controls the maximum number of characters
102  *       printed, as with %s.
103  *     + If the '#' flag is specified, any letters in the hostname
104  *       will be forced to lower case before printing.
105  *     + If the '+' flag is specified, any letters in the hostname
106  *       will be forced to upper case before printing.  If both
107  *       '#' and '+' are given, the '+' flag will be ignored.
108  *     + The '0' and ' ' flags have no effect.
109  *  
110  *   - If a dotted quad is to be printed:
111  *     + The precision has no effect; dotted quads are always
112  *       7 to 12 characters in length, depending on the value
113  *       to be printed and the format flags used.
114  *     + If the '0' flag is given, each field (byte) of the address
115  *       will be padded with '0' on the left to three digits.
116  *     + If the ' ' flag is given, each field (byte) of the address
117  *       will be padded with spaces on the left to three digits.  If
118  *       both '0' and ' ' are given, the ' ' flag will be ignored.
119  *     + The '#' and '+' flags have no effect.
120  */
121 static void vsnprintf(char *p, unsigned int avail, char *fmt, va_list ap)
122 {
123   unsigned int width, precision, haveprec, len;
124   int ljust, plsign, spsign, altform, zfill;
125   int hflag, lflag, count, *countp, j;
126   char *x, *y, xbuf[MAXPREC + 21], fbuf[20];
127   struct hostent *he;
128   struct in_addr ia;
129   unsigned long UVAL;
130   long SVAL, *lcountp;
131   double FVAL;
132   short *hcountp;
133
134   count = 0;
135   avail--;
136   while (*fmt && avail) {
137     if (*fmt != '%') {
138       *p++ = *fmt++;
139       avail--;
140       count++;
141       continue;
142     }
143
144     /** Found a format specifier **/
145     ljust = plsign = spsign = altform = zfill = 0;
146     width = precision = haveprec = 0;
147     hflag = lflag = 0;
148     fmt++;
149
150     /* parse format flags */
151     while (*fmt) {
152       switch (*fmt) {
153         case '-': ljust   = 1; fmt++; continue;      /* left justify */
154         case '+': plsign  = 1; fmt++; continue;      /* use + or - */
155         case ' ': spsign  = 1; fmt++; continue;      /* use space or - */
156         case '#': altform = 1; fmt++; continue;      /* alternate form */
157         case '0': zfill   = 1; fmt++; continue;      /* pad with 0 */
158         default: break;
159       }
160       break;
161     }
162
163     /* parse minimum width */
164     if (*fmt == '*') {
165       width = va_arg(ap, int);
166       fmt++;
167     } else while (isdigit(*fmt)) {
168       width = (width * 10) + (*fmt - '0');
169       fmt++;
170     }
171
172     /* parse precision */
173     if (*fmt == '.') {
174       fmt++;
175       haveprec = 1;
176       if (*fmt == '*') {
177         precision = va_arg(ap, int);
178         fmt++;
179       } else while (isdigit(*fmt)) {
180         precision = (precision * 10) + (*fmt - '0');
181         fmt++;
182       }
183     }
184
185     /* parse size flags */
186     while (*fmt) {
187       switch (*fmt) {
188         case 'h': hflag   = 1; fmt++; continue;      /* short argument */
189         case 'l': lflag   = 1; fmt++; continue;      /* long argument */
190         default: break;
191       }
192       break;
193     }
194
195     /* parse format specifier */
196     if (!*fmt) break;
197     switch (*fmt++) {
198       case 'e':
199       case 'E':
200       case 'f':
201       case 'g':
202       case 'G':
203         FVAL = va_arg(ap, double);
204         sprintf(fbuf, "%%%s%s.*L%c", plsign ? "+" : (spsign ? " " : ""),
205                 altform ? "#" : "", fmt[-1]);
206         if (!haveprec) precision = 6;
207         if (precision > MAXPREC) precision = MAXPREC;
208         sprintf(xbuf, fbuf, precision, FVAL);
209         x = xbuf;
210         len = strlen(x);
211         break;
212
213       case 'i': 
214       case 'd': /* signed decimal integer */
215         if      (lflag) SVAL = va_arg(ap, long);
216         else if (hflag) SVAL = va_arg(ap, short);
217         else            SVAL = va_arg(ap, int);
218         UVAL = (SVAL < 0) ? -SVAL : SVAL;
219
220         if (SVAL < 0)    xbuf[0] = '-';
221         else if (plsign) xbuf[0] = '+';
222         else if (spsign) xbuf[0] = ' ';
223         else             xbuf[0] = 0;
224
225         if (!haveprec) {
226           if (zfill && !ljust) precision = width - !!xbuf[0];
227           else precision = 1;
228           if (precision < 1 + !!xbuf[0]) precision = 1 + !!xbuf[0];
229         }
230         if (precision > MAXPREC) precision = MAXPREC;
231
232         mkint(xbuf + 1, UVAL, 10, 0, precision);
233         x = xbuf + !xbuf[0];
234         len = strlen(x);
235         break;
236
237
238       case 'o': /* unsigned octal integer */
239         if      (lflag) UVAL = va_arg(ap, unsigned long);
240         else if (hflag) UVAL = va_arg(ap, unsigned short);
241         else            UVAL = va_arg(ap, unsigned int);
242
243         xbuf[0] = '0';
244
245         if (!haveprec) {
246           if (zfill && !ljust) precision = width;
247           else precision = 1;
248         }
249         if (precision > MAXPREC) precision = MAXPREC;
250
251         mkint(xbuf + 1, UVAL, 8, 0, precision);
252         x = xbuf + (xbuf[1] == '0' || !altform);
253         len = strlen(x);
254         break;
255
256       case 'u': /* unsigned decimal integer */
257         if      (lflag) UVAL = va_arg(ap, unsigned long);
258         else if (hflag) UVAL = va_arg(ap, unsigned short);
259         else            UVAL = va_arg(ap, unsigned int);
260
261         if (!haveprec) {
262           if (zfill && !ljust) precision = width;
263           else precision = 1;
264         }
265         if (precision > MAXPREC) precision = MAXPREC;
266
267         mkint(xbuf, UVAL, 10, 0, precision);
268         x = xbuf;
269         len = strlen(x);
270         break;
271
272       case 'x': 
273       case 'X': /* unsigned hexadecimal integer */
274         if      (lflag) UVAL = va_arg(ap, unsigned long);
275         else if (hflag) UVAL = va_arg(ap, unsigned short);
276         else            UVAL = va_arg(ap, unsigned int);
277
278         xbuf[0] = '0';
279         xbuf[1] = 'x';
280
281         if (!haveprec) {
282           if (zfill && !ljust) precision = width;
283           else precision = 1;
284         }
285         if (precision > MAXPREC) precision = MAXPREC;
286
287         mkint(xbuf + 2, UVAL, 16, 0, precision);
288         x = xbuf + ((altform && UVAL) ? 0 : 2);
289         len = strlen(x);
290         break;
291
292       case '%': /* literal % */
293         xbuf[0] = '%';
294         xbuf[1] = 0;
295         x = xbuf;
296         len = 1;
297         break;
298
299       case 'c': /* character */
300         xbuf[0] = va_arg(ap, int);
301         xbuf[1] = 0;
302         x = xbuf;
303         len = 1;
304         break;
305
306       case 's': /* string */
307         x = va_arg(ap, char *);
308         if (!x) x = "<null>";
309         len = strlen(x);
310         if (haveprec && precision < len) len = precision;
311         break;
312
313       case 'I': /* IP address:
314          * value is provided as a network-order unsigned long integer
315          * precision specifies max hostname length, as for %s
316          * if precision is explicitly 0, no hostname lookup is done
317          * if 0fill specified, IPaddr fields are 0-filled to 3 digits
318          * if spsign specified, IPaddr fields are space-filled to 3 digits
319          */
320         UVAL = va_arg(ap, unsigned long);
321         ia.s_addr = UVAL;
322         if (haveprec && !precision) he = 0;
323         else he = gethostbyaddr((char *)&ia, 4, AF_INET);
324         if (he) {
325           x = he->h_name;
326           len = strlen(x);
327           if (haveprec && precision < len) len = precision;
328           if (altform)
329             for (y = x; *y; y++) if (isupper(*y)) *y = tolower(*y);
330           else if (plsign)
331             for (y = x; *y; y++) if (islower(*y)) *y = toupper(*y);
332         } else {
333           UVAL = ntohl(UVAL);
334           if      (zfill)  x = "%03u.%03u.%03u.%03u";
335           else if (spsign) x = "%3u.%3u.%3u.%3u";
336           else             x = "%u.%u.%u.%u";
337           sprintf(xbuf, x,
338                   (UVAL & 0xff000000) >> 24, (UVAL & 0x00ff0000) >> 16,
339                   (UVAL & 0x0000ff00) >> 8,  (UVAL & 0x000000ff));
340           x = xbuf;
341           len = strlen(xbuf);
342         }
343         break;
344
345       case 'n': /* report count so far */
346         if (lflag) {
347           lcountp = va_arg(ap, long *);
348           *lcountp = count;
349         } else if (hflag) {
350           hcountp = va_arg(ap, short *);
351           *hcountp = count;
352         } else {
353           countp = va_arg(ap, int *);
354           *countp = count;
355         }
356         continue;
357
358       default: /* unknown specifier */
359         continue;
360     }
361
362     /* render the results */
363     if (len > avail)   len = avail;
364     if (!width)        width = len;
365     if (width > avail) width = avail;
366     j = width - len;
367     if (j > 0) {
368       avail -= j;
369       count += j;
370     }
371
372     if (!ljust) while (j-- > 0) *p++ = ' ';
373
374     strncpy(p, x, len);
375     avail -= len;
376     count += len;
377     p += len;
378
379     if (ljust) while (j-- > 0) *p++ = ' ';
380   }
381   *p = 0;
382 }
383
384
385 void snprintf(char *p, unsigned int avail, char *fmt, ...)
386 {
387   va_list ap;
388
389   va_start(ap, fmt);
390   vsnprintf(p, avail, fmt, ap);
391   va_end(ap);
392 }
393 #endif /* AFS_OSF20_ENV || AFS_AIX32_ENV */