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