libacfutils
A general purpose library of utility functions designed to make it easier to develop addons for the X-Plane flight simulator.
Loading...
Searching...
No Matches
compress_zip.c
1/*
2 * CDDL HEADER START
3 *
4 * This file and its contents are supplied under the terms of the
5 * Common Development and Distribution License ("CDDL"), version 1.0.
6 * You may only use this file in accordance with the terms of version
7 * 1.0 of the CDDL.
8 *
9 * A full copy of the text of the CDDL should have accompanied this
10 * source. A copy of the CDDL is also available via the Internet at
11 * http://www.illumos.org/license/CDDL.
12 *
13 * CDDL HEADER END
14*/
15/*
16 * Copyright 2018 Saso Kiselkov. All rights reserved.
17 */
18
19#include <string.h>
20
21#include "acfutils/assert.h"
22#include "acfutils/compress.h"
23#include "acfutils/helpers.h"
24#include "acfutils/safe_alloc.h"
25
26#include "zip/zip.h"
27
28typedef struct {
29 void *buf;
30 size_t len;
31} outbuf_t;
32
33static size_t
34read_cb(void *arg, uint64_t offset, const void *data, size_t size)
35{
36 ASSERT(arg != NULL);
37 outbuf_t *buf = arg;
38 UNUSED(offset);
39 ASSERT(data != NULL || size != 0);
40
41 buf->buf = safe_realloc(buf->buf, buf->len + size);
42 memcpy(buf->buf + buf->len, data, size);
43 buf->len += size;
44
45 return (size);
46}
47
48void *
49decompress_zip(void *in_buf, size_t len, size_t *out_len)
50{
51 ASSERT(in_buf != NULL || len == 0);
52 ASSERT(out_len != NULL);
53 *out_len = 0;
54 if (len == 0) {
55 return (NULL);
56 }
57
58 struct zip_t *zip = zip_stream_open(in_buf, len, 0, 'r');
59 if (zip == NULL) {
60 return (NULL);
61 }
62 if (zip_entries_total(zip) <= 0) {
63 goto errout;
64 }
65 outbuf_t buf = {};
66 if (zip_entry_extract(zip, read_cb, &buf) != 0) {
67 goto errout;
68 }
70
71 *out_len = buf.len;
72 return (buf.buf);
73
74errout:
76 if (buf.buf != NULL) {
77 free(buf.buf);
78 }
79 return (NULL);
80}
#define ASSERT(x)
Definition assert.h:208
#define UNUSED(x)
Definition core.h:103
void zip_stream_close(struct zip_t *zip)
Definition zip.c:1898
struct zip_t * zip_stream_open(const char *stream, size_t size, int level, char mode)
Definition zip.c:1829
ssize_t zip_entries_total(struct zip_t *zip)
Definition zip.c:1730
static void * safe_realloc(void *oldptr, size_t size)
Definition safe_alloc.h:86
Definition zip.c:98