*: style fixes. no code changes
[platform/upstream/busybox.git] / archival / bbunzip.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Common code for gunzip-like applets
4  *
5  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
6  */
7 #include "libbb.h"
8 #include "bb_archive.h"
9
10 enum {
11         OPT_STDOUT     = 1 << 0,
12         OPT_FORCE      = 1 << 1,
13         /* only some decompressors: */
14         OPT_VERBOSE    = 1 << 2,
15         OPT_DECOMPRESS = 1 << 3,
16         OPT_TEST       = 1 << 4,
17 };
18
19 static
20 int open_to_or_warn(int to_fd, const char *filename, int flags, int mode)
21 {
22         int fd = open3_or_warn(filename, flags, mode);
23         if (fd < 0) {
24                 return 1;
25         }
26         xmove_fd(fd, to_fd);
27         return 0;
28 }
29
30 char* FAST_FUNC append_ext(char *filename, const char *expected_ext)
31 {
32         return xasprintf("%s.%s", filename, expected_ext);
33 }
34
35 int FAST_FUNC bbunpack(char **argv,
36         IF_DESKTOP(long long) int FAST_FUNC (*unpacker)(unpack_info_t *info),
37         char* FAST_FUNC (*make_new_name)(char *filename, const char *expected_ext),
38         const char *expected_ext
39 )
40 {
41         struct stat stat_buf;
42         IF_DESKTOP(long long) int status;
43         char *filename, *new_name;
44         smallint exitcode = 0;
45         unpack_info_t info;
46
47         do {
48                 /* NB: new_name is *maybe* malloc'ed! */
49                 new_name = NULL;
50                 filename = *argv; /* can be NULL - 'streaming' bunzip2 */
51
52                 if (filename && LONE_DASH(filename))
53                         filename = NULL;
54
55                 /* Open src */
56                 if (filename) {
57                         if (stat(filename, &stat_buf) != 0) {
58                                 bb_simple_perror_msg(filename);
59  err:
60                                 exitcode = 1;
61                                 goto free_name;
62                         }
63                         if (open_to_or_warn(STDIN_FILENO, filename, O_RDONLY, 0))
64                                 goto err;
65                 }
66
67                 /* Special cases: test, stdout */
68                 if (option_mask32 & (OPT_STDOUT|OPT_TEST)) {
69                         if (option_mask32 & OPT_TEST)
70                                 if (open_to_or_warn(STDOUT_FILENO, bb_dev_null, O_WRONLY, 0))
71                                         goto err;
72                         filename = NULL;
73                 }
74
75                 /* Open dst if we are going to unpack to file */
76                 if (filename) {
77                         new_name = make_new_name(filename, expected_ext);
78                         if (!new_name) {
79                                 bb_error_msg("%s: unknown suffix - ignored", filename);
80                                 goto err;
81                         }
82
83                         /* -f: overwrite existing output files */
84                         if (option_mask32 & OPT_FORCE) {
85                                 unlink(new_name);
86                         }
87
88                         /* O_EXCL: "real" bunzip2 doesn't overwrite files */
89                         /* GNU gunzip does not bail out, but goes to next file */
90                         if (open_to_or_warn(STDOUT_FILENO, new_name, O_WRONLY | O_CREAT | O_EXCL,
91                                         stat_buf.st_mode))
92                                 goto err;
93                 }
94
95                 /* Check that the input is sane */
96                 if (isatty(STDIN_FILENO) && (option_mask32 & OPT_FORCE) == 0) {
97                         bb_error_msg_and_die("compressed data not read from terminal, "
98                                         "use -f to force it");
99                 }
100
101                 /* memset(&info, 0, sizeof(info)); */
102                 info.mtime = 0; /* so far it has one member only */
103                 status = unpacker(&info);
104                 if (status < 0)
105                         exitcode = 1;
106
107                 if (!(option_mask32 & OPT_STDOUT))
108                         xclose(STDOUT_FILENO); /* with error check! */
109
110                 if (filename) {
111                         char *del = new_name;
112                         if (status >= 0) {
113                                 /* TODO: restore other things? */
114                                 if (info.mtime) {
115                                         struct timeval times[2];
116
117                                         times[1].tv_sec = times[0].tv_sec = info.mtime;
118                                         times[1].tv_usec = times[0].tv_usec = 0;
119                                         /* Note: we closed it first.
120                                          * On some systems calling utimes
121                                          * then closing resets the mtime
122                                          * back to current time. */
123                                         utimes(new_name, times); /* ignoring errors */
124                                 }
125
126                                 /* Delete _compressed_ file */
127                                 del = filename;
128                                 /* restore extension (unless tgz -> tar case) */
129                                 if (new_name == filename)
130                                         filename[strlen(filename)] = '.';
131                         }
132                         xunlink(del);
133
134 #if 0 /* Currently buggy - wrong name: "a.gz: 261% - replaced with a.gz" */
135                         /* Extreme bloat for gunzip compat */
136                         if (ENABLE_DESKTOP && (option_mask32 & OPT_VERBOSE) && status >= 0) {
137                                 fprintf(stderr, "%s: %u%% - replaced with %s\n",
138                                         filename, (unsigned)(stat_buf.st_size*100 / (status+1)), new_name);
139                         }
140 #endif
141
142  free_name:
143                         if (new_name != filename)
144                                 free(new_name);
145                 }
146         } while (*argv && *++argv);
147
148         if (option_mask32 & OPT_STDOUT)
149                 xclose(STDOUT_FILENO); /* with error check! */
150
151         return exitcode;
152 }
153
154 #if ENABLE_UNCOMPRESS || ENABLE_BUNZIP2 || ENABLE_UNLZMA || ENABLE_UNXZ
155 static
156 char* FAST_FUNC make_new_name_generic(char *filename, const char *expected_ext)
157 {
158         char *extension = strrchr(filename, '.');
159         if (!extension || strcmp(extension + 1, expected_ext) != 0) {
160                 /* Mimic GNU gunzip - "real" bunzip2 tries to */
161                 /* unpack file anyway, to file.out */
162                 return NULL;
163         }
164         *extension = '\0';
165         return filename;
166 }
167 #endif
168
169
170 /*
171  * Uncompress applet for busybox (c) 2002 Glenn McGrath
172  *
173  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
174  */
175
176 //usage:#define uncompress_trivial_usage
177 //usage:       "[-cf] [FILE]..."
178 //usage:#define uncompress_full_usage "\n\n"
179 //usage:       "Decompress .Z file[s]\n"
180 //usage:     "\n        -c      Write to stdout"
181 //usage:     "\n        -f      Overwrite"
182
183 #if ENABLE_UNCOMPRESS
184 static
185 IF_DESKTOP(long long) int FAST_FUNC unpack_uncompress(unpack_info_t *info UNUSED_PARAM)
186 {
187         IF_DESKTOP(long long) int status = -1;
188
189         if ((xread_char(STDIN_FILENO) != 0x1f) || (xread_char(STDIN_FILENO) != 0x9d)) {
190                 bb_error_msg("invalid magic");
191         } else {
192                 status = unpack_Z_stream(STDIN_FILENO, STDOUT_FILENO);
193         }
194         return status;
195 }
196 int uncompress_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
197 int uncompress_main(int argc UNUSED_PARAM, char **argv)
198 {
199         getopt32(argv, "cf");
200         argv += optind;
201
202         return bbunpack(argv, unpack_uncompress, make_new_name_generic, "Z");
203 }
204 #endif
205
206
207 /*
208  * Gzip implementation for busybox
209  *
210  * Based on GNU gzip v1.2.4 Copyright (C) 1992-1993 Jean-loup Gailly.
211  *
212  * Originally adjusted for busybox by Sven Rudolph <sr1@inf.tu-dresden.de>
213  * based on gzip sources
214  *
215  * Adjusted further by Erik Andersen <andersen@codepoet.org> to support files as
216  * well as stdin/stdout, and to generally behave itself wrt command line
217  * handling.
218  *
219  * General cleanup to better adhere to the style guide and make use of standard
220  * busybox functions by Glenn McGrath
221  *
222  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
223  *
224  * gzip (GNU zip) -- compress files with zip algorithm and 'compress' interface
225  * Copyright (C) 1992-1993 Jean-loup Gailly
226  * The unzip code was written and put in the public domain by Mark Adler.
227  * Portions of the lzw code are derived from the public domain 'compress'
228  * written by Spencer Thomas, Joe Orost, James Woods, Jim McKie, Steve Davies,
229  * Ken Turkowski, Dave Mack and Peter Jannesen.
230  *
231  * See the license_msg below and the file COPYING for the software license.
232  * See the file algorithm.doc for the compression algorithms and file formats.
233  */
234
235 //usage:#define gunzip_trivial_usage
236 //usage:       "[-cft] [FILE]..."
237 //usage:#define gunzip_full_usage "\n\n"
238 //usage:       "Decompress FILEs (or stdin)\n"
239 //usage:     "\n        -c      Write to stdout"
240 //usage:     "\n        -f      Force"
241 //usage:     "\n        -t      Test file integrity"
242 //usage:
243 //usage:#define gunzip_example_usage
244 //usage:       "$ ls -la /tmp/BusyBox*\n"
245 //usage:       "-rw-rw-r--    1 andersen andersen   557009 Apr 11 10:55 /tmp/BusyBox-0.43.tar.gz\n"
246 //usage:       "$ gunzip /tmp/BusyBox-0.43.tar.gz\n"
247 //usage:       "$ ls -la /tmp/BusyBox*\n"
248 //usage:       "-rw-rw-r--    1 andersen andersen  1761280 Apr 14 17:47 /tmp/BusyBox-0.43.tar\n"
249 //usage:
250 //usage:#define zcat_trivial_usage
251 //usage:       "FILE"
252 //usage:#define zcat_full_usage "\n\n"
253 //usage:       "Decompress to stdout"
254
255 #if ENABLE_GUNZIP
256 static
257 char* FAST_FUNC make_new_name_gunzip(char *filename, const char *expected_ext UNUSED_PARAM)
258 {
259         char *extension = strrchr(filename, '.');
260
261         if (!extension)
262                 return NULL;
263
264         extension++;
265         if (strcmp(extension, "tgz" + 1) == 0
266 #if ENABLE_FEATURE_SEAMLESS_Z
267          || (extension[0] == 'Z' && extension[1] == '\0')
268 #endif
269         ) {
270                 extension[-1] = '\0';
271         } else if (strcmp(extension, "tgz") == 0) {
272                 filename = xstrdup(filename);
273                 extension = strrchr(filename, '.');
274                 extension[2] = 'a';
275                 extension[3] = 'r';
276         } else {
277                 return NULL;
278         }
279         return filename;
280 }
281 static
282 IF_DESKTOP(long long) int FAST_FUNC unpack_gunzip(unpack_info_t *info)
283 {
284         IF_DESKTOP(long long) int status = -1;
285
286         /* do the decompression, and cleanup */
287         if (xread_char(STDIN_FILENO) == 0x1f) {
288                 unsigned char magic2;
289
290                 magic2 = xread_char(STDIN_FILENO);
291                 if (ENABLE_FEATURE_SEAMLESS_Z && magic2 == 0x9d) {
292                         status = unpack_Z_stream(STDIN_FILENO, STDOUT_FILENO);
293                 } else if (magic2 == 0x8b) {
294                         status = unpack_gz_stream_with_info(STDIN_FILENO, STDOUT_FILENO, info);
295                 } else {
296                         goto bad_magic;
297                 }
298                 if (status < 0) {
299                         bb_error_msg("error inflating");
300                 }
301         } else {
302  bad_magic:
303                 bb_error_msg("invalid magic");
304                 /* status is still == -1 */
305         }
306         return status;
307 }
308 /*
309  * Linux kernel build uses gzip -d -n. We accept and ignore it.
310  * Man page says:
311  * -n --no-name
312  * gzip: do not save the original file name and time stamp.
313  * (The original name is always saved if the name had to be truncated.)
314  * gunzip: do not restore the original file name/time even if present
315  * (remove only the gzip suffix from the compressed file name).
316  * This option is the default when decompressing.
317  * -N --name
318  * gzip: always save the original file name and time stamp (this is the default)
319  * gunzip: restore the original file name and time stamp if present.
320  */
321 int gunzip_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
322 int gunzip_main(int argc UNUSED_PARAM, char **argv)
323 {
324         getopt32(argv, "cfvdtn");
325         argv += optind;
326         /* if called as zcat */
327         if (applet_name[1] == 'c')
328                 option_mask32 |= OPT_STDOUT;
329
330         return bbunpack(argv, unpack_gunzip, make_new_name_gunzip, /*unused:*/ NULL);
331 }
332 #endif
333
334
335 /*
336  * Modified for busybox by Glenn McGrath
337  * Added support output to stdout by Thomas Lundquist <thomasez@zelow.no>
338  *
339  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
340  */
341 //usage:#define bunzip2_trivial_usage
342 //usage:       "[-cf] [FILE]..."
343 //usage:#define bunzip2_full_usage "\n\n"
344 //usage:       "Decompress FILEs (or stdin)\n"
345 //usage:     "\n        -c      Write to stdout"
346 //usage:     "\n        -f      Force"
347 //usage:#define bzcat_trivial_usage
348 //usage:       "FILE"
349 //usage:#define bzcat_full_usage "\n\n"
350 //usage:       "Decompress to stdout"
351 //applet:IF_BUNZIP2(APPLET(bunzip2, BB_DIR_USR_BIN, BB_SUID_DROP))
352 //applet:IF_BUNZIP2(APPLET_ODDNAME(bzcat, bunzip2, BB_DIR_USR_BIN, BB_SUID_DROP, bzcat))
353 #if ENABLE_BUNZIP2
354 static
355 IF_DESKTOP(long long) int FAST_FUNC unpack_bunzip2(unpack_info_t *info UNUSED_PARAM)
356 {
357         return unpack_bz2_stream_prime(STDIN_FILENO, STDOUT_FILENO);
358 }
359 int bunzip2_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
360 int bunzip2_main(int argc UNUSED_PARAM, char **argv)
361 {
362         getopt32(argv, "cfvdt");
363         argv += optind;
364         if (applet_name[2] == 'c') /* bzcat */
365                 option_mask32 |= OPT_STDOUT;
366
367         return bbunpack(argv, unpack_bunzip2, make_new_name_generic, "bz2");
368 }
369 #endif
370
371
372 /*
373  * Small lzma deflate implementation.
374  * Copyright (C) 2006  Aurelien Jacobs <aurel@gnuage.org>
375  *
376  * Based on bunzip.c from busybox
377  *
378  * Licensed under GPLv2, see file LICENSE in this source tree.
379  */
380
381 //usage:#define unlzma_trivial_usage
382 //usage:       "[-cf] [FILE]..."
383 //usage:#define unlzma_full_usage "\n\n"
384 //usage:       "Decompress FILE (or stdin)\n"
385 //usage:     "\n        -c      Write to stdout"
386 //usage:     "\n        -f      Force"
387 //usage:
388 //usage:#define lzma_trivial_usage
389 //usage:       "-d [-cf] [FILE]..."
390 //usage:#define lzma_full_usage "\n\n"
391 //usage:       "Decompress FILE (or stdin)\n"
392 //usage:     "\n        -d      Decompress"
393 //usage:     "\n        -c      Write to stdout"
394 //usage:     "\n        -f      Force"
395 //usage:
396 //usage:#define lzcat_trivial_usage
397 //usage:       "FILE"
398 //usage:#define lzcat_full_usage "\n\n"
399 //usage:       "Decompress to stdout"
400 //usage:
401 //usage:#define unxz_trivial_usage
402 //usage:       "[-cf] [FILE]..."
403 //usage:#define unxz_full_usage "\n\n"
404 //usage:       "Decompress FILE (or stdin)\n"
405 //usage:     "\n        -c      Write to stdout"
406 //usage:     "\n        -f      Force"
407 //usage:
408 //usage:#define xz_trivial_usage
409 //usage:       "-d [-cf] [FILE]..."
410 //usage:#define xz_full_usage "\n\n"
411 //usage:       "Decompress FILE (or stdin)\n"
412 //usage:     "\n        -d      Decompress"
413 //usage:     "\n        -c      Write to stdout"
414 //usage:     "\n        -f      Force"
415 //usage:
416 //usage:#define xzcat_trivial_usage
417 //usage:       "FILE"
418 //usage:#define xzcat_full_usage "\n\n"
419 //usage:       "Decompress to stdout"
420
421 #if ENABLE_UNLZMA
422 static
423 IF_DESKTOP(long long) int FAST_FUNC unpack_unlzma(unpack_info_t *info UNUSED_PARAM)
424 {
425         return unpack_lzma_stream(STDIN_FILENO, STDOUT_FILENO);
426 }
427 int unlzma_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
428 int unlzma_main(int argc UNUSED_PARAM, char **argv)
429 {
430         IF_LZMA(int opts =) getopt32(argv, "cfvdt");
431 # if ENABLE_LZMA
432         /* lzma without -d or -t? */
433         if (applet_name[2] == 'm' && !(opts & (OPT_DECOMPRESS|OPT_TEST)))
434                 bb_show_usage();
435 # endif
436         /* lzcat? */
437         if (applet_name[2] == 'c')
438                 option_mask32 |= OPT_STDOUT;
439
440         argv += optind;
441         return bbunpack(argv, unpack_unlzma, make_new_name_generic, "lzma");
442 }
443 #endif
444
445
446 #if ENABLE_UNXZ
447 static
448 IF_DESKTOP(long long) int FAST_FUNC unpack_unxz(unpack_info_t *info UNUSED_PARAM)
449 {
450         struct {
451                 uint32_t v1;
452                 uint16_t v2;
453         } magic;
454         xread(STDIN_FILENO, &magic, 6);
455         if (magic.v1 != XZ_MAGIC1a || magic.v2 != XZ_MAGIC2a) {
456                 bb_error_msg("invalid magic");
457                 return -1;
458         }
459         return unpack_xz_stream(STDIN_FILENO, STDOUT_FILENO);
460 }
461 int unxz_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
462 int unxz_main(int argc UNUSED_PARAM, char **argv)
463 {
464         IF_XZ(int opts =) getopt32(argv, "cfvdt");
465 # if ENABLE_XZ
466         /* xz without -d or -t? */
467         if (applet_name[2] == '\0' && !(opts & (OPT_DECOMPRESS|OPT_TEST)))
468                 bb_show_usage();
469 # endif
470         /* xzcat? */
471         if (applet_name[2] == 'c')
472                 option_mask32 |= OPT_STDOUT;
473
474         argv += optind;
475         return bbunpack(argv, unpack_unxz, make_new_name_generic, "xz");
476 }
477 #endif