1 /*-
2  * Copyright (c) 2007 Joerg Sonnenberger
3  * Copyright (c) 2012 Michihiro NAKAJIMA
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include "archive_platform.h"
28 
29 #ifdef HAVE_SYS_WAIT_H
30 #  include <sys/wait.h>
31 #endif
32 #ifdef HAVE_ERRNO_H
33 #  include <errno.h>
34 #endif
35 #ifdef HAVE_FCNTL_H
36 #  include <fcntl.h>
37 #endif
38 #ifdef HAVE_LIMITS_H
39 #  include <limits.h>
40 #endif
41 #ifdef HAVE_SIGNAL_H
42 #  include <signal.h>
43 #endif
44 #ifdef HAVE_STDLIB_H
45 #  include <stdlib.h>
46 #endif
47 #ifdef HAVE_STRING_H
48 #  include <string.h>
49 #endif
50 #ifdef HAVE_UNISTD_H
51 #  include <unistd.h>
52 #endif
53 
54 #include "archive.h"
55 #include "archive_private.h"
56 #include "archive_string.h"
57 #include "archive_read_private.h"
58 #include "filter_fork.h"
59 
60 
61 #if ARCHIVE_VERSION_NUMBER < 4000000
62 /* Deprecated; remove in libarchive 4.0 */
63 int
64 archive_read_support_compression_program(struct archive *a, const char *cmd)
65 {
66 	return archive_read_support_filter_program(a, cmd);
67 }
68 
69 int
70 archive_read_support_compression_program_signature(struct archive *a,
71     const char *cmd, const void *signature, size_t signature_len)
72 {
73 	return archive_read_support_filter_program_signature(a,
74 	    cmd, signature, signature_len);
75 }
76 #endif
77 
78 int
79 archive_read_support_filter_program(struct archive *a, const char *cmd)
80 {
81 	return (archive_read_support_filter_program_signature(a, cmd, NULL, 0));
82 }
83 
84 /*
85  * The bidder object stores the command and the signature to watch for.
86  * The 'inhibit' entry here is used to ensure that unchecked filters never
87  * bid twice in the same pipeline.
88  */
89 struct program_bidder {
90 	char *description;
91 	char *cmd;
92 	void *signature;
93 	size_t signature_len;
94 	int inhibit;
95 };
96 
97 static int	program_bidder_bid(struct archive_read_filter_bidder *,
98 		    struct archive_read_filter *upstream);
99 static int	program_bidder_init(struct archive_read_filter *);
100 static void	program_bidder_free(struct archive_read_filter_bidder *);
101 
102 /*
103  * The actual filter needs to track input and output data.
104  */
105 struct program_filter {
106 	struct archive_string description;
107 #if defined(_WIN32) && !defined(__CYGWIN__)
108 	HANDLE		 child;
109 #else
110 	pid_t		 child;
111 #endif
112 	int		 exit_status;
113 	int		 waitpid_return;
114 	int		 child_stdin, child_stdout;
115 
116 	char		*out_buf;
117 	size_t		 out_buf_len;
118 };
119 
120 static ssize_t	program_filter_read(struct archive_read_filter *,
121 		    const void **);
122 static int	program_filter_close(struct archive_read_filter *);
123 static void	free_state(struct program_bidder *);
124 
125 static const struct archive_read_filter_bidder_vtable
126 program_bidder_vtable = {
127 	.bid = program_bidder_bid,
128 	.init = program_bidder_init,
129 	.free = program_bidder_free,
130 };
131 
132 int
133 archive_read_support_filter_program_signature(struct archive *_a,
134     const char *cmd, const void *signature, size_t signature_len)
135 {
136 	struct archive_read *a = (struct archive_read *)_a;
137 	struct program_bidder *state;
138 
139 	/*
140 	 * Allocate our private state.
141 	 */
142 	state = (struct program_bidder *)calloc(1, sizeof (*state));
143 	if (state == NULL)
144 		goto memerr;
145 	state->cmd = strdup(cmd);
146 	if (state->cmd == NULL)
147 		goto memerr;
148 
149 	if (signature != NULL && signature_len > 0) {
150 		state->signature_len = signature_len;
151 		state->signature = malloc(signature_len);
152 		memcpy(state->signature, signature, signature_len);
153 	}
154 
155 	if (__archive_read_register_bidder(a, state, NULL,
156 				&program_bidder_vtable) != ARCHIVE_OK) {
157 		free_state(state);
158 		return (ARCHIVE_FATAL);
159 	}
160 	return (ARCHIVE_OK);
161 
162 memerr:
163 	free_state(state);
164 	archive_set_error(_a, ENOMEM, "Can't allocate memory");
165 	return (ARCHIVE_FATAL);
166 }
167 
168 static void
169 program_bidder_free(struct archive_read_filter_bidder *self)
170 {
171 	struct program_bidder *state = (struct program_bidder *)self->data;
172 
173 	free_state(state);
174 }
175 
176 static void
177 free_state(struct program_bidder *state)
178 {
179 
180 	if (state) {
181 		free(state->cmd);
182 		free(state->signature);
183 		free(state);
184 	}
185 }
186 
187 /*
188  * If we do have a signature, bid only if that matches.
189  *
190  * If there's no signature, we bid INT_MAX the first time
191  * we're called, then never bid again.
192  */
193 static int
194 program_bidder_bid(struct archive_read_filter_bidder *self,
195     struct archive_read_filter *upstream)
196 {
197 	struct program_bidder *state = self->data;
198 	const char *p;
199 
200 	/* If we have a signature, use that to match. */
201 	if (state->signature_len > 0) {
202 		p = __archive_read_filter_ahead(upstream,
203 		    state->signature_len, NULL);
204 		if (p == NULL)
205 			return (0);
206 		/* No match, so don't bid. */
207 		if (memcmp(p, state->signature, state->signature_len) != 0)
208 			return (0);
209 		return ((int)state->signature_len * 8);
210 	}
211 
212 	/* Otherwise, bid once and then never bid again. */
213 	if (state->inhibit)
214 		return (0);
215 	state->inhibit = 1;
216 	return (INT_MAX);
217 }
218 
219 /*
220  * Shut down the child, return ARCHIVE_OK if it exited normally.
221  *
222  * Note that the return value is sticky; if we're called again,
223  * we won't reap the child again, but we will return the same status
224  * (including error message if the child came to a bad end).
225  */
226 static int
227 child_stop(struct archive_read_filter *self, struct program_filter *state)
228 {
229 	/* Close our side of the I/O with the child. */
230 	if (state->child_stdin != -1) {
231 		close(state->child_stdin);
232 		state->child_stdin = -1;
233 	}
234 	if (state->child_stdout != -1) {
235 		close(state->child_stdout);
236 		state->child_stdout = -1;
237 	}
238 
239 	if (state->child != 0) {
240 		/* Reap the child. */
241 		do {
242 			state->waitpid_return
243 			    = waitpid(state->child, &state->exit_status, 0);
244 		} while (state->waitpid_return == -1 && errno == EINTR);
245 #if defined(_WIN32) && !defined(__CYGWIN__)
246 		CloseHandle(state->child);
247 #endif
248 		state->child = 0;
249 	}
250 
251 	if (state->waitpid_return < 0) {
252 		/* waitpid() failed?  This is ugly. */
253 		archive_set_error(&self->archive->archive, ARCHIVE_ERRNO_MISC,
254 		    "Child process exited badly");
255 		return (ARCHIVE_WARN);
256 	}
257 
258 #if !defined(_WIN32) || defined(__CYGWIN__)
259 	if (WIFSIGNALED(state->exit_status)) {
260 #ifdef SIGPIPE
261 		/* If the child died because we stopped reading before
262 		 * it was done, that's okay.  Some archive formats
263 		 * have padding at the end that we routinely ignore. */
264 		/* The alternative to this would be to add a step
265 		 * before close(child_stdout) above to read from the
266 		 * child until the child has no more to write. */
267 		if (WTERMSIG(state->exit_status) == SIGPIPE)
268 			return (ARCHIVE_OK);
269 #endif
270 		archive_set_error(&self->archive->archive, ARCHIVE_ERRNO_MISC,
271 		    "Child process exited with signal %d",
272 		    WTERMSIG(state->exit_status));
273 		return (ARCHIVE_WARN);
274 	}
275 #endif /* !_WIN32 || __CYGWIN__ */
276 
277 	if (WIFEXITED(state->exit_status)) {
278 		if (WEXITSTATUS(state->exit_status) == 0)
279 			return (ARCHIVE_OK);
280 
281 		archive_set_error(&self->archive->archive,
282 		    ARCHIVE_ERRNO_MISC,
283 		    "Child process exited with status %d",
284 		    WEXITSTATUS(state->exit_status));
285 		return (ARCHIVE_WARN);
286 	}
287 
288 	return (ARCHIVE_WARN);
289 }
290 
291 /*
292  * Use select() to decide whether the child is ready for read or write.
293  */
294 static ssize_t
295 child_read(struct archive_read_filter *self, char *buf, size_t buf_len)
296 {
297 	struct program_filter *state = self->data;
298 	ssize_t ret, requested, avail;
299 	const char *p;
300 #if defined(_WIN32) && !defined(__CYGWIN__)
301 	HANDLE handle = (HANDLE)_get_osfhandle(state->child_stdout);
302 #endif
303 
304 	requested = buf_len > SSIZE_MAX ? SSIZE_MAX : buf_len;
305 
306 	for (;;) {
307 		do {
308 #if defined(_WIN32) && !defined(__CYGWIN__)
309 			/* Avoid infinity wait.
310 			 * Note: If there is no data in the pipe, ReadFile()
311 			 * called in read() never returns and so we won't
312 			 * write remaining encoded data to the pipe.
313 			 * Note: This way may cause performance problem.
314 			 * we are looking forward to great code to resolve
315 			 * this.  */
316 			DWORD pipe_avail = -1;
317 			int cnt = 2;
318 
319 			while (PeekNamedPipe(handle, NULL, 0, NULL,
320 			    &pipe_avail, NULL) != 0 && pipe_avail == 0 &&
321 			    cnt--)
322 				Sleep(5);
323 			if (pipe_avail == 0) {
324 				ret = -1;
325 				errno = EAGAIN;
326 				break;
327 			}
328 #endif
329 			ret = read(state->child_stdout, buf, requested);
330 		} while (ret == -1 && errno == EINTR);
331 
332 		if (ret > 0)
333 			return (ret);
334 		if (ret == 0 || (ret == -1 && errno == EPIPE))
335 			/* Child has closed its output; reap the child
336 			 * and return the status. */
337 			return (child_stop(self, state));
338 		if (ret == -1 && errno != EAGAIN)
339 			return (-1);
340 
341 		if (state->child_stdin == -1) {
342 			/* Block until child has some I/O ready. */
343 			__archive_check_child(state->child_stdin,
344 			    state->child_stdout);
345 			continue;
346 		}
347 
348 		/* Get some more data from upstream. */
349 		p = __archive_read_filter_ahead(self->upstream, 1, &avail);
350 		if (p == NULL) {
351 			close(state->child_stdin);
352 			state->child_stdin = -1;
353 			fcntl(state->child_stdout, F_SETFL, 0);
354 			if (avail < 0)
355 				return (avail);
356 			continue;
357 		}
358 
359 		do {
360 			ret = write(state->child_stdin, p, avail);
361 		} while (ret == -1 && errno == EINTR);
362 
363 		if (ret > 0) {
364 			/* Consume whatever we managed to write. */
365 			__archive_read_filter_consume(self->upstream, ret);
366 		} else if (ret == -1 && errno == EAGAIN) {
367 			/* Block until child has some I/O ready. */
368 			__archive_check_child(state->child_stdin,
369 			    state->child_stdout);
370 		} else {
371 			/* Write failed. */
372 			close(state->child_stdin);
373 			state->child_stdin = -1;
374 			fcntl(state->child_stdout, F_SETFL, 0);
375 			/* If it was a bad error, we're done; otherwise
376 			 * it was EPIPE or EOF, and we can still read
377 			 * from the child. */
378 			if (ret == -1 && errno != EPIPE)
379 				return (-1);
380 		}
381 	}
382 }
383 
384 static const struct archive_read_filter_vtable
385 program_reader_vtable = {
386 	.read = program_filter_read,
387 	.close = program_filter_close,
388 };
389 
390 int
391 __archive_read_program(struct archive_read_filter *self, const char *cmd)
392 {
393 	struct program_filter	*state;
394 	static const size_t out_buf_len = 65536;
395 	char *out_buf;
396 	const char *prefix = "Program: ";
397 	int ret;
398 	size_t l;
399 
400 	l = strlen(prefix) + strlen(cmd) + 1;
401 	state = (struct program_filter *)calloc(1, sizeof(*state));
402 	out_buf = (char *)malloc(out_buf_len);
403 	if (state == NULL || out_buf == NULL ||
404 	    archive_string_ensure(&state->description, l) == NULL) {
405 		archive_set_error(&self->archive->archive, ENOMEM,
406 		    "Can't allocate input data");
407 		if (state != NULL) {
408 			archive_string_free(&state->description);
409 			free(state);
410 		}
411 		free(out_buf);
412 		return (ARCHIVE_FATAL);
413 	}
414 	archive_strcpy(&state->description, prefix);
415 	archive_strcat(&state->description, cmd);
416 
417 	self->code = ARCHIVE_FILTER_PROGRAM;
418 	self->name = state->description.s;
419 
420 	state->out_buf = out_buf;
421 	state->out_buf_len = out_buf_len;
422 
423 	ret = __archive_create_child(cmd, &state->child_stdin,
424 	    &state->child_stdout, &state->child);
425 	if (ret != ARCHIVE_OK) {
426 		free(state->out_buf);
427 		archive_string_free(&state->description);
428 		free(state);
429 		archive_set_error(&self->archive->archive, EINVAL,
430 		    "Can't initialize filter; unable to run program \"%s\"",
431 		    cmd);
432 		return (ARCHIVE_FATAL);
433 	}
434 
435 	self->data = state;
436 	self->vtable = &program_reader_vtable;
437 
438 	/* XXX Check that we can read at least one byte? */
439 	return (ARCHIVE_OK);
440 }
441 
442 static int
443 program_bidder_init(struct archive_read_filter *self)
444 {
445 	struct program_bidder   *bidder_state;
446 
447 	bidder_state = (struct program_bidder *)self->bidder->data;
448 	return (__archive_read_program(self, bidder_state->cmd));
449 }
450 
451 static ssize_t
452 program_filter_read(struct archive_read_filter *self, const void **buff)
453 {
454 	struct program_filter *state;
455 	ssize_t bytes;
456 	size_t total;
457 	char *p;
458 
459 	state = (struct program_filter *)self->data;
460 
461 	total = 0;
462 	p = state->out_buf;
463 	while (state->child_stdout != -1 && total < state->out_buf_len) {
464 		bytes = child_read(self, p, state->out_buf_len - total);
465 		if (bytes < 0)
466 			/* No recovery is possible if we can no longer
467 			 * read from the child. */
468 			return (ARCHIVE_FATAL);
469 		if (bytes == 0)
470 			/* We got EOF from the child. */
471 			break;
472 		total += bytes;
473 		p += bytes;
474 	}
475 
476 	*buff = state->out_buf;
477 	return (total);
478 }
479 
480 static int
481 program_filter_close(struct archive_read_filter *self)
482 {
483 	struct program_filter	*state;
484 	int e;
485 
486 	state = (struct program_filter *)self->data;
487 	e = child_stop(self, state);
488 
489 	/* Release our private data. */
490 	free(state->out_buf);
491 	archive_string_free(&state->description);
492 	free(state);
493 
494 	return (e);
495 }
496