xref: /illumos-gate/usr/src/lib/libshare/common/parser.c (revision 68ac2337c38c8af06edcf32a72e42de36ec72a9d)
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 2006 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <stdio.h>
30 #include <ctype.h>
31 
32 #define	TK_INIT		0
33 #define	TK_TOKEN	1
34 #define	TK_SKIPWHITE	2
35 #define	TK_QUOTED	3
36 
37 /*
38  * assumes quoted strings are delimited by white space (i.e sp
39  * "string" sp). Backslash can be used to quote a quote mark.
40  * quoted strings will have the quotes stripped.
41  */
42 
43 char *
44 get_token(char *string)
45 {
46 	static char *orig = NULL;
47 	static char *curp;
48 	char *ret;
49 	int state = TK_INIT;
50 	int c;
51 	int quotechar;
52 
53 	if (string != orig || string == NULL) {
54 		orig = string;
55 		curp = string;
56 		if (string == NULL) {
57 			return (NULL);
58 		}
59 	}
60 	ret = curp;
61 	while ((c = *curp) != '\0') {
62 		switch (state) {
63 		case TK_SKIPWHITE:
64 		case TK_INIT:
65 			if (isspace(c)) {
66 				while (*curp && isspace(*curp))
67 					curp++;
68 				ret = curp;
69 			}
70 			if (c == '"' || c == '\'') {
71 				state = TK_QUOTED;
72 				curp++;
73 				ret = curp;
74 				quotechar = c; /* want to match for close */
75 			} else {
76 				state = TK_TOKEN;
77 			}
78 			break;
79 		case TK_TOKEN:
80 			switch (c) {
81 			case '\\':
82 				curp++;
83 				if (*curp) {
84 					curp++;
85 					break;
86 				} else {
87 					return (ret);
88 				}
89 				break;
90 			default:
91 				if (*curp == '\0' || isspace(c)) {
92 					*curp++ = '\0';
93 					return (ret);
94 				}
95 				curp++;
96 				break;
97 			}
98 			break;
99 		case TK_QUOTED:
100 			switch (c) {
101 			case '\\':
102 				curp++;
103 				if (*curp) {
104 					curp++;
105 					break;
106 				}
107 				curp++;
108 				break;
109 			default:
110 				if (c == '\0' || c == quotechar) {
111 					*curp++ = '\0';
112 					return (ret);
113 				}
114 				curp++;
115 				break;
116 			}
117 			break;
118 		}
119 	}
120 	return (NULL);
121 }
122