unlzma.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. /* Why our g[un]zip/bunzip2 are so ugly compared to this beauty? */
  11. #include "busybox.h"
  12. #include "unarchive.h"
  13. #define UNLZMA_OPT_STDOUT 1
  14. int unlzma_main(int argc, char **argv)
  15. {
  16. USE_DESKTOP(long long) int status;
  17. char *filename;
  18. unsigned opt;
  19. int src_fd, dst_fd;
  20. opt = getopt32(argc, argv, "c");
  21. /* Set input filename and number */
  22. filename = argv[optind];
  23. if (filename && (filename[0] != '-') && (filename[1] != '\0')) {
  24. /* Open input file */
  25. src_fd = xopen(filename, O_RDONLY);
  26. } else {
  27. src_fd = STDIN_FILENO;
  28. filename = 0;
  29. }
  30. /* if called as lzmacat force the stdout flag */
  31. if ((opt & UNLZMA_OPT_STDOUT) || applet_name[4] == 'c')
  32. filename = 0;
  33. if (filename) {
  34. struct stat stat_buf;
  35. /* bug: char *extension = filename + strlen(filename) - 5; */
  36. char *extension = strrchr(filename, '.');
  37. if (!extension || strcmp(extension, ".lzma") != 0) {
  38. bb_error_msg_and_die("invalid extension");
  39. }
  40. xstat(filename, &stat_buf);
  41. *extension = '\0';
  42. dst_fd = xopen3(filename, O_WRONLY | O_CREAT | O_TRUNC,
  43. stat_buf.st_mode);
  44. } else
  45. dst_fd = STDOUT_FILENO;
  46. status = unlzma(src_fd, dst_fd);
  47. if (filename) {
  48. if (status >= 0) /* if success delete src, else delete dst */
  49. filename[strlen(filename)] = '.';
  50. if (unlink(filename) < 0) {
  51. bb_error_msg_and_die("cannot remove %s", filename);
  52. }
  53. }
  54. return (status < 0);
  55. }