lsmod: repair indentation
[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 {
17         char *filename;
18         unsigned long opt;
19         int status, src_fd, dst_fd;
20
21         opt = bb_getopt_ulflags(argc, argv, "cf");
22
23         /* Set input filename and number */
24         filename = argv[optind];
25         if ((filename) && (filename[0] != '-') && (filename[1] != '\0')) {
26                 /* Open input file */
27                 src_fd = xopen(filename, O_RDONLY);
28         } else {
29                 src_fd = STDIN_FILENO;
30                 filename = 0;
31         }
32
33         /* if called as bzcat force the stdout flag */
34         if ((opt & BUNZIP2_OPT_STDOUT) || bb_applet_name[2] == 'c')
35                 filename = 0;
36
37         /* Check that the input is sane.  */
38         if (isatty(src_fd) && (opt & BUNZIP2_OPT_FORCE) == 0) {
39                 bb_error_msg_and_die("Compressed data not read from terminal.  "
40                                 "Use -f to force it.");
41         }
42
43         if (filename) {
44                 struct stat stat_buf;
45                 /* extension = filename+strlen(filename)-4 is buggy:
46                  * strlen may be less than 4 */
47                 char *extension = strrchr(filename, '.');
48                 if (!extension || strcmp(extension, ".bz2") != 0) {
49                         bb_error_msg_and_die("invalid extension");
50                 }
51                 xstat(filename, &stat_buf);
52                 *extension = '\0';
53                 dst_fd = xopen3(filename, O_WRONLY | O_CREAT | O_TRUNC,
54                                 stat_buf.st_mode);
55         } else dst_fd = STDOUT_FILENO;
56         status = uncompressStream(src_fd, dst_fd);
57         if (filename) {
58                 if (!status) filename[strlen(filename)] = '.';
59                 if (unlink(filename) < 0) {
60                         bb_error_msg_and_die("cannot remove %s", filename);
61                 }
62         }
63
64         return status;
65 }