xref: /f-stack/tools/libutil/fparseln.c (revision ebf5cedb)
1 /*	$NetBSD: fparseln.c,v 1.7 2007/03/08 19:57:53 drochner Exp $	*/
2 
3 /*
4  * Copyright (c) 1997 Christos Zoulas.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. All advertising materials mentioning features or use of this software
15  *    must display the following acknowledgement:
16  *	This product includes software developed by Christos Zoulas.
17  * 4. The name of the author may not be used to endorse or promote products
18  *    derived from this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
21  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
24  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 #include <sys/types.h>
36 #include <assert.h>
37 #include <errno.h>
38 #include <stdio.h>
39 #include <string.h>
40 #include <stdlib.h>
41 #include <libutil.h>
42 
43 static int isescaped(const char *, const char *, int);
44 
45 /* isescaped():
46  *	Return true if the character in *p that belongs to a string
47  *	that starts in *sp, is escaped by the escape character esc.
48  */
49 static int
50 isescaped(const char *sp, const char *p, int esc)
51 {
52 	const char     *cp;
53 	size_t		ne;
54 
55 #if 0
56 	_DIAGASSERT(sp != NULL);
57 	_DIAGASSERT(p != NULL);
58 #endif
59 
60 	/* No escape character */
61 	if (esc == '\0')
62 		return 0;
63 
64 	/* Count the number of escape characters that precede ours */
65 	for (ne = 0, cp = p; --cp >= sp && *cp == esc; ne++)
66 		continue;
67 
68 	/* Return true if odd number of escape characters */
69 	return (ne & 1) != 0;
70 }
71 
72 
73 /* fparseln():
74  *	Read a line from a file parsing continuations ending in \
75  *	and eliminating trailing newlines, or comments starting with
76  *	the comment char.
77  */
78 char *
79 fparseln(FILE *fp, size_t *size, size_t *lineno, const char str[3], int flags)
80 {
81 	static const char dstr[3] = { '\\', '\\', '#' };
82 
83 	size_t	s, len;
84 	char   *buf;
85 	char   *ptr, *cp;
86 	int	cnt;
87 	char	esc, con, nl, com;
88 #ifdef FSTACK
89 	#define MAXLINELEN 4096
90 	char fbuf[MAXLINELEN];
91 #endif
92 
93 #if 0
94 	_DIAGASSERT(fp != NULL);
95 #endif
96 
97 	len = 0;
98 	buf = NULL;
99 	cnt = 1;
100 
101 	if (str == NULL)
102 		str = dstr;
103 
104 	esc = str[0];
105 	con = str[1];
106 	com = str[2];
107 	/*
108 	 * XXX: it would be cool to be able to specify the newline character,
109 	 * but unfortunately, fgetln does not let us
110 	 */
111 	nl  = '\n';
112 
113 	while (cnt) {
114 		cnt = 0;
115 
116 		if (lineno)
117 			(*lineno)++;
118 
119 #ifndef FSTACK
120 		if ((ptr = fgetln(fp, &s)) == NULL)
121 			break;
122 #else
123 		if (fgets(fbuf, MAXLINELEN, fp) == NULL)
124 			break;
125 		fbuf[strcspn(fbuf, "\n")] = '\0';
126 		ptr = fbuf;
127 #endif
128 
129 		if (s && com) {		/* Check and eliminate comments */
130 			for (cp = ptr; cp < ptr + s; cp++)
131 				if (*cp == com && !isescaped(ptr, cp, esc)) {
132 					s = cp - ptr;
133 					cnt = s == 0 && buf == NULL;
134 					break;
135 				}
136 		}
137 
138 		if (s && nl) { 		/* Check and eliminate newlines */
139 			cp = &ptr[s - 1];
140 
141 			if (*cp == nl)
142 				s--;	/* forget newline */
143 		}
144 
145 		if (s && con) {		/* Check and eliminate continuations */
146 			cp = &ptr[s - 1];
147 
148 			if (*cp == con && !isescaped(ptr, cp, esc)) {
149 				s--;	/* forget continuation char */
150 				cnt = 1;
151 			}
152 		}
153 
154 		if (s == 0) {
155 			/*
156 			 * nothing to add, skip realloc except in case
157 			 * we need a minimal buf to return an empty line
158 			 */
159 			if (cnt || buf != NULL)
160 				continue;
161 		}
162 
163 		if ((cp = realloc(buf, len + s + 1)) == NULL) {
164 			free(buf);
165 			return NULL;
166 		}
167 		buf = cp;
168 
169 		(void) memcpy(buf + len, ptr, s);
170 		len += s;
171 		buf[len] = '\0';
172 	}
173 
174 	if ((flags & FPARSELN_UNESCALL) != 0 && esc && buf != NULL &&
175 	    strchr(buf, esc) != NULL) {
176 		ptr = cp = buf;
177 		while (cp[0] != '\0') {
178 			int skipesc;
179 
180 			while (cp[0] != '\0' && cp[0] != esc)
181 				*ptr++ = *cp++;
182 			if (cp[0] == '\0' || cp[1] == '\0')
183 				break;
184 
185 			skipesc = 0;
186 			if (cp[1] == com)
187 				skipesc += (flags & FPARSELN_UNESCCOMM);
188 			if (cp[1] == con)
189 				skipesc += (flags & FPARSELN_UNESCCONT);
190 			if (cp[1] == esc)
191 				skipesc += (flags & FPARSELN_UNESCESC);
192 			if (cp[1] != com && cp[1] != con && cp[1] != esc)
193 				skipesc = (flags & FPARSELN_UNESCREST);
194 
195 			if (skipesc)
196 				cp++;
197 			else
198 				*ptr++ = *cp++;
199 			*ptr++ = *cp++;
200 		}
201 		*ptr = '\0';
202 		len = strlen(buf);
203 	}
204 
205 	if (size)
206 		*size = len;
207 	return buf;
208 }
209 
210 #ifdef TEST
211 
212 int
213 main(int argc, char *argv[])
214 {
215 	char   *ptr;
216 	size_t	size, line;
217 
218 	line = 0;
219 	while ((ptr = fparseln(stdin, &size, &line, NULL,
220 	    FPARSELN_UNESCALL)) != NULL)
221 		printf("line %d (%d) |%s|\n", line, size, ptr);
222 	return 0;
223 }
224 
225 /*
226 
227 # This is a test
228 line 1
229 line 2 \
230 line 3 # Comment
231 line 4 \# Not comment \\\\
232 
233 # And a comment \
234 line 5 \\\
235 line 6
236 
237 */
238 
239 #endif /* TEST */
240