lzma.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #include <lzma.h>
  2. #include <stdio.h>
  3. #include <linux/compiler.h>
  4. #include "util.h"
  5. #include "debug.h"
  6. #define BUFSIZE 8192
  7. static const char *lzma_strerror(lzma_ret ret)
  8. {
  9. switch ((int) ret) {
  10. case LZMA_MEM_ERROR:
  11. return "Memory allocation failed";
  12. case LZMA_OPTIONS_ERROR:
  13. return "Unsupported decompressor flags";
  14. case LZMA_FORMAT_ERROR:
  15. return "The input is not in the .xz format";
  16. case LZMA_DATA_ERROR:
  17. return "Compressed file is corrupt";
  18. case LZMA_BUF_ERROR:
  19. return "Compressed file is truncated or otherwise corrupt";
  20. default:
  21. return "Unknown error, possibly a bug";
  22. }
  23. }
  24. int lzma_decompress_to_file(const char *input, int output_fd)
  25. {
  26. lzma_action action = LZMA_RUN;
  27. lzma_stream strm = LZMA_STREAM_INIT;
  28. lzma_ret ret;
  29. int err = -1;
  30. u8 buf_in[BUFSIZE];
  31. u8 buf_out[BUFSIZE];
  32. FILE *infile;
  33. infile = fopen(input, "rb");
  34. if (!infile) {
  35. pr_err("lzma: fopen failed on %s: '%s'\n",
  36. input, strerror(errno));
  37. return -1;
  38. }
  39. ret = lzma_stream_decoder(&strm, UINT64_MAX, LZMA_CONCATENATED);
  40. if (ret != LZMA_OK) {
  41. pr_err("lzma: lzma_stream_decoder failed %s (%d)\n",
  42. lzma_strerror(ret), ret);
  43. goto err_fclose;
  44. }
  45. strm.next_in = NULL;
  46. strm.avail_in = 0;
  47. strm.next_out = buf_out;
  48. strm.avail_out = sizeof(buf_out);
  49. while (1) {
  50. if (strm.avail_in == 0 && !feof(infile)) {
  51. strm.next_in = buf_in;
  52. strm.avail_in = fread(buf_in, 1, sizeof(buf_in), infile);
  53. if (ferror(infile)) {
  54. pr_err("lzma: read error: %s\n", strerror(errno));
  55. goto err_fclose;
  56. }
  57. if (feof(infile))
  58. action = LZMA_FINISH;
  59. }
  60. ret = lzma_code(&strm, action);
  61. if (strm.avail_out == 0 || ret == LZMA_STREAM_END) {
  62. ssize_t write_size = sizeof(buf_out) - strm.avail_out;
  63. if (writen(output_fd, buf_out, write_size) != write_size) {
  64. pr_err("lzma: write error: %s\n", strerror(errno));
  65. goto err_fclose;
  66. }
  67. strm.next_out = buf_out;
  68. strm.avail_out = sizeof(buf_out);
  69. }
  70. if (ret != LZMA_OK) {
  71. if (ret == LZMA_STREAM_END)
  72. break;
  73. pr_err("lzma: failed %s\n", lzma_strerror(ret));
  74. goto err_fclose;
  75. }
  76. }
  77. err = 0;
  78. err_fclose:
  79. fclose(infile);
  80. return err;
  81. }