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