Upgrade netcat a lot. Make -e able to take the rest of the command line as
[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 #include <fcntl.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <unistd.h>
16
17 #include "busybox.h"
18 #include "unarchive.h"
19
20 #define UNLZMA_OPT_STDOUT       1
21
22 int unlzma_main(int argc, char **argv)
23 {
24         char *filename;
25         unsigned long opt;
26         int status, src_fd, dst_fd;
27
28         opt = bb_getopt_ulflags(argc, argv, "c");
29
30         /* Set input filename and number */
31         filename = argv[optind];
32         if ((filename) && (filename[0] != '-') && (filename[1] != '\0')) {
33                 /* Open input file */
34                 src_fd = bb_xopen(filename, O_RDONLY);
35         } else {
36                 src_fd = STDIN_FILENO;
37                 filename = 0;
38         }
39
40         /* if called as lzmacat force the stdout flag */
41         if ((opt & UNLZMA_OPT_STDOUT) || bb_applet_name[4] == 'c')
42                 filename = 0;
43
44         if (filename) {
45                 struct stat stat_buf;
46                 char *extension = filename + strlen(filename) - 5;
47
48                 if (strcmp(extension, ".lzma") != 0) {
49                         bb_error_msg_and_die("Invalid extension");
50                 }
51                 xstat(filename, &stat_buf);
52                 *extension = 0;
53                 dst_fd = bb_xopen3(filename, O_WRONLY | O_CREAT, stat_buf.st_mode);
54         } else
55                 dst_fd = STDOUT_FILENO;
56         status = unlzma(src_fd, dst_fd);
57         if (filename) {
58                 if (!status)
59                         filename[strlen(filename)] = '.';
60                 if (unlink(filename) < 0) {
61                         bb_error_msg_and_die("Couldn't remove %s", filename);
62                 }
63         }
64
65         return status;
66 }
67