lzma.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. u8 buf_in[BUFSIZE];
  30. u8 buf_out[BUFSIZE];
  31. FILE *infile;
  32. infile = fopen(input, "rb");
  33. if (!infile) {
  34. pr_err("lzma: fopen failed on %s: '%s'\n",
  35. input, strerror(errno));
  36. return -1;
  37. }
  38. ret = lzma_stream_decoder(&strm, UINT64_MAX, LZMA_CONCATENATED);
  39. if (ret != LZMA_OK) {
  40. pr_err("lzma: lzma_stream_decoder failed %s (%d)\n",
  41. lzma_strerror(ret), ret);
  42. return -1;
  43. }
  44. strm.next_in = NULL;
  45. strm.avail_in = 0;
  46. strm.next_out = buf_out;
  47. strm.avail_out = sizeof(buf_out);
  48. while (1) {
  49. if (strm.avail_in == 0 && !feof(infile)) {
  50. strm.next_in = buf_in;
  51. strm.avail_in = fread(buf_in, 1, sizeof(buf_in), infile);
  52. if (ferror(infile)) {
  53. pr_err("lzma: read error: %s\n", strerror(errno));
  54. return -1;
  55. }
  56. if (feof(infile))
  57. action = LZMA_FINISH;
  58. }
  59. ret = lzma_code(&strm, action);
  60. if (strm.avail_out == 0 || ret == LZMA_STREAM_END) {
  61. ssize_t write_size = sizeof(buf_out) - strm.avail_out;
  62. if (writen(output_fd, buf_out, write_size) != write_size) {
  63. pr_err("lzma: write error: %s\n", strerror(errno));
  64. return -1;
  65. }
  66. strm.next_out = buf_out;
  67. strm.avail_out = sizeof(buf_out);
  68. }
  69. if (ret != LZMA_OK) {
  70. if (ret == LZMA_STREAM_END)
  71. return 0;
  72. pr_err("lzma: failed %s\n", lzma_strerror(ret));
  73. return -1;
  74. }
  75. }
  76. fclose(infile);
  77. return 0;
  78. }