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