zlib.c 1.3 KB

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