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