File: xpopen.c

package info (click to toggle)
pdsh 1.7-6-8
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 1,024 kB
  • ctags: 517
  • sloc: ansic: 6,164; sh: 5,783; makefile: 201; exp: 107; perl: 91
file content (268 lines) | stat: -rw-r--r-- 6,248 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
/*****************************************************************************\
 *
 *  $Id: xpopen.c,v 1.9 2002/08/18 20:15:38 garlick Exp $
 *  $Source: /chaos/cvs/pdsh/xpopen.c,v $
 *
 *  Copyright (C) 1998-2002 The Regents of the University of California.
 *  Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER).
 *  Written by Jim Garlick (garlick@llnl.gov>
 *  UCRL-CODE-980038
 *  
 *  This file is part of PDSH, a parallel remote shell program.
 *  For details, see <http://www.llnl.gov/linux/pdsh/>.
 *  
 *  PDSH is free software; you can redistribute it and/or modify it under
 *  the terms of the GNU General Public License as published by the Free
 *  Software Foundation; either version 2 of the License, or (at your option)
 *  any later version.
 *  
 *  PDSH is distributed in the hope that it will be useful, but WITHOUT 
 *  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
 *  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License 
 *  for more details.
 *  
 *  You should have received a copy of the GNU General Public License along
 *  with PDSH; if not, write to the Free Software Foundation, Inc.,
 *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
\*****************************************************************************/

#if     HAVE_CONFIG_H
#include "config.h"
#endif

#if	HAVE_UNISTD_H
#include <unistd.h>	/* for R_OK, access() */
#endif

#include <stdio.h>
#include <limits.h>	/* ARG_MAX */
#include <sys/wait.h>   /* waitpid() */
#include <string.h>     /* strcmp() */
#include <stdlib.h>
#include <errno.h>

#include "xmalloc.h"
#include "xstring.h"
#include "err.h"
#include "list.h"

#define QUOTE '\"'
#define SPACE ' '
#define TAB   '\t'
#define NWLN  '\n'

extern int errno;

static struct pid {
	struct pid *next;
	FILE *fp;
	pid_t pid;
} *pidlist;

/* forward declaration */
static list_t _parse_command_with_quotes(char *str);

/* 
 * xpopen(): a safer popen for pdsh.
 * We bypass shell by doing a fork and exec'ing the cmd directly.
 * also, set euid back to original user. This avoids passing possibly
 * user supplied arguments to a suid shell.
 *
 * xpopen returns NULL if the fork or pipe calls fail, or if it cannot
 * allocate memory.
 *
 * Since a shell is not invoked on the command string, you cannot pass
 * things that normally the shell would handle. The only thing xpopen()
 * attempts to deal with are double quoted strings.
 *
 * the returned stream must be closed by xpclose (see below)
 * 
 * cmd (IN) 	cmd to run, as in popen
 * mode(IN)	"r" for reading, "w" (or anything else) for writing
 * OUT		FILE * to output/input stream of child process
 */
FILE *
xpopen(char *cmd, char *mode)
{
	struct pid *cur;
	int fds[2], j, read, fd;
	pid_t pid;
	char *av[ARG_MAX+1];
	int maxfd = sysconf(_SC_OPEN_MAX);
        list_t args = _parse_command_with_quotes(cmd);

	if ((*mode != 'r' && *mode != 'w') || mode[1] != '\0') {
		errno = EINVAL;
		return (NULL);
	}

	cur = Malloc(sizeof(struct pid));

        read = (*mode == 'r');

	/* build up argument vector */
	j=0;
	while ((av[j++] = list_shift(args)) != NULL) {;}
	av[++j] = NULL;
	

	if (pipe(fds) < 0) {
		close(fds[0]);
		close(fds[1]);
		Free((void **)&cur);
		errx("%p: unable to dup stdout\n");
	}

	switch (pid = fork()) {
	case -1:			/* Error. */
		close(fds[0]);
		close(fds[1]);
		Free((void **)&cur);
		return (NULL);

	case 0:				/* child */

		close(fds[read ? 0 : 1]);
		dup2(fds[read ? 1 : 0], read ? STDOUT_FILENO : STDIN_FILENO);

		for (fd = STDERR_FILENO + 1; fd < maxfd; fd++)
			close(fd);

		setgid(getgid());
		setuid(getuid());

		do {
			if (access(av[0], F_OK) != 0 && errno != EINTR) {
				fprintf(stderr, "%s: not found\n", av[0]); 
				fflush(stderr);
			}
		} while (errno == EINTR);

		execv(av[0], av);

		exit(errno);
	} /* switch() */

	/* free av */
	while( av[j++] != NULL) 
		Free((void **)&av[j]);

	close(fds[read ? 1 : 0]);

	/* insert child pid into pidlist */
	cur->fp = fdopen(fds[read ? 0 : 1], mode);
	cur->pid = pid;
	cur->next = pidlist;
	pidlist = cur;

	return (cur->fp); 

}

/*
 * xpclose(): close stream opened with xpopen. reap proper child and
 *            return exit status.
 *
 * f (IN)	file stream as returned by xpopen()
 *
 * (OUT)	-1 on error (was f opened by xpopen?) 
 *              otherwise, exit status of child as modified by 
 *              WEXITSTATUS macro (see waitpid(3))
 *              This is different from pclose, which returns the 
 *              unmodified status from waitpid.
 */
int 
xpclose(FILE *f)
{
	int status;
	pid_t pid;
	struct pid *cur, *last;

	fclose(f);

	for (last = NULL, cur = pidlist; cur; last = cur, cur = cur->next)
		if (f == cur->fp)
			break;

	if (cur == NULL)
		return(-1);

	do {
		pid = waitpid(cur->pid, &status, 0);
	} while (pid == -1 && errno == EINTR);

	if (last == NULL)
		pidlist = cur->next;
	else
		last->next = cur->next;

	Free((void **)&cur);

	return (WIFEXITED(status) != 0) ? WEXITSTATUS(status) : -1;
}
	
/* parse_commaned_with_quotes(): 
 * helper function for xpopen
 *
 * provides simple string parsing with support for double quoted arguments,
 * and that is all. This is probably too simple to do what you want.
 * Only makes a minimal effort to complain when there's no matching quote.
 *
 * str(IN)	string to parse
 * (OUT)	list of arguments, strings enclosed in "" are treated as
 * 		one arg. 
 */
static list_t 
_parse_command_with_quotes(char *str)
{
	list_t args = list_new();
	char *c, *lc;

	c = lc = str;

	while (*c != '\0') {
		switch (*c) {
		case QUOTE:
			lc = ++c;
			/* find matching quote */
			while( *c != '\0' &&  *c != QUOTE)
				c++;

			if (*c == '\0') 
				errx("%P: Unmatched `%c' in xpopen\n", *lc);

			/* nullify quote */
			*c = '\0';

			/* push token onto list */
			if (strlen(lc) > 0)
				list_push(args, lc);

			/* move c past null */
			lc = ++c;

			break;
		case SPACE:
		case TAB:
		case NWLN:
			/* nullify and push token onto list */
			*c = '\0';
			if (lc != NULL && strlen(lc) > 0) 
				list_push(args, lc);

			lc = ++c;
			break;
		default:
			c++;
		}
	}

	/* hit a null. push last token onto list, if such a one exists */
	if (strlen(lc) > 0) 
		list_push(args, lc);

	return args;

}