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_7z.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 2023 Saso Kiselkov. All rights reserved.
17 */
18
19#include <string.h>
20#include <stdlib.h>
21
22#include <7z.h>
23#include <7zAlloc.h>
24#include <7zBuf.h>
25#include <7zCrc.h>
26#include <7zFile.h>
27#include <7zVersion.h>
28
29#include "acfutils/assert.h"
30#include "acfutils/compress.h"
31#include "acfutils/safe_alloc.h"
32
40bool_t
41test_7z(const void *in_buf, size_t len)
42{
43 static const uint8_t magic[] = { '7', 'z', 0xBC, 0xAF, 0x27, 0x1C };
44 return (len >= sizeof (magic) &&
45 memcmp(in_buf, magic, sizeof (magic)) == 0);
46}
47
60void *
61decompress_7z(const char *filename, size_t *out_len)
62{
63#define kInputBufSize ((size_t)1 << 18)
64 void *out_buf = NULL;
65 static const ISzAlloc g_Alloc = { SzAlloc, SzFree };
66 ISzAlloc allocImp = g_Alloc;
67 ISzAlloc allocTempImp = g_Alloc;
68 CFileInStream archiveStream;
69 CLookToRead2 lookStream;
70 CSzArEx db;
71 SRes res;
72 UInt32 blockIndex = 0xFFFFFFFF;
73 Byte *outBuffer = NULL;
74 size_t outBufferSize = 0;
75 size_t offset = 0;
76 size_t outSizeProcessed = 0;
77
78 if (InFile_Open(&archiveStream.file, filename))
79 return (NULL);
80
81 FileInStream_CreateVTable(&archiveStream);
82 LookToRead2_CreateVTable(&lookStream, False);
83 lookStream.buf = ISzAlloc_Alloc(&allocImp, kInputBufSize);
84 lookStream.bufSize = kInputBufSize;
85 lookStream.realStream = &archiveStream.vt;
86 LookToRead2_INIT(&lookStream);
87
88 CrcGenerateTable();
89 SzArEx_Init(&db);
90 res = SzArEx_Open(&db, &lookStream.vt, &allocImp, &allocTempImp);
91 if (res != SZ_OK)
92 goto out;
93
94 res = SzArEx_Extract(&db, &lookStream.vt, 0, &blockIndex, &outBuffer,
95 &outBufferSize, &offset, &outSizeProcessed, &allocImp,
96 &allocTempImp);
97 if (res != SZ_OK)
98 goto out;
99
100 *out_len = outBufferSize;
101 out_buf = safe_malloc(outBufferSize);
102 memcpy(out_buf, outBuffer, outBufferSize);
103
104out:
105 ISzAlloc_Free(&allocImp, outBuffer);
106 SzArEx_Free(&db, &allocImp);
107 ISzAlloc_Free(&allocImp, lookStream.buf);
108
109 File_Close(&archiveStream.file);
110
111 return (out_buf);
112}
void * decompress_7z(const char *filename, size_t *out_len)
Definition compress_7z.c:61
bool_t test_7z(const void *in_buf, size_t len)
Definition compress_7z.c:41
static void * safe_malloc(size_t size)
Definition safe_alloc.h:56