installer: Move the installer from contrib/ to usr.sbin/.
[dragonfly.git] / usr.sbin / installer / libaura / popen.c
1 /*
2  * Copyright (c) 1988, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 2004 The DragonFly Project.  All rights reserved.
5  *
6  * This code is derived from software written by Ken Arnold and
7  * published in UNIX Review, Vol. 6, No. 8.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *      This product includes software developed by the University of
20  *      California, Berkeley and its contributors.
21  * 4. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  * $FreeBSD: src/lib/libc/gen/popen.c,v 1.14 2000/01/27 23:06:19 jasone Exp $
38  * $DragonFly: src/contrib/bsdinstaller-1.1.6/src/lib/libaura/popen.c,v 1.1.1.1 2008/03/12 22:15:54 dave Exp $
39  * $Id: popen.c,v 1.6 2005/02/06 06:57:30 cpressey Exp $
40  *
41  * @(#)popen.c  8.3 (Berkeley) 5/3/95
42  *
43  * A modified version of the standard popen()/pclose() functions
44  * which adds a third function, pgetpid(), which allows the program
45  * which used popen() to obtain the pid of the process on the other
46  * end of the pipe.
47  */
48
49 #include <sys/param.h>
50 #include <sys/wait.h>
51 #include <sys/types.h>
52 #include <sys/time.h>
53
54 #include <errno.h>
55 #include <signal.h>
56 #include <stdarg.h>
57 #include <paths.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <unistd.h>
62
63 #include "popen.h"
64
65 extern char **environ;
66
67 static struct pid {
68         struct pid      *next;
69         FILE            *fp;
70         pid_t           pid;
71 } *pidlist;
72
73 FILE *
74 aura_popen(const char *fmt, const char *type, ...)
75 {
76         FILE *iop;
77         struct pid *cur;
78         struct pid *p;
79         va_list args;
80         char *command;
81         const char *argv[4];
82         int pdes[2], pid;
83         volatile enum { READ, WRITE, TWO_WAY } pipedir;
84
85         /*
86          * Lite2 introduced two-way popen() pipes using socketpair().
87          * FreeBSD's pipe() is bidirectional, so we use that.
88          */
89         if (strchr(type, '+')) {
90                 pipedir = TWO_WAY;
91         } else {
92                 if (type[1] != '\0')
93                         return(NULL);
94                 if (*type == 'r')
95                         pipedir = READ;
96                 else if (*type == 'w')
97                         pipedir = WRITE;
98                 else
99                         return(NULL);
100         }
101
102         if (pipe(pdes) < 0)
103                 return(NULL);
104
105         if ((cur = malloc(sizeof(struct pid))) == NULL) {
106                 close(pdes[0]);
107                 close(pdes[1]);
108                 return(NULL);
109         }
110
111         va_start(args, type);
112         vasprintf(&command, fmt, args);
113         va_end(args);
114
115         argv[0] = "sh";
116         argv[1] = "-c";
117         argv[2] = command;
118         argv[3] = NULL;
119
120         switch (pid = vfork()) {
121         case -1:                        /* Error. */
122                 close(pdes[0]);
123                 close(pdes[1]);
124                 free(cur);
125                 free(command);
126                 return(NULL);
127                 /* NOTREACHED */
128         case 0:                         /* Child. */
129                 if (pipedir == READ || pipedir == TWO_WAY) {
130                         /*
131                          * The dup2() to STDIN_FILENO is repeated to avoid
132                          * writing to pdes[1], which might corrupt the
133                          * parent's copy.  This isn't good enough in
134                          * general, since the _exit() is no return, so
135                          * the compiler is free to corrupt all the local
136                          * variables.
137                          */
138                         close(pdes[0]);
139                         if (pdes[1] != STDOUT_FILENO) {
140                                 dup2(pdes[1], STDOUT_FILENO);
141                                 close(pdes[1]);
142                                 if (pipedir == TWO_WAY)
143                                         dup2(STDOUT_FILENO, STDIN_FILENO);
144                         } else if (pipedir == TWO_WAY &&
145                                    (pdes[1] != STDIN_FILENO)) {
146                                 dup2(pdes[1], STDIN_FILENO);
147                         }
148                 } else {
149                         if (pdes[0] != STDIN_FILENO) {
150                                 dup2(pdes[0], STDIN_FILENO);
151                                 close(pdes[0]);
152                         }
153                         close(pdes[1]);
154                 }
155                 for (p = pidlist; p; p = p->next) {
156                         close(fileno(p->fp));
157                 }
158                 execve(_PATH_BSHELL, __DECONST(char **, argv), environ);
159                 _exit(127);
160                 /* NOTREACHED */
161         }
162
163         /* Parent; assume fdopen can't fail. */
164         if (pipedir == READ || pipedir == TWO_WAY) {
165                 iop = fdopen(pdes[0], type);
166                 close(pdes[1]);
167         } else {
168                 iop = fdopen(pdes[1], type);
169                 close(pdes[0]);
170         }
171
172         /* Link into list of file descriptors. */
173         cur->fp = iop;
174         cur->pid =  pid;
175         cur->next = pidlist;
176         pidlist = cur;
177
178         free(command);
179         return(iop);
180 }
181
182 /*
183  * pclose --
184  *      Pclose returns -1 if stream is not associated with a `popened' command,
185  *      if already `pclosed', or waitpid returns an error.
186  */
187 int
188 aura_pclose(FILE *iop)
189 {
190         struct pid *cur, *last;
191         int pstat;
192         pid_t pid;
193
194         /* Find the appropriate file pointer. */
195         for (last = NULL, cur = pidlist; cur; last = cur, cur = cur->next) {
196                 if (cur->fp == iop)
197                         break;
198         }
199
200         if (cur == NULL)
201                 return (-1);
202
203         fclose(iop);
204
205         do {
206                 pid = wait4(cur->pid, &pstat, 0, (struct rusage *)0);
207         } while (pid == -1 && errno == EINTR);
208
209         /* Remove the entry from the linked list. */
210         if (last == NULL)
211                 pidlist = cur->next;
212         else
213                 last->next = cur->next;
214         free(cur);
215
216         return (pid == -1 ? -1 : pstat);
217 }
218
219 pid_t
220 aura_pgetpid(FILE *iop)
221 {
222         struct pid *cur, *last;
223
224         /* Find the appropriate file pointer. */
225         for (last = NULL, cur = pidlist; cur; last = cur, cur = cur->next)
226                 if (cur->fp == iop)
227                         break;
228         if (cur == NULL)
229                 return (-1);
230         return(cur->pid);
231 }
232
233 /*
234  * Returns:
235  *      1 if all went well.
236  *      0 if an error occurred, in which case err is set to:
237  *              AURA_PGETS_TIMEOUT:     select() timed out.
238  *              AURA_PGETS_SELECT_ERR:  a select() error occurred.
239  *              AURA_PGETS_EOF:         end of file condition on pipe.
240  *              AURA_PGETS_FGETS_ERR:   a fgets() error occurred.
241  */
242 int
243 aura_pgets(FILE *p, char *buf, size_t len, long msec, int *err)
244 {
245         struct timeval tv;
246         struct timeval *tvp;
247         fd_set r;
248         int n;
249
250         tv.tv_sec = msec / 1000;
251         tv.tv_usec = (msec % 1000) * 1000;
252         tvp = (msec < 0 ? NULL : &tv);
253
254         FD_ZERO(&r);
255         FD_SET(fileno(p), &r);
256
257         *err = 0;
258         buf[0] = '\0';
259
260         if (feof(p)) {
261                 *err = AURA_PGETS_EOF;
262                 return(0);
263         }
264         if (ferror(p)) {
265                 *err = AURA_PGETS_FGETS_ERR;
266                 return(0);
267         }
268
269         n = select(fileno(p) + 1, &r, NULL, NULL, tvp);
270
271         if (n == 0) {
272                 *err = AURA_PGETS_TIMEOUT;
273                 return(0);
274         } else if (n < 0) {
275                 *err = AURA_PGETS_SELECT_ERR;
276                 return(0);
277         } else {
278                 /* Data came in; read it. */
279                 if (fgets(buf, len, p) == NULL) {
280                         if (feof(p)) {
281                                 *err = AURA_PGETS_EOF;
282                         } else {
283                                 *err = AURA_PGETS_FGETS_ERR;
284                         }
285                         return(0);
286                 } else {
287                         return(1);
288                 }
289         }
290 }