- whitespace cleanup and add a possible shrinkage suggestion
[oweals/busybox.git] / archival / bunzip2.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  *  Modified for busybox by Glenn McGrath <bug1@iinet.net.au>
4  *  Added support output to stdout by Thomas Lundquist <thomasez@zelow.no>
5  *
6  *  Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
7  */
8
9 #include "busybox.h"
10 #include "unarchive.h"
11
12 #define BUNZIP2_OPT_STDOUT      1
13 #define BUNZIP2_OPT_FORCE       2
14
15 int bunzip2_main(int argc, char **argv);
16 int bunzip2_main(int argc, char **argv)
17 {
18         USE_DESKTOP(long long) int status;
19         char *filename;
20         unsigned opt;
21         int src_fd, dst_fd;
22
23         opt = getopt32(argc, argv, "cf");
24
25         /* Set input filename and number */
26         filename = argv[optind];
27         if (filename && NOT_LONE_DASH(filename)) {
28                 /* Open input file */
29                 src_fd = xopen(filename, O_RDONLY);
30         } else {
31                 src_fd = STDIN_FILENO;
32                 filename = 0;
33         }
34
35         /* if called as bzcat force the stdout flag */
36         if ((opt & BUNZIP2_OPT_STDOUT) || applet_name[2] == 'c')
37                 filename = 0;
38
39         /* Check that the input is sane.  */
40         if (isatty(src_fd) && (opt & BUNZIP2_OPT_FORCE) == 0) {
41                 bb_error_msg_and_die("compressed data not read from terminal, "
42                                 "use -f to force it");
43         }
44
45         if (filename) {
46                 struct stat stat_buf;
47                 /* extension = filename+strlen(filename)-4 is buggy:
48                  * strlen may be less than 4 */
49                 char *extension = strrchr(filename, '.');
50                 if (!extension || strcmp(extension, ".bz2") != 0) {
51                         bb_error_msg_and_die("invalid extension");
52                 }
53                 xstat(filename, &stat_buf);
54                 *extension = '\0';
55                 dst_fd = xopen3(filename, O_WRONLY | O_CREAT | O_TRUNC,
56                                 stat_buf.st_mode);
57         } else dst_fd = STDOUT_FILENO;
58         status = uncompressStream(src_fd, dst_fd);
59         if (filename) {
60                 if (status >= 0) filename[strlen(filename)] = '.';
61                 if (unlink(filename) < 0) {
62                         bb_error_msg_and_die("cannot remove %s", filename);
63                 }
64         }
65
66         return status;
67 }