ifupdown: save some 100+ bytes of code in addstr()
[oweals/busybox.git] / archival / unlzma.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Small lzma deflate implementation.
4  * Copyright (C) 2006  Aurelien Jacobs <aurel@gnuage.org>
5  *
6  * Based on bunzip.c from busybox
7  *
8  * Licensed under GPL v2, see file LICENSE in this tarball for details.
9  */
10
11 /* Why our g[un]zip/bunzip2 are so ugly compared to this beauty? */
12
13 #include "busybox.h"
14 #include "unarchive.h"
15
16 #define UNLZMA_OPT_STDOUT       1
17
18 int unlzma_main(int argc, char **argv)
19 {
20         USE_DESKTOP(long long) int status;
21         char *filename;
22         unsigned opt;
23         int src_fd, dst_fd;
24
25         opt = getopt32(argc, argv, "c");
26
27         /* Set input filename and number */
28         filename = argv[optind];
29         if (filename && (filename[0] != '-') && (filename[1] != '\0')) {
30                 /* Open input file */
31                 src_fd = xopen(filename, O_RDONLY);
32         } else {
33                 src_fd = STDIN_FILENO;
34                 filename = 0;
35         }
36
37         /* if called as lzmacat force the stdout flag */
38         if ((opt & UNLZMA_OPT_STDOUT) || applet_name[4] == 'c')
39                 filename = 0;
40
41         if (filename) {
42                 struct stat stat_buf;
43                 /* bug: char *extension = filename + strlen(filename) - 5; */
44                 char *extension = strrchr(filename, '.');
45                 if (!extension || strcmp(extension, ".lzma") != 0) {
46                         bb_error_msg_and_die("invalid extension");
47                 }
48                 xstat(filename, &stat_buf);
49                 *extension = '\0';
50                 dst_fd = xopen3(filename, O_WRONLY | O_CREAT | O_TRUNC,
51                                 stat_buf.st_mode);
52         } else
53                 dst_fd = STDOUT_FILENO;
54         status = unlzma(src_fd, dst_fd);
55         if (filename) {
56                 if (status >= 0) /* if success delete src, else delete dst */
57                         filename[strlen(filename)] = '.';
58                 if (unlink(filename) < 0) {
59                         bb_error_msg_and_die("cannot remove %s", filename);
60                 }
61         }
62
63         return (status < 0);
64 }