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