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: stable/11/sys/kern/subr_scanf.c 351760 2019-09-03 16:38:52Z mav $");
39
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 */
89typedef u_quad_t (*ccfntype)(const char *, char **, int);
90
91static const u_char *__sccl(char *, const u_char *);
92
93int
94sscanf(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
105int
106vsscanf(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		 */
152again:		c = *fmt++;
153		switch (c) {
154		case '%':
155literal:
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
311		case CT_CHAR:
312			/* scan arbitrary characters (sets NOSKIP) */
313			if (width == 0)
314				width = 1;
315			if (flags & SUPPRESS) {
316				size_t sum = 0;
317				for (;;) {
318					if ((n = inr) < width) {
319						sum += n;
320						width -= n;
321						inp += n;
322						if (sum == 0)
323							goto input_failure;
324						break;
325					} else {
326						sum += width;
327						inr -= width;
328						inp += width;
329						break;
330					}
331				}
332				nread += sum;
333			} else {
334				bcopy(inp, va_arg(ap, char *), width);
335				inr -= width;
336				inp += width;
337				nread += width;
338				nassigned++;
339			}
340			nconversions++;
341			break;
342
343		case CT_CCL:
344			/* scan a (nonempty) character class (sets NOSKIP) */
345			if (width == 0)
346				width = (size_t)~0;	/* `infinity' */
347			/* take only those things in the class */
348			if (flags & SUPPRESS) {
349				n = 0;
350				while (ccltab[(unsigned char)*inp]) {
351					n++, inr--, inp++;
352					if (--width == 0)
353						break;
354					if (inr <= 0) {
355						if (n == 0)
356							goto input_failure;
357						break;
358					}
359				}
360				if (n == 0)
361					goto match_failure;
362			} else {
363				p0 = p = va_arg(ap, char *);
364				while (ccltab[(unsigned char)*inp]) {
365					inr--;
366					*p++ = *inp++;
367					if (--width == 0)
368						break;
369					if (inr <= 0) {
370						if (p == p0)
371							goto input_failure;
372						break;
373					}
374				}
375				n = p - p0;
376				if (n == 0)
377					goto match_failure;
378				*p = 0;
379				nassigned++;
380			}
381			nread += n;
382			nconversions++;
383			break;
384
385		case CT_STRING:
386			/* like CCL, but zero-length string OK, & no NOSKIP */
387			if (width == 0)
388				width = (size_t)~0;
389			if (flags & SUPPRESS) {
390				n = 0;
391				while (!isspace(*inp)) {
392					n++, inr--, inp++;
393					if (--width == 0)
394						break;
395					if (inr <= 0)
396						break;
397				}
398				nread += n;
399			} else {
400				p0 = p = va_arg(ap, char *);
401				while (!isspace(*inp)) {
402					inr--;
403					*p++ = *inp++;
404					if (--width == 0)
405						break;
406					if (inr <= 0)
407						break;
408				}
409				*p = 0;
410				nread += p - p0;
411				nassigned++;
412			}
413			nconversions++;
414			continue;
415
416		case CT_INT:
417			/* scan an integer as if by strtoq/strtouq */
418#ifdef hardway
419			if (width == 0 || width > sizeof(buf) - 1)
420				width = sizeof(buf) - 1;
421#else
422			/* size_t is unsigned, hence this optimisation */
423			if (--width > sizeof(buf) - 2)
424				width = sizeof(buf) - 2;
425			width++;
426#endif
427			flags |= SIGNOK | NDIGITS | NZDIGITS;
428			for (p = buf; width; width--) {
429				c = *inp;
430				/*
431				 * Switch on the character; `goto ok'
432				 * if we accept it as a part of number.
433				 */
434				switch (c) {
435
436				/*
437				 * The digit 0 is always legal, but is
438				 * special.  For %i conversions, if no
439				 * digits (zero or nonzero) have been
440				 * scanned (only signs), we will have
441				 * base==0.  In that case, we should set
442				 * it to 8 and enable 0x prefixing.
443				 * Also, if we have not scanned zero digits
444				 * before this, do not turn off prefixing
445				 * (someone else will turn it off if we
446				 * have scanned any nonzero digits).
447				 */
448				case '0':
449					if (base == 0) {
450						base = 8;
451						flags |= PFXOK;
452					}
453					if (flags & NZDIGITS)
454					    flags &= ~(SIGNOK|NZDIGITS|NDIGITS);
455					else
456					    flags &= ~(SIGNOK|PFXOK|NDIGITS);
457					goto ok;
458
459				/* 1 through 7 always legal */
460				case '1': case '2': case '3':
461				case '4': case '5': case '6': case '7':
462					base = basefix[base];
463					flags &= ~(SIGNOK | PFXOK | NDIGITS);
464					goto ok;
465
466				/* digits 8 and 9 ok iff decimal or hex */
467				case '8': case '9':
468					base = basefix[base];
469					if (base <= 8)
470						break;	/* not legal here */
471					flags &= ~(SIGNOK | PFXOK | NDIGITS);
472					goto ok;
473
474				/* letters ok iff hex */
475				case 'A': case 'B': case 'C':
476				case 'D': case 'E': case 'F':
477				case 'a': case 'b': case 'c':
478				case 'd': case 'e': case 'f':
479					/* no need to fix base here */
480					if (base <= 10)
481						break;	/* not legal here */
482					flags &= ~(SIGNOK | PFXOK | NDIGITS);
483					goto ok;
484
485				/* sign ok only as first character */
486				case '+': case '-':
487					if (flags & SIGNOK) {
488						flags &= ~SIGNOK;
489						goto ok;
490					}
491					break;
492
493				/* x ok iff flag still set & 2nd char */
494				case 'x': case 'X':
495					if (flags & PFXOK && p == buf + 1) {
496						base = 16;	/* if %i */
497						flags &= ~PFXOK;
498						goto ok;
499					}
500					break;
501				}
502
503				/*
504				 * If we got here, c is not a legal character
505				 * for a number.  Stop accumulating digits.
506				 */
507				break;
508		ok:
509				/*
510				 * c is legal: store it and look at the next.
511				 */
512				*p++ = c;
513				if (--inr > 0)
514					inp++;
515				else
516					break;		/* end of input */
517			}
518			/*
519			 * If we had only a sign, it is no good; push
520			 * back the sign.  If the number ends in `x',
521			 * it was [sign] '0' 'x', so push back the x
522			 * and treat it as [sign] '0'.
523			 */
524			if (flags & NDIGITS) {
525				if (p > buf) {
526					inp--;
527					inr++;
528				}
529				goto match_failure;
530			}
531			c = ((u_char *)p)[-1];
532			if (c == 'x' || c == 'X') {
533				--p;
534				inp--;
535				inr++;
536			}
537			if ((flags & SUPPRESS) == 0) {
538				u_quad_t res;
539
540				*p = 0;
541				res = (*ccfn)(buf, (char **)NULL, base);
542				if (flags & POINTER)
543					*va_arg(ap, void **) =
544						(void *)(uintptr_t)res;
545				else if (flags & SHORTSHORT)
546					*va_arg(ap, char *) = res;
547				else if (flags & SHORT)
548					*va_arg(ap, short *) = res;
549				else if (flags & LONG)
550					*va_arg(ap, long *) = res;
551				else if (flags & QUAD)
552					*va_arg(ap, quad_t *) = res;
553				else if (flags & INTMAXT)
554					*va_arg(ap, intmax_t *) = res;
555				else if (flags & PTRDIFFT)
556					*va_arg(ap, ptrdiff_t *) = res;
557				else if (flags & SIZET)
558					*va_arg(ap, size_t *) = res;
559				else
560					*va_arg(ap, int *) = res;
561				nassigned++;
562			}
563			nread += p - buf;
564			nconversions++;
565			break;
566
567		}
568	}
569input_failure:
570	return (nconversions != 0 ? nassigned : -1);
571match_failure:
572	return (nassigned);
573}
574
575/*
576 * Fill in the given table from the scanset at the given format
577 * (just after `[').  Return a pointer to the character past the
578 * closing `]'.  The table has a 1 wherever characters should be
579 * considered part of the scanset.
580 */
581static const u_char *
582__sccl(char *tab, const u_char *fmt)
583{
584	int c, n, v;
585
586	/* first `clear' the whole table */
587	c = *fmt++;		/* first char hat => negated scanset */
588	if (c == '^') {
589		v = 1;		/* default => accept */
590		c = *fmt++;	/* get new first char */
591	} else
592		v = 0;		/* default => reject */
593
594	/* XXX: Will not work if sizeof(tab*) > sizeof(char) */
595	for (n = 0; n < 256; n++)
596		     tab[n] = v;	/* memset(tab, v, 256) */
597
598	if (c == 0)
599		return (fmt - 1);/* format ended before closing ] */
600
601	/*
602	 * Now set the entries corresponding to the actual scanset
603	 * to the opposite of the above.
604	 *
605	 * The first character may be ']' (or '-') without being special;
606	 * the last character may be '-'.
607	 */
608	v = 1 - v;
609	for (;;) {
610		tab[c] = v;		/* take character c */
611doswitch:
612		n = *fmt++;		/* and examine the next */
613		switch (n) {
614
615		case 0:			/* format ended too soon */
616			return (fmt - 1);
617
618		case '-':
619			/*
620			 * A scanset of the form
621			 *	[01+-]
622			 * is defined as `the digit 0, the digit 1,
623			 * the character +, the character -', but
624			 * the effect of a scanset such as
625			 *	[a-zA-Z0-9]
626			 * is implementation defined.  The V7 Unix
627			 * scanf treats `a-z' as `the letters a through
628			 * z', but treats `a-a' as `the letter a, the
629			 * character -, and the letter a'.
630			 *
631			 * For compatibility, the `-' is not considered
632			 * to define a range if the character following
633			 * it is either a close bracket (required by ANSI)
634			 * or is not numerically greater than the character
635			 * we just stored in the table (c).
636			 */
637			n = *fmt;
638			if (n == ']' || n < c) {
639				c = '-';
640				break;	/* resume the for(;;) */
641			}
642			fmt++;
643			/* fill in the range */
644			do {
645			    tab[++c] = v;
646			} while (c < n);
647			c = n;
648			/*
649			 * Alas, the V7 Unix scanf also treats formats
650			 * such as [a-c-e] as `the letters a through e'.
651			 * This too is permitted by the standard....
652			 */
653			goto doswitch;
654			break;
655
656		case ']':		/* end of scanset */
657			return (fmt);
658
659		default:		/* just another character */
660			c = n;
661			break;
662		}
663	}
664	/* NOTREACHED */
665}
666
667