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