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.
23 #include <sys/types.h>
28 #include "unarchive.h"
30 #define GUNZIP_TO_STDOUT 1
31 #define GUNZIP_FORCE 2
33 extern int uncompress_main(int argc, char **argv)
35 int status = EXIT_SUCCESS;
38 flags = bb_getopt_ulflags(argc, argv, "cf");
40 while (optind < argc) {
41 const char *compressed_file = argv[optind++];
42 const char *delete_path = NULL;
43 char *uncompressed_file = NULL;
47 if (strcmp(compressed_file, "-") == 0) {
48 src_fd = STDIN_FILENO;
49 flags |= GUNZIP_TO_STDOUT;
51 src_fd = bb_xopen(compressed_file, O_RDONLY);
54 /* Check that the input is sane. */
55 if (isatty(src_fd) && ((flags & GUNZIP_FORCE) == 0)) {
57 ("compressed data not read from terminal. Use -f to force it.");
60 /* Set output filename and number */
61 if (flags & GUNZIP_TO_STDOUT) {
62 dst_fd = STDOUT_FILENO;
67 uncompressed_file = bb_xstrdup(compressed_file);
69 extension = strrchr(uncompressed_file, '.');
70 if (!extension || (strcmp(extension, ".Z") != 0)) {
71 bb_error_msg_and_die("Invalid extension");
75 /* Open output file */
76 dst_fd = bb_xopen(uncompressed_file, O_WRONLY | O_CREAT);
78 /* Set permissions on the file */
79 stat(compressed_file, &stat_buf);
80 chmod(uncompressed_file, stat_buf.st_mode);
82 /* If unzip succeeds remove the old file */
83 delete_path = compressed_file;
86 /* do the decompression, and cleanup */
87 if ((bb_xread_char(src_fd) != 0x1f) || (bb_xread_char(src_fd) != 0x9d)) {
88 bb_error_msg_and_die("Invalid magic");
91 status = uncompress(src_fd, dst_fd);
93 if ((status != EXIT_SUCCESS) && (uncompressed_file)) {
94 /* Unzip failed, remove the uncomressed file instead of compressed file */
95 delete_path = uncompressed_file;
98 if (dst_fd != STDOUT_FILENO) {
101 if (src_fd != STDIN_FILENO) {
105 /* delete_path will be NULL if in test mode or from stdin */
106 if (delete_path && (unlink(delete_path) == -1)) {
107 bb_error_msg_and_die("Couldn't remove %s", delete_path);
110 free(uncompressed_file);