Decompress gzip data into a malloc'd buffer. Returns NULL on failure. * *out_total receives the decompressed size. Caller must free the result. */
| 7046 | /* Decompress gzip data into a malloc'd buffer. Returns NULL on failure. |
| 7047 | * *out_total receives the decompressed size. Caller must free the result. */ |
| 7048 | static unsigned char *gzip_decompress(const unsigned char *data, int data_len, size_t *out_total) { |
| 7049 | z_stream strm = {0}; |
| 7050 | unsigned char *mutable_data; |
| 7051 | memcpy(&mutable_data, &data, sizeof(data)); |
| 7052 | strm.next_in = mutable_data; |
| 7053 | strm.avail_in = (unsigned int)data_len; |
| 7054 | |
| 7055 | if (inflateInit2(&strm, 16 + MAX_WBITS) != Z_OK) { |
| 7056 | return NULL; |
| 7057 | } |
| 7058 | |
| 7059 | size_t buf_cap = (size_t)data_len * DECOMP_FACTOR; |
| 7060 | if (buf_cap < CLI_BUF_4K) { |
| 7061 | buf_cap = CLI_BUF_4K; |
| 7062 | } |
| 7063 | if (buf_cap > DECOMPRESS_MAX_BYTES) { |
| 7064 | buf_cap = DECOMPRESS_MAX_BYTES; |
| 7065 | } |
| 7066 | unsigned char *decompressed = malloc(buf_cap); |
| 7067 | if (!decompressed) { |
| 7068 | inflateEnd(&strm); |
| 7069 | return NULL; |
| 7070 | } |
| 7071 | |
| 7072 | size_t total = 0; |
| 7073 | int ret; |
| 7074 | do { |
| 7075 | if (total >= buf_cap) { |
| 7076 | size_t new_cap = buf_cap * GROWTH_FACTOR; |
| 7077 | if (new_cap > DECOMPRESS_MAX_BYTES) { |
| 7078 | free(decompressed); |
| 7079 | inflateEnd(&strm); |
| 7080 | return NULL; |
| 7081 | } |
| 7082 | unsigned char *nb = realloc(decompressed, new_cap); |
| 7083 | if (!nb) { |
| 7084 | free(decompressed); |
| 7085 | inflateEnd(&strm); |
| 7086 | return NULL; |
| 7087 | } |
| 7088 | decompressed = nb; |
| 7089 | buf_cap = new_cap; |
| 7090 | } |
| 7091 | strm.next_out = decompressed + total; |
| 7092 | strm.avail_out = (unsigned int)(buf_cap - total); |
| 7093 | ret = inflate(&strm, Z_NO_FLUSH); |
| 7094 | total = buf_cap - strm.avail_out; |
| 7095 | } while (ret == Z_OK); |
| 7096 | |
| 7097 | inflateEnd(&strm); |
| 7098 | |
| 7099 | if (ret != Z_STREAM_END) { |
| 7100 | free(decompressed); |
| 7101 | return NULL; |
| 7102 | } |
| 7103 | *out_total = total; |
| 7104 | return decompressed; |
| 7105 | } |
no outgoing calls
no test coverage detected