zlib.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <fcntl.h>
  3. #include <stdio.h>
  4. #include <unistd.h>
  5. #include <sys/stat.h>
  6. #include <sys/mman.h>
  7. #include <zlib.h>
  8. #include "util/compress.h"
  9. #include "util/util.h"
  10. #include "util/debug.h"
  11. #define CHUNK_SIZE 16384
  12. int gzip_decompress_to_file(const char *input, int output_fd)
  13. {
  14. int ret = Z_STREAM_ERROR;
  15. int input_fd;
  16. void *ptr;
  17. int len;
  18. struct stat stbuf;
  19. unsigned char buf[CHUNK_SIZE];
  20. z_stream zs = {
  21. .zalloc = Z_NULL,
  22. .zfree = Z_NULL,
  23. .opaque = Z_NULL,
  24. .avail_in = 0,
  25. .next_in = Z_NULL,
  26. };
  27. input_fd = open(input, O_RDONLY);
  28. if (input_fd < 0)
  29. return -1;
  30. if (fstat(input_fd, &stbuf) < 0)
  31. goto out_close;
  32. ptr = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, input_fd, 0);
  33. if (ptr == MAP_FAILED)
  34. goto out_close;
  35. if (inflateInit2(&zs, 16 + MAX_WBITS) != Z_OK)
  36. goto out_unmap;
  37. zs.next_in = ptr;
  38. zs.avail_in = stbuf.st_size;
  39. do {
  40. zs.next_out = buf;
  41. zs.avail_out = CHUNK_SIZE;
  42. ret = inflate(&zs, Z_NO_FLUSH);
  43. switch (ret) {
  44. case Z_NEED_DICT:
  45. ret = Z_DATA_ERROR;
  46. /* fall through */
  47. case Z_DATA_ERROR:
  48. case Z_MEM_ERROR:
  49. goto out;
  50. default:
  51. break;
  52. }
  53. len = CHUNK_SIZE - zs.avail_out;
  54. if (writen(output_fd, buf, len) != len) {
  55. ret = Z_DATA_ERROR;
  56. goto out;
  57. }
  58. } while (ret != Z_STREAM_END);
  59. out:
  60. inflateEnd(&zs);
  61. out_unmap:
  62. munmap(ptr, stbuf.st_size);
  63. out_close:
  64. close(input_fd);
  65. return ret == Z_STREAM_END ? 0 : -1;
  66. }