Standardize on the vi editing directives being on the first line.
[platform/upstream/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 <fcntl.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <unistd.h>
14
15 #include "busybox.h"
16 #include "unarchive.h"
17
18 #define BUNZIP2_OPT_STDOUT      1
19 #define BUNZIP2_OPT_FORCE       2
20
21 int bunzip2_main(int argc, char **argv)
22 {
23         char *filename;
24         unsigned long opt;
25         int status, src_fd, dst_fd;
26
27         opt = bb_getopt_ulflags(argc, argv, "cf");
28
29         /* Set input filename and number */
30         filename = argv[optind];
31         if ((filename) && (filename[0] != '-') && (filename[1] != '\0')) {
32                 /* Open input file */
33                 src_fd = bb_xopen(filename, O_RDONLY);
34         } else {
35                 src_fd = STDIN_FILENO;
36                 filename = 0;
37         }
38
39         /* if called as bzcat force the stdout flag */
40         if ((opt & BUNZIP2_OPT_STDOUT) || bb_applet_name[2] == 'c')
41                 filename = 0;
42
43         /* Check that the input is sane.  */
44         if (isatty(src_fd) && (opt & BUNZIP2_OPT_FORCE) == 0) {
45                 bb_error_msg_and_die("Compressed data not read from terminal.  Use -f to force it.");
46         }
47
48         if (filename) {
49                 struct stat stat_buf;
50                 char *extension=filename+strlen(filename)-4;
51                 if (strcmp(extension, ".bz2") != 0) {
52                         bb_error_msg_and_die("Invalid extension");
53                 }
54                 xstat(filename, &stat_buf);
55                 *extension=0;
56                 dst_fd = bb_xopen3(filename, O_WRONLY | O_CREAT, stat_buf.st_mode);
57         } else dst_fd = STDOUT_FILENO;
58         status = uncompressStream(src_fd, dst_fd);
59         if(filename) {
60                 if (!status) filename[strlen(filename)]='.';
61                 if (unlink(filename) < 0) {
62                         bb_error_msg_and_die("Couldn't remove %s", filename);
63                 }
64         }
65
66         return status;
67 }