1 /* vi: set sw=4 ts=4: */
3 * Uncompress applet for busybox (c) 2002 Glenn McGrath
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24 #include <sys/types.h>
29 #include "unarchive.h"
31 int uncompress_main(int argc, char **argv)
33 const char gunzip_to_stdout = 1;
34 const char gunzip_force = 2;
35 char status = EXIT_SUCCESS;
39 while ((opt = getopt(argc, argv, "cfh")) != -1) {
42 flags |= gunzip_to_stdout;
45 flags |= gunzip_force;
48 bb_show_usage(); /* exit's inside usage */
54 const char *old_path = argv[optind];
55 const char *delete_path = NULL;
56 char *new_path = NULL;
62 if (old_path == NULL || strcmp(old_path, "-") == 0) {
63 src_fd = fileno(stdin);
64 flags |= gunzip_to_stdout;
66 src_fd = bb_xopen(old_path, O_RDONLY);
68 /* Get the time stamp on the input file. */
69 if (stat(old_path, &stat_buf) < 0) {
70 bb_error_msg_and_die("Couldn't stat file %s", old_path);
74 /* Check that the input is sane. */
75 if (isatty(src_fd) && ((flags & gunzip_force) == 0)) {
77 ("compressed data not read from terminal. Use -f to force it.");
80 /* Set output filename and number */
81 if (flags & gunzip_to_stdout) {
82 dst_fd = fileno(stdout);
86 new_path = bb_xstrdup(old_path);
88 extension = strrchr(new_path, '.');
89 if (!extension || (strcmp(extension, ".Z") != 0)) {
90 bb_error_msg_and_die("Invalid extension");
94 /* Open output file */
95 dst_fd = bb_xopen(new_path, O_WRONLY | O_CREAT);
97 /* Set permissions on the file */
98 chmod(new_path, stat_buf.st_mode);
100 /* If unzip succeeds remove the old file */
101 delete_path = old_path;
104 /* do the decompression, and cleanup */
105 if ((bb_xread_char(src_fd) == 0x1f) && (bb_xread_char(src_fd) == 0x9d)) {
106 status = uncompress(src_fd, dst_fd);
108 bb_error_msg_and_die("Invalid magic");
111 if ((status != EXIT_SUCCESS) && (new_path)) {
112 /* Unzip failed, remove new path instead of old path */
113 delete_path = new_path;
116 if (dst_fd != fileno(stdout)) {
119 if (src_fd != fileno(stdin)) {
123 /* delete_path will be NULL if in test mode or from stdin */
124 if (delete_path && (unlink(delete_path) == -1)) {
125 bb_error_msg_and_die("Couldn't remove %s", delete_path);
130 } while (optind < argc);