8d098b656ceeef16771225310e631cd2f367522b
[dragonfly.git] / lib / libc / gen / wordexp.c
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  * $FreeBSD: src/lib/libc/gen/wordexp.c,v 1.6 2004/06/30 13:55:08 tjr Exp $
27  * $DragonFly: src/lib/libc/gen/wordexp.c,v 1.1 2008/10/06 21:01:37 swildner Exp $
28  */
29
30 #include <sys/types.h>
31 #include <sys/wait.h>
32 #include <fcntl.h>
33 #include <paths.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <wordexp.h>
39
40 static int      we_askshell(const char *, wordexp_t *, int);
41 static int      we_check(const char *, int);
42
43 /*
44  * wordexp --
45  *      Perform shell word expansion on `words' and place the resulting list
46  *      of words in `we'. See wordexp(3).
47  *
48  *      Specified by IEEE Std. 1003.1-2001.
49  */
50 int
51 wordexp(const char * __restrict words, wordexp_t * __restrict we, int flags)
52 {
53         int error;
54
55         if (flags & WRDE_REUSE)
56                 wordfree(we);
57         if ((flags & WRDE_APPEND) == 0) {
58                 we->we_wordc = 0;
59                 we->we_wordv = NULL;
60                 we->we_strings = NULL;
61                 we->we_nbytes = 0;
62         }
63         if ((error = we_check(words, flags)) != 0) {
64                 wordfree(we);
65                 return (error);
66         }
67         if ((error = we_askshell(words, we, flags)) != 0) {
68                 wordfree(we);
69                 return (error);
70         }
71         return (0);
72 }
73
74 /*
75  * we_askshell --
76  *      Use the `wordexp' /bin/sh builtin function to do most of the work
77  *      in expanding the word string. This function is complicated by
78  *      memory management.
79  */
80 static int
81 we_askshell(const char *words, wordexp_t *we, int flags)
82 {
83         int pdes[2];                    /* Pipe to child */
84         char bbuf[9];                   /* Buffer for byte count */
85         char wbuf[9];                   /* Buffer for word count */
86         long nwords, nbytes;            /* Number of words, bytes from child */
87         long i;                         /* Handy integer */
88         size_t sofs;                    /* Offset into we->we_strings */
89         size_t vofs;                    /* Offset into we->we_wordv */
90         pid_t pid;                      /* Process ID of child */
91         int status;                     /* Child exit status */
92         char *ifs;                      /* IFS env. var. */
93         char *np, *p;                   /* Handy pointers */
94         char *nstrings;                 /* Temporary for realloc() */
95         char **nwv;                     /* Temporary for realloc() */
96
97         if ((ifs = getenv("IFS")) == NULL)
98                 ifs = " \t\n";
99
100         if (pipe(pdes) < 0)
101                 return (WRDE_NOSPACE);  /* XXX */
102         if ((pid = fork()) < 0) {
103                 _close(pdes[0]);
104                 _close(pdes[1]);
105                 return (WRDE_NOSPACE);  /* XXX */
106         }
107         else if (pid == 0) {
108                 /*
109                  * We are the child; just get /bin/sh to run the wordexp
110                  * builtin on `words'.
111                  */
112                 int devnull;
113                 char *cmd;
114
115                 _close(pdes[0]);
116                 if (_dup2(pdes[1], STDOUT_FILENO) < 0)
117                         _exit(1);
118                 _close(pdes[1]);
119                 if (asprintf(&cmd, "wordexp%c%s\n", *ifs, words) < 0)
120                         _exit(1);
121                 if ((flags & WRDE_SHOWERR) == 0) {
122                         if ((devnull = _open(_PATH_DEVNULL, O_RDWR, 0666)) < 0)
123                                 _exit(1);
124                         if (_dup2(devnull, STDERR_FILENO) < 0)
125                                 _exit(1);
126                         _close(devnull);
127                 }
128                 execl(_PATH_BSHELL, "sh", flags & WRDE_UNDEF ? "-u" : "+u",
129                     "-c", cmd, (char *)NULL);
130                 _exit(1);
131         }
132
133         /*
134          * We are the parent; read the output of the shell wordexp function,
135          * which is a 32-bit hexadecimal word count, a 32-bit hexadecimal
136          * byte count (not including terminating null bytes), followed by
137          * the expanded words separated by nulls.
138          */
139         _close(pdes[1]);
140         if (_read(pdes[0], wbuf, 8) != 8 || _read(pdes[0], bbuf, 8) != 8) {
141                 _close(pdes[0]);
142                 _waitpid(pid, &status, 0);
143                 return (flags & WRDE_UNDEF ? WRDE_BADVAL : WRDE_SYNTAX);
144         }
145         wbuf[8] = bbuf[8] = '\0';
146         nwords = strtol(wbuf, NULL, 16);
147         nbytes = strtol(bbuf, NULL, 16) + nwords;
148
149         /*
150          * Allocate or reallocate (when flags & WRDE_APPEND) the word vector
151          * and string storage buffers for the expanded words we're about to
152          * read from the child.
153          */
154         sofs = we->we_nbytes;
155         vofs = we->we_wordc;
156         if ((flags & (WRDE_DOOFFS|WRDE_APPEND)) == (WRDE_DOOFFS|WRDE_APPEND))
157                 vofs += we->we_offs;
158         we->we_wordc += nwords;
159         we->we_nbytes += nbytes;
160         if ((nwv = realloc(we->we_wordv, (we->we_wordc + 1 +
161             (flags & WRDE_DOOFFS ?  we->we_offs : 0)) *
162             sizeof(char *))) == NULL) {
163                 _close(pdes[0]);
164                 _waitpid(pid, &status, 0);
165                 return (WRDE_NOSPACE);
166         }
167         we->we_wordv = nwv;
168         if ((nstrings = realloc(we->we_strings, we->we_nbytes)) == NULL) {
169                 _close(pdes[0]);
170                 _waitpid(pid, &status, 0);
171                 return (WRDE_NOSPACE);
172         }
173         for (i = 0; i < vofs; i++)
174                 if (we->we_wordv[i] != NULL)
175                         we->we_wordv[i] += nstrings - we->we_strings;
176         we->we_strings = nstrings;
177
178         if (_read(pdes[0], we->we_strings + sofs, nbytes) != nbytes) {
179                 _close(pdes[0]);
180                 _waitpid(pid, &status, 0);
181                 return (flags & WRDE_UNDEF ? WRDE_BADVAL : WRDE_SYNTAX);
182         }
183
184         if (_waitpid(pid, &status, 0) < 0 || !WIFEXITED(status) ||
185             WEXITSTATUS(status) != 0) {
186                 _close(pdes[0]);
187                 return (flags & WRDE_UNDEF ? WRDE_BADVAL : WRDE_SYNTAX);
188         }
189         _close(pdes[0]);
190
191         /*
192          * Break the null-terminated expanded word strings out into
193          * the vector.
194          */
195         if (vofs == 0 && flags & WRDE_DOOFFS)
196                 while (vofs < we->we_offs)
197                         we->we_wordv[vofs++] = NULL;
198         p = we->we_strings + sofs;
199         while (nwords-- != 0) {
200                 we->we_wordv[vofs++] = p;
201                 if ((np = memchr(p, '\0', nbytes)) == NULL)
202                         return (WRDE_NOSPACE);  /* XXX */
203                 nbytes -= np - p + 1;
204                 p = np + 1;
205         }
206         we->we_wordv[vofs] = NULL;
207
208         return (0);
209 }
210
211 /*
212  * we_check --
213  *      Check that the string contains none of the following unquoted
214  *      special characters: <newline> |&;<>(){}
215  *      or command substitutions when WRDE_NOCMD is set in flags.
216  */
217 static int
218 we_check(const char *words, int flags)
219 {
220         char c;
221         int dquote, level, quote, squote;
222
223         quote = squote = dquote = 0;
224         while ((c = *words++) != '\0') {
225                 switch (c) {
226                 case '\\':
227                         quote ^= 1;
228                         continue;
229                 case '\'':
230                         if (quote + dquote == 0)
231                                 squote ^= 1;
232                         break;
233                 case '"':
234                         if (quote + squote == 0)
235                                 dquote ^= 1;
236                         break;
237                 case '`':
238                         if (quote + squote == 0 && flags & WRDE_NOCMD)
239                                 return (WRDE_CMDSUB);
240                         while ((c = *words++) != '\0' && c != '`')
241                                 if (c == '\\' && (c = *words++) == '\0')
242                                         break;
243                         if (c == '\0')
244                                 return (WRDE_SYNTAX);
245                         break;
246                 case '|': case '&': case ';': case '<': case '>':
247                 case '{': case '}': case '(': case ')': case '\n':
248                         if (quote + squote + dquote == 0)
249                                 return (WRDE_BADCHAR);
250                         break;
251                 case '$':
252                         if ((c = *words++) == '\0')
253                                 break;
254                         else if (quote + squote == 0 && c == '(') {
255                                 if (flags & WRDE_NOCMD && *words != '(')
256                                         return (WRDE_CMDSUB);
257                                 level = 1;
258                                 while ((c = *words++) != '\0') {
259                                         if (c == '\\') {
260                                                 if ((c = *words++) == '\0')
261                                                         break;
262                                         } else if (c == '(')
263                                                 level++;
264                                         else if (c == ')' && --level == 0)
265                                                 break;
266                                 }
267                                 if (c == '\0' || level != 0)
268                                         return (WRDE_SYNTAX);
269                         } else if (quote + squote == 0 && c == '{') {
270                                 level = 1;
271                                 while ((c = *words++) != '\0') {
272                                         if (c == '\\') {
273                                                 if ((c = *words++) == '\0')
274                                                         break;
275                                         } else if (c == '{')
276                                                 level++;
277                                         else if (c == '}' && --level == 0)
278                                                 break;
279                                 }
280                                 if (c == '\0' || level != 0)
281                                         return (WRDE_SYNTAX);
282                         } else
283                                 c = *--words;
284                         break;
285                 default:
286                         break;
287                 }
288                 quote = 0;
289         }
290         if (quote + squote + dquote != 0)
291                 return (WRDE_SYNTAX);
292
293         return (0);
294 }
295
296 /*
297  * wordfree --
298  *      Free the result of wordexp(). See wordexp(3).
299  *
300  *      Specified by IEEE Std. 1003.1-2001.
301  */
302 void
303 wordfree(wordexp_t *we)
304 {
305
306         if (we == NULL)
307                 return;
308         free(we->we_wordv);
309         free(we->we_strings);
310         we->we_wordv = NULL;
311         we->we_strings = NULL;
312         we->we_nbytes = 0;
313         we->we_wordc = 0;
314 }