xref: /freebsd/lib/libc/gen/wordexp.c (revision fcb560670601b2a4d87bb31d7531c8dcc37ee71b)
1 /*-
2  * Copyright (c) 2002 Tim J. Robbins.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include "namespace.h"
28 #include <sys/cdefs.h>
29 #include <sys/types.h>
30 #include <sys/wait.h>
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <paths.h>
34 #include <signal.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <unistd.h>
39 #include <wordexp.h>
40 #include "un-namespace.h"
41 
42 __FBSDID("$FreeBSD$");
43 
44 static int	we_askshell(const char *, wordexp_t *, int);
45 static int	we_check(const char *, int);
46 
47 /*
48  * wordexp --
49  *	Perform shell word expansion on `words' and place the resulting list
50  *	of words in `we'. See wordexp(3).
51  *
52  *	Specified by IEEE Std. 1003.1-2001.
53  */
54 int
55 wordexp(const char * __restrict words, wordexp_t * __restrict we, int flags)
56 {
57 	int error;
58 
59 	if (flags & WRDE_REUSE)
60 		wordfree(we);
61 	if ((flags & WRDE_APPEND) == 0) {
62 		we->we_wordc = 0;
63 		we->we_wordv = NULL;
64 		we->we_strings = NULL;
65 		we->we_nbytes = 0;
66 	}
67 	if ((error = we_check(words, flags)) != 0) {
68 		wordfree(we);
69 		return (error);
70 	}
71 	if ((error = we_askshell(words, we, flags)) != 0) {
72 		wordfree(we);
73 		return (error);
74 	}
75 	return (0);
76 }
77 
78 static size_t
79 we_read_fully(int fd, char *buffer, size_t len)
80 {
81 	size_t done;
82 	ssize_t nread;
83 
84 	done = 0;
85 	do {
86 		nread = _read(fd, buffer + done, len - done);
87 		if (nread == -1 && errno == EINTR)
88 			continue;
89 		if (nread <= 0)
90 			break;
91 		done += nread;
92 	} while (done != len);
93 	return done;
94 }
95 
96 /*
97  * we_askshell --
98  *	Use the `wordexp' /bin/sh builtin function to do most of the work
99  *	in expanding the word string. This function is complicated by
100  *	memory management.
101  */
102 static int
103 we_askshell(const char *words, wordexp_t *we, int flags)
104 {
105 	int pdes[2];			/* Pipe to child */
106 	char bbuf[9];			/* Buffer for byte count */
107 	char wbuf[9];			/* Buffer for word count */
108 	long nwords, nbytes;		/* Number of words, bytes from child */
109 	long i;				/* Handy integer */
110 	size_t sofs;			/* Offset into we->we_strings */
111 	size_t vofs;			/* Offset into we->we_wordv */
112 	pid_t pid;			/* Process ID of child */
113 	pid_t wpid;			/* waitpid return value */
114 	int status;			/* Child exit status */
115 	int error;			/* Our return value */
116 	int serrno;			/* errno to return */
117 	char *np, *p;			/* Handy pointers */
118 	char *nstrings;			/* Temporary for realloc() */
119 	char **nwv;			/* Temporary for realloc() */
120 	sigset_t newsigblock, oldsigblock;
121 
122 	serrno = errno;
123 
124 	if (pipe2(pdes, O_CLOEXEC) < 0)
125 		return (WRDE_NOSPACE);	/* XXX */
126 	(void)sigemptyset(&newsigblock);
127 	(void)sigaddset(&newsigblock, SIGCHLD);
128 	(void)_sigprocmask(SIG_BLOCK, &newsigblock, &oldsigblock);
129 	if ((pid = fork()) < 0) {
130 		serrno = errno;
131 		_close(pdes[0]);
132 		_close(pdes[1]);
133 		(void)_sigprocmask(SIG_SETMASK, &oldsigblock, NULL);
134 		errno = serrno;
135 		return (WRDE_NOSPACE);	/* XXX */
136 	}
137 	else if (pid == 0) {
138 		/*
139 		 * We are the child; just get /bin/sh to run the wordexp
140 		 * builtin on `words'.
141 		 */
142 		(void)_sigprocmask(SIG_SETMASK, &oldsigblock, NULL);
143 		if ((pdes[1] != STDOUT_FILENO ?
144 		    _dup2(pdes[1], STDOUT_FILENO) :
145 		    _fcntl(pdes[1], F_SETFD, 0)) < 0)
146 			_exit(1);
147 		execl(_PATH_BSHELL, "sh", flags & WRDE_UNDEF ? "-u" : "+u",
148 		    "-c", "eval \"$1\";eval \"wordexp $2\"", "",
149 		    flags & WRDE_SHOWERR ? "" : "exec 2>/dev/null", words,
150 		    (char *)NULL);
151 		_exit(1);
152 	}
153 
154 	/*
155 	 * We are the parent; read the output of the shell wordexp function,
156 	 * which is a 32-bit hexadecimal word count, a 32-bit hexadecimal
157 	 * byte count (not including terminating null bytes), followed by
158 	 * the expanded words separated by nulls.
159 	 */
160 	_close(pdes[1]);
161 	if (we_read_fully(pdes[0], wbuf, 8) != 8 ||
162 			we_read_fully(pdes[0], bbuf, 8) != 8) {
163 		error = flags & WRDE_UNDEF ? WRDE_BADVAL : WRDE_SYNTAX;
164 		serrno = errno;
165 		goto cleanup;
166 	}
167 	wbuf[8] = bbuf[8] = '\0';
168 	nwords = strtol(wbuf, NULL, 16);
169 	nbytes = strtol(bbuf, NULL, 16) + nwords;
170 
171 	/*
172 	 * Allocate or reallocate (when flags & WRDE_APPEND) the word vector
173 	 * and string storage buffers for the expanded words we're about to
174 	 * read from the child.
175 	 */
176 	sofs = we->we_nbytes;
177 	vofs = we->we_wordc;
178 	if ((flags & (WRDE_DOOFFS|WRDE_APPEND)) == (WRDE_DOOFFS|WRDE_APPEND))
179 		vofs += we->we_offs;
180 	we->we_wordc += nwords;
181 	we->we_nbytes += nbytes;
182 	if ((nwv = realloc(we->we_wordv, (we->we_wordc + 1 +
183 	    (flags & WRDE_DOOFFS ?  we->we_offs : 0)) *
184 	    sizeof(char *))) == NULL) {
185 		error = WRDE_NOSPACE;
186 		goto cleanup;
187 	}
188 	we->we_wordv = nwv;
189 	if ((nstrings = realloc(we->we_strings, we->we_nbytes)) == NULL) {
190 		error = WRDE_NOSPACE;
191 		goto cleanup;
192 	}
193 	for (i = 0; i < vofs; i++)
194 		if (we->we_wordv[i] != NULL)
195 			we->we_wordv[i] += nstrings - we->we_strings;
196 	we->we_strings = nstrings;
197 
198 	if (we_read_fully(pdes[0], we->we_strings + sofs, nbytes) != nbytes) {
199 		error = flags & WRDE_UNDEF ? WRDE_BADVAL : WRDE_SYNTAX;
200 		serrno = errno;
201 		goto cleanup;
202 	}
203 
204 	error = 0;
205 cleanup:
206 	_close(pdes[0]);
207 	do
208 		wpid = _waitpid(pid, &status, 0);
209 	while (wpid < 0 && errno == EINTR);
210 	(void)_sigprocmask(SIG_SETMASK, &oldsigblock, NULL);
211 	if (error != 0) {
212 		errno = serrno;
213 		return (error);
214 	}
215 	if (wpid < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0)
216 		return (flags & WRDE_UNDEF ? WRDE_BADVAL : WRDE_SYNTAX);
217 
218 	/*
219 	 * Break the null-terminated expanded word strings out into
220 	 * the vector.
221 	 */
222 	if (vofs == 0 && flags & WRDE_DOOFFS)
223 		while (vofs < we->we_offs)
224 			we->we_wordv[vofs++] = NULL;
225 	p = we->we_strings + sofs;
226 	while (nwords-- != 0) {
227 		we->we_wordv[vofs++] = p;
228 		if ((np = memchr(p, '\0', nbytes)) == NULL)
229 			return (WRDE_NOSPACE);	/* XXX */
230 		nbytes -= np - p + 1;
231 		p = np + 1;
232 	}
233 	we->we_wordv[vofs] = NULL;
234 
235 	return (0);
236 }
237 
238 /*
239  * we_check --
240  *	Check that the string contains none of the following unquoted
241  *	special characters: <newline> |&;<>(){}
242  *	or command substitutions when WRDE_NOCMD is set in flags.
243  */
244 static int
245 we_check(const char *words, int flags)
246 {
247 	char c;
248 	int dquote, level, quote, squote;
249 
250 	quote = squote = dquote = 0;
251 	while ((c = *words++) != '\0') {
252 		switch (c) {
253 		case '\\':
254 			if (squote == 0)
255 				quote ^= 1;
256 			continue;
257 		case '\'':
258 			if (quote + dquote == 0)
259 				squote ^= 1;
260 			break;
261 		case '"':
262 			if (quote + squote == 0)
263 				dquote ^= 1;
264 			break;
265 		case '`':
266 			if (quote + squote == 0 && flags & WRDE_NOCMD)
267 				return (WRDE_CMDSUB);
268 			while ((c = *words++) != '\0' && c != '`')
269 				if (c == '\\' && (c = *words++) == '\0')
270 					break;
271 			if (c == '\0')
272 				return (WRDE_SYNTAX);
273 			break;
274 		case '|': case '&': case ';': case '<': case '>':
275 		case '{': case '}': case '(': case ')': case '\n':
276 			if (quote + squote + dquote == 0)
277 				return (WRDE_BADCHAR);
278 			break;
279 		case '$':
280 			if ((c = *words++) == '\0')
281 				break;
282 			else if (quote + squote == 0 && c == '(') {
283 				if (flags & WRDE_NOCMD && *words != '(')
284 					return (WRDE_CMDSUB);
285 				level = 1;
286 				while ((c = *words++) != '\0') {
287 					if (c == '\\') {
288 						if ((c = *words++) == '\0')
289 							break;
290 					} else if (c == '(')
291 						level++;
292 					else if (c == ')' && --level == 0)
293 						break;
294 				}
295 				if (c == '\0' || level != 0)
296 					return (WRDE_SYNTAX);
297 			} else if (quote + squote == 0 && c == '{') {
298 				level = 1;
299 				while ((c = *words++) != '\0') {
300 					if (c == '\\') {
301 						if ((c = *words++) == '\0')
302 							break;
303 					} else if (c == '{')
304 						level++;
305 					else if (c == '}' && --level == 0)
306 						break;
307 				}
308 				if (c == '\0' || level != 0)
309 					return (WRDE_SYNTAX);
310 			} else
311 				--words;
312 			break;
313 		default:
314 			break;
315 		}
316 		quote = 0;
317 	}
318 	if (quote + squote + dquote != 0)
319 		return (WRDE_SYNTAX);
320 
321 	return (0);
322 }
323 
324 /*
325  * wordfree --
326  *	Free the result of wordexp(). See wordexp(3).
327  *
328  *	Specified by IEEE Std. 1003.1-2001.
329  */
330 void
331 wordfree(wordexp_t *we)
332 {
333 
334 	if (we == NULL)
335 		return;
336 	free(we->we_wordv);
337 	free(we->we_strings);
338 	we->we_wordv = NULL;
339 	we->we_strings = NULL;
340 	we->we_nbytes = 0;
341 	we->we_wordc = 0;
342 }
343