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