xref: /freebsd/lib/libutil/fparseln.c (revision 6f1af0d7d2af54b339b5212434cd6d4fda628d80)
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 #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 
89 #if 0
90 	_DIAGASSERT(fp != NULL);
91 #endif
92 
93 	len = 0;
94 	buf = NULL;
95 	cnt = 1;
96 
97 	if (str == NULL)
98 		str = dstr;
99 
100 	esc = str[0];
101 	con = str[1];
102 	com = str[2];
103 	/*
104 	 * XXX: it would be cool to be able to specify the newline character,
105 	 * but unfortunately, fgetln does not let us
106 	 */
107 	nl  = '\n';
108 
109 	while (cnt) {
110 		cnt = 0;
111 
112 		if (lineno)
113 			(*lineno)++;
114 
115 		if ((ptr = fgetln(fp, &s)) == NULL)
116 			break;
117 
118 		if (s && com) {		/* Check and eliminate comments */
119 			for (cp = ptr; cp < ptr + s; cp++)
120 				if (*cp == com && !isescaped(ptr, cp, esc)) {
121 					s = cp - ptr;
122 					cnt = s == 0 && buf == NULL;
123 					break;
124 				}
125 		}
126 
127 		if (s && nl) { 		/* Check and eliminate newlines */
128 			cp = &ptr[s - 1];
129 
130 			if (*cp == nl)
131 				s--;	/* forget newline */
132 		}
133 
134 		if (s && con) {		/* Check and eliminate continuations */
135 			cp = &ptr[s - 1];
136 
137 			if (*cp == con && !isescaped(ptr, cp, esc)) {
138 				s--;	/* forget continuation char */
139 				cnt = 1;
140 			}
141 		}
142 
143 		if (s == 0) {
144 			/*
145 			 * nothing to add, skip realloc except in case
146 			 * we need a minimal buf to return an empty line
147 			 */
148 			if (cnt || buf != NULL)
149 				continue;
150 		}
151 
152 		if ((cp = realloc(buf, len + s + 1)) == NULL) {
153 			free(buf);
154 			return NULL;
155 		}
156 		buf = cp;
157 
158 		(void) memcpy(buf + len, ptr, s);
159 		len += s;
160 		buf[len] = '\0';
161 	}
162 
163 	if ((flags & FPARSELN_UNESCALL) != 0 && esc && buf != NULL &&
164 	    strchr(buf, esc) != NULL) {
165 		ptr = cp = buf;
166 		while (cp[0] != '\0') {
167 			int skipesc;
168 
169 			while (cp[0] != '\0' && cp[0] != esc)
170 				*ptr++ = *cp++;
171 			if (cp[0] == '\0' || cp[1] == '\0')
172 				break;
173 
174 			skipesc = 0;
175 			if (cp[1] == com)
176 				skipesc += (flags & FPARSELN_UNESCCOMM);
177 			if (cp[1] == con)
178 				skipesc += (flags & FPARSELN_UNESCCONT);
179 			if (cp[1] == esc)
180 				skipesc += (flags & FPARSELN_UNESCESC);
181 			if (cp[1] != com && cp[1] != con && cp[1] != esc)
182 				skipesc = (flags & FPARSELN_UNESCREST);
183 
184 			if (skipesc)
185 				cp++;
186 			else
187 				*ptr++ = *cp++;
188 			*ptr++ = *cp++;
189 		}
190 		*ptr = '\0';
191 		len = strlen(buf);
192 	}
193 
194 	if (size)
195 		*size = len;
196 	return buf;
197 }
198 
199 #ifdef TEST
200 
201 int
202 main(int argc, char *argv[])
203 {
204 	char   *ptr;
205 	size_t	size, line;
206 
207 	line = 0;
208 	while ((ptr = fparseln(stdin, &size, &line, NULL,
209 	    FPARSELN_UNESCALL)) != NULL)
210 		printf("line %d (%d) |%s|\n", line, size, ptr);
211 	return 0;
212 }
213 
214 /*
215 
216 # This is a test
217 line 1
218 line 2 \
219 line 3 # Comment
220 line 4 \# Not comment \\\\
221 
222 # And a comment \
223 line 5 \\\
224 line 6
225 
226 */
227 
228 #endif /* TEST */
229