xref: /freebsd/sys/kern/subr_scanf.c (revision 39beb93c)
1 /*-
2  * Copyright (c) 1990, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Chris Torek.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    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.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * From: Id: vfscanf.c,v 1.13 1998/09/25 12:20:27 obrien Exp
33  * From: static char sccsid[] = "@(#)strtol.c	8.1 (Berkeley) 6/4/93";
34  * From: static char sccsid[] = "@(#)strtoul.c	8.1 (Berkeley) 6/4/93";
35  */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/ctype.h>
43 #include <sys/limits.h>
44 
45 /*
46  * Note that stdarg.h and the ANSI style va_start macro is used for both
47  * ANSI and traditional C compilers.
48  */
49 #include <machine/stdarg.h>
50 
51 #define	BUF		32 	/* Maximum length of numeric string. */
52 
53 /*
54  * Flags used during conversion.
55  */
56 #define	LONG		0x01	/* l: long or double */
57 #define	SHORT		0x04	/* h: short */
58 #define	SUPPRESS	0x08	/* suppress assignment */
59 #define	POINTER		0x10	/* weird %p pointer (`fake hex') */
60 #define	NOSKIP		0x20	/* do not skip blanks */
61 #define	QUAD		0x400
62 
63 /*
64  * The following are used in numeric conversions only:
65  * SIGNOK, NDIGITS, DPTOK, and EXPOK are for floating point;
66  * SIGNOK, NDIGITS, PFXOK, and NZDIGITS are for integral.
67  */
68 #define	SIGNOK		0x40	/* +/- is (still) legal */
69 #define	NDIGITS		0x80	/* no digits detected */
70 
71 #define	DPTOK		0x100	/* (float) decimal point is still legal */
72 #define	EXPOK		0x200	/* (float) exponent (e+3, etc) still legal */
73 
74 #define	PFXOK		0x100	/* 0x prefix is (still) legal */
75 #define	NZDIGITS	0x200	/* no zero digits detected */
76 
77 /*
78  * Conversion types.
79  */
80 #define	CT_CHAR		0	/* %c conversion */
81 #define	CT_CCL		1	/* %[...] conversion */
82 #define	CT_STRING	2	/* %s conversion */
83 #define	CT_INT		3	/* integer, i.e., strtoq or strtouq */
84 typedef u_quad_t (*ccfntype)(const char *, char **, int);
85 
86 static const u_char *__sccl(char *, const u_char *);
87 
88 int
89 sscanf(const char *ibuf, const char *fmt, ...)
90 {
91 	va_list ap;
92 	int ret;
93 
94 	va_start(ap, fmt);
95 	ret = vsscanf(ibuf, fmt, ap);
96 	va_end(ap);
97 	return(ret);
98 }
99 
100 int
101 vsscanf(const char *inp, char const *fmt0, va_list ap)
102 {
103 	int inr;
104 	const u_char *fmt = (const u_char *)fmt0;
105 	int c;			/* character from format, or conversion */
106 	size_t width;		/* field width, or 0 */
107 	char *p;		/* points into all kinds of strings */
108 	int n;			/* handy integer */
109 	int flags;		/* flags as defined above */
110 	char *p0;		/* saves original value of p when necessary */
111 	int nassigned;		/* number of fields assigned */
112 	int nconversions;	/* number of conversions */
113 	int nread;		/* number of characters consumed from fp */
114 	int base;		/* base argument to strtoq/strtouq */
115 	ccfntype ccfn;		/* conversion function (strtoq/strtouq) */
116 	char ccltab[256];	/* character class table for %[...] */
117 	char buf[BUF];		/* buffer for numeric conversions */
118 
119 	/* `basefix' is used to avoid `if' tests in the integer scanner */
120 	static short basefix[17] =
121 		{ 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
122 
123 	inr = strlen(inp);
124 
125 	nassigned = 0;
126 	nconversions = 0;
127 	nread = 0;
128 	base = 0;		/* XXX just to keep gcc happy */
129 	ccfn = NULL;		/* XXX just to keep gcc happy */
130 	for (;;) {
131 		c = *fmt++;
132 		if (c == 0)
133 			return (nassigned);
134 		if (isspace(c)) {
135 			while (inr > 0 && isspace(*inp))
136 				nread++, inr--, inp++;
137 			continue;
138 		}
139 		if (c != '%')
140 			goto literal;
141 		width = 0;
142 		flags = 0;
143 		/*
144 		 * switch on the format.  continue if done;
145 		 * break once format type is derived.
146 		 */
147 again:		c = *fmt++;
148 		switch (c) {
149 		case '%':
150 literal:
151 			if (inr <= 0)
152 				goto input_failure;
153 			if (*inp != c)
154 				goto match_failure;
155 			inr--, inp++;
156 			nread++;
157 			continue;
158 
159 		case '*':
160 			flags |= SUPPRESS;
161 			goto again;
162 		case 'l':
163 			flags |= LONG;
164 			goto again;
165 		case 'q':
166 			flags |= QUAD;
167 			goto again;
168 		case 'h':
169 			flags |= SHORT;
170 			goto again;
171 
172 		case '0': case '1': case '2': case '3': case '4':
173 		case '5': case '6': case '7': case '8': case '9':
174 			width = width * 10 + c - '0';
175 			goto again;
176 
177 		/*
178 		 * Conversions.
179 		 *
180 		 */
181 		case 'd':
182 			c = CT_INT;
183 			ccfn = (ccfntype)strtoq;
184 			base = 10;
185 			break;
186 
187 		case 'i':
188 			c = CT_INT;
189 			ccfn = (ccfntype)strtoq;
190 			base = 0;
191 			break;
192 
193 		case 'o':
194 			c = CT_INT;
195 			ccfn = strtouq;
196 			base = 8;
197 			break;
198 
199 		case 'u':
200 			c = CT_INT;
201 			ccfn = strtouq;
202 			base = 10;
203 			break;
204 
205 		case 'x':
206 			flags |= PFXOK;	/* enable 0x prefixing */
207 			c = CT_INT;
208 			ccfn = strtouq;
209 			base = 16;
210 			break;
211 
212 		case 's':
213 			c = CT_STRING;
214 			break;
215 
216 		case '[':
217 			fmt = __sccl(ccltab, fmt);
218 			flags |= NOSKIP;
219 			c = CT_CCL;
220 			break;
221 
222 		case 'c':
223 			flags |= NOSKIP;
224 			c = CT_CHAR;
225 			break;
226 
227 		case 'p':	/* pointer format is like hex */
228 			flags |= POINTER | PFXOK;
229 			c = CT_INT;
230 			ccfn = strtouq;
231 			base = 16;
232 			break;
233 
234 		case 'n':
235 			nconversions++;
236 			if (flags & SUPPRESS)	/* ??? */
237 				continue;
238 			if (flags & SHORT)
239 				*va_arg(ap, short *) = nread;
240 			else if (flags & LONG)
241 				*va_arg(ap, long *) = nread;
242 			else if (flags & QUAD)
243 				*va_arg(ap, quad_t *) = nread;
244 			else
245 				*va_arg(ap, int *) = nread;
246 			continue;
247 		}
248 
249 		/*
250 		 * We have a conversion that requires input.
251 		 */
252 		if (inr <= 0)
253 			goto input_failure;
254 
255 		/*
256 		 * Consume leading white space, except for formats
257 		 * that suppress this.
258 		 */
259 		if ((flags & NOSKIP) == 0) {
260 			while (isspace(*inp)) {
261 				nread++;
262 				if (--inr > 0)
263 					inp++;
264 				else
265 					goto input_failure;
266 			}
267 			/*
268 			 * Note that there is at least one character in
269 			 * the buffer, so conversions that do not set NOSKIP
270 			 * can no longer result in an input failure.
271 			 */
272 		}
273 
274 		/*
275 		 * Do the conversion.
276 		 */
277 		switch (c) {
278 
279 		case CT_CHAR:
280 			/* scan arbitrary characters (sets NOSKIP) */
281 			if (width == 0)
282 				width = 1;
283 			if (flags & SUPPRESS) {
284 				size_t sum = 0;
285 				for (;;) {
286 					if ((n = inr) < width) {
287 						sum += n;
288 						width -= n;
289 						inp += n;
290 						if (sum == 0)
291 							goto input_failure;
292 						break;
293 					} else {
294 						sum += width;
295 						inr -= width;
296 						inp += width;
297 						break;
298 					}
299 				}
300 				nread += sum;
301 			} else {
302 				bcopy(inp, va_arg(ap, char *), width);
303 				inr -= width;
304 				inp += width;
305 				nread += width;
306 				nassigned++;
307 			}
308 			nconversions++;
309 			break;
310 
311 		case CT_CCL:
312 			/* scan a (nonempty) character class (sets NOSKIP) */
313 			if (width == 0)
314 				width = (size_t)~0;	/* `infinity' */
315 			/* take only those things in the class */
316 			if (flags & SUPPRESS) {
317 				n = 0;
318 				while (ccltab[(unsigned char)*inp]) {
319 					n++, inr--, inp++;
320 					if (--width == 0)
321 						break;
322 					if (inr <= 0) {
323 						if (n == 0)
324 							goto input_failure;
325 						break;
326 					}
327 				}
328 				if (n == 0)
329 					goto match_failure;
330 			} else {
331 				p0 = p = va_arg(ap, char *);
332 				while (ccltab[(unsigned char)*inp]) {
333 					inr--;
334 					*p++ = *inp++;
335 					if (--width == 0)
336 						break;
337 					if (inr <= 0) {
338 						if (p == p0)
339 							goto input_failure;
340 						break;
341 					}
342 				}
343 				n = p - p0;
344 				if (n == 0)
345 					goto match_failure;
346 				*p = 0;
347 				nassigned++;
348 			}
349 			nread += n;
350 			nconversions++;
351 			break;
352 
353 		case CT_STRING:
354 			/* like CCL, but zero-length string OK, & no NOSKIP */
355 			if (width == 0)
356 				width = (size_t)~0;
357 			if (flags & SUPPRESS) {
358 				n = 0;
359 				while (!isspace(*inp)) {
360 					n++, inr--, inp++;
361 					if (--width == 0)
362 						break;
363 					if (inr <= 0)
364 						break;
365 				}
366 				nread += n;
367 			} else {
368 				p0 = p = va_arg(ap, char *);
369 				while (!isspace(*inp)) {
370 					inr--;
371 					*p++ = *inp++;
372 					if (--width == 0)
373 						break;
374 					if (inr <= 0)
375 						break;
376 				}
377 				*p = 0;
378 				nread += p - p0;
379 				nassigned++;
380 			}
381 			nconversions++;
382 			continue;
383 
384 		case CT_INT:
385 			/* scan an integer as if by strtoq/strtouq */
386 #ifdef hardway
387 			if (width == 0 || width > sizeof(buf) - 1)
388 				width = sizeof(buf) - 1;
389 #else
390 			/* size_t is unsigned, hence this optimisation */
391 			if (--width > sizeof(buf) - 2)
392 				width = sizeof(buf) - 2;
393 			width++;
394 #endif
395 			flags |= SIGNOK | NDIGITS | NZDIGITS;
396 			for (p = buf; width; width--) {
397 				c = *inp;
398 				/*
399 				 * Switch on the character; `goto ok'
400 				 * if we accept it as a part of number.
401 				 */
402 				switch (c) {
403 
404 				/*
405 				 * The digit 0 is always legal, but is
406 				 * special.  For %i conversions, if no
407 				 * digits (zero or nonzero) have been
408 				 * scanned (only signs), we will have
409 				 * base==0.  In that case, we should set
410 				 * it to 8 and enable 0x prefixing.
411 				 * Also, if we have not scanned zero digits
412 				 * before this, do not turn off prefixing
413 				 * (someone else will turn it off if we
414 				 * have scanned any nonzero digits).
415 				 */
416 				case '0':
417 					if (base == 0) {
418 						base = 8;
419 						flags |= PFXOK;
420 					}
421 					if (flags & NZDIGITS)
422 					    flags &= ~(SIGNOK|NZDIGITS|NDIGITS);
423 					else
424 					    flags &= ~(SIGNOK|PFXOK|NDIGITS);
425 					goto ok;
426 
427 				/* 1 through 7 always legal */
428 				case '1': case '2': case '3':
429 				case '4': case '5': case '6': case '7':
430 					base = basefix[base];
431 					flags &= ~(SIGNOK | PFXOK | NDIGITS);
432 					goto ok;
433 
434 				/* digits 8 and 9 ok iff decimal or hex */
435 				case '8': case '9':
436 					base = basefix[base];
437 					if (base <= 8)
438 						break;	/* not legal here */
439 					flags &= ~(SIGNOK | PFXOK | NDIGITS);
440 					goto ok;
441 
442 				/* letters ok iff hex */
443 				case 'A': case 'B': case 'C':
444 				case 'D': case 'E': case 'F':
445 				case 'a': case 'b': case 'c':
446 				case 'd': case 'e': case 'f':
447 					/* no need to fix base here */
448 					if (base <= 10)
449 						break;	/* not legal here */
450 					flags &= ~(SIGNOK | PFXOK | NDIGITS);
451 					goto ok;
452 
453 				/* sign ok only as first character */
454 				case '+': case '-':
455 					if (flags & SIGNOK) {
456 						flags &= ~SIGNOK;
457 						goto ok;
458 					}
459 					break;
460 
461 				/* x ok iff flag still set & 2nd char */
462 				case 'x': case 'X':
463 					if (flags & PFXOK && p == buf + 1) {
464 						base = 16;	/* if %i */
465 						flags &= ~PFXOK;
466 						goto ok;
467 					}
468 					break;
469 				}
470 
471 				/*
472 				 * If we got here, c is not a legal character
473 				 * for a number.  Stop accumulating digits.
474 				 */
475 				break;
476 		ok:
477 				/*
478 				 * c is legal: store it and look at the next.
479 				 */
480 				*p++ = c;
481 				if (--inr > 0)
482 					inp++;
483 				else
484 					break;		/* end of input */
485 			}
486 			/*
487 			 * If we had only a sign, it is no good; push
488 			 * back the sign.  If the number ends in `x',
489 			 * it was [sign] '0' 'x', so push back the x
490 			 * and treat it as [sign] '0'.
491 			 */
492 			if (flags & NDIGITS) {
493 				if (p > buf) {
494 					inp--;
495 					inr++;
496 				}
497 				goto match_failure;
498 			}
499 			c = ((u_char *)p)[-1];
500 			if (c == 'x' || c == 'X') {
501 				--p;
502 				inp--;
503 				inr++;
504 			}
505 			if ((flags & SUPPRESS) == 0) {
506 				u_quad_t res;
507 
508 				*p = 0;
509 				res = (*ccfn)(buf, (char **)NULL, base);
510 				if (flags & POINTER)
511 					*va_arg(ap, void **) =
512 						(void *)(uintptr_t)res;
513 				else if (flags & SHORT)
514 					*va_arg(ap, short *) = res;
515 				else if (flags & LONG)
516 					*va_arg(ap, long *) = res;
517 				else if (flags & QUAD)
518 					*va_arg(ap, quad_t *) = res;
519 				else
520 					*va_arg(ap, int *) = res;
521 				nassigned++;
522 			}
523 			nread += p - buf;
524 			nconversions++;
525 			break;
526 
527 		}
528 	}
529 input_failure:
530 	return (nconversions != 0 ? nassigned : -1);
531 match_failure:
532 	return (nassigned);
533 }
534 
535 /*
536  * Fill in the given table from the scanset at the given format
537  * (just after `[').  Return a pointer to the character past the
538  * closing `]'.  The table has a 1 wherever characters should be
539  * considered part of the scanset.
540  */
541 static const u_char *
542 __sccl(char *tab, const u_char *fmt)
543 {
544 	int c, n, v;
545 
546 	/* first `clear' the whole table */
547 	c = *fmt++;		/* first char hat => negated scanset */
548 	if (c == '^') {
549 		v = 1;		/* default => accept */
550 		c = *fmt++;	/* get new first char */
551 	} else
552 		v = 0;		/* default => reject */
553 
554 	/* XXX: Will not work if sizeof(tab*) > sizeof(char) */
555 	for (n = 0; n < 256; n++)
556 		     tab[n] = v;	/* memset(tab, v, 256) */
557 
558 	if (c == 0)
559 		return (fmt - 1);/* format ended before closing ] */
560 
561 	/*
562 	 * Now set the entries corresponding to the actual scanset
563 	 * to the opposite of the above.
564 	 *
565 	 * The first character may be ']' (or '-') without being special;
566 	 * the last character may be '-'.
567 	 */
568 	v = 1 - v;
569 	for (;;) {
570 		tab[c] = v;		/* take character c */
571 doswitch:
572 		n = *fmt++;		/* and examine the next */
573 		switch (n) {
574 
575 		case 0:			/* format ended too soon */
576 			return (fmt - 1);
577 
578 		case '-':
579 			/*
580 			 * A scanset of the form
581 			 *	[01+-]
582 			 * is defined as `the digit 0, the digit 1,
583 			 * the character +, the character -', but
584 			 * the effect of a scanset such as
585 			 *	[a-zA-Z0-9]
586 			 * is implementation defined.  The V7 Unix
587 			 * scanf treats `a-z' as `the letters a through
588 			 * z', but treats `a-a' as `the letter a, the
589 			 * character -, and the letter a'.
590 			 *
591 			 * For compatibility, the `-' is not considerd
592 			 * to define a range if the character following
593 			 * it is either a close bracket (required by ANSI)
594 			 * or is not numerically greater than the character
595 			 * we just stored in the table (c).
596 			 */
597 			n = *fmt;
598 			if (n == ']' || n < c) {
599 				c = '-';
600 				break;	/* resume the for(;;) */
601 			}
602 			fmt++;
603 			/* fill in the range */
604 			do {
605 			    tab[++c] = v;
606 			} while (c < n);
607 			c = n;
608 			/*
609 			 * Alas, the V7 Unix scanf also treats formats
610 			 * such as [a-c-e] as `the letters a through e'.
611 			 * This too is permitted by the standard....
612 			 */
613 			goto doswitch;
614 			break;
615 
616 		case ']':		/* end of scanset */
617 			return (fmt);
618 
619 		default:		/* just another character */
620 			c = n;
621 			break;
622 		}
623 	}
624 	/* NOTREACHED */
625 }
626 
627