2
* Copyright (C) 2009 Sourcefire, Inc.
6
* This program is free software; you can redistribute it and/or modify
7
* it under the terms of the GNU General Public License version 2 as
8
* published by the Free Software Foundation.
10
* This program is distributed in the hope that it will be useful,
11
* but WITHOUT ANY WARRANTY; without even the implied warranty of
12
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
* GNU General Public License for more details.
15
* You should have received a copy of the GNU General Public License
16
* along with this program; if not, write to the Free Software
17
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21
/* zlib-alike state interface to LZMA */
24
#include "clamav-config.h"
27
#include "lzma_iface.h"
29
void *__lzma_wrap_alloc(void *unused, size_t size) {
31
return cli_malloc(size);
33
void __lzma_wrap_free(void *unused, void *freeme) {
37
static ISzAlloc g_Alloc = { __lzma_wrap_alloc, __lzma_wrap_free };
40
static unsigned char lzma_getbyte(struct CLI_LZMA *L, int *fail) {
42
if(!L->next_in || !L->avail_in) {
54
int cli_LzmaInit(struct CLI_LZMA *L, uint64_t size_override) {
58
L->p_cnt = LZMA_PROPS_SIZE;
60
L->usize = size_override;
64
} else if(size_override)
65
cli_warnmsg("cli_LzmaInit: ignoring late size override\n");
67
if(L->freeme) return LZMA_RESULT_OK;
70
L->header[LZMA_PROPS_SIZE - L->p_cnt] = lzma_getbyte(L, &fail);
71
if(fail) return LZMA_RESULT_OK;
76
uint64_t c = (uint64_t)lzma_getbyte(L, &fail);
77
if(fail) return LZMA_RESULT_OK;
78
L->usize = c << (8 * (8 - L->s_cnt));
82
LzmaDec_Construct(&L->state);
83
if(LzmaDec_Allocate(&L->state, L->header, LZMA_PROPS_SIZE, &g_Alloc) != SZ_OK)
84
return LZMA_RESULT_DATA_ERROR;
85
LzmaDec_Init(&L->state);
88
return LZMA_RESULT_OK;
92
void cli_LzmaShutdown(struct CLI_LZMA *L) {
94
LzmaDec_Free(&L->state, &g_Alloc);
99
int cli_LzmaDecode(struct CLI_LZMA *L) {
101
SizeT outbytes, inbytes;
103
ELzmaFinishMode finish;
105
if(!L->freeme) return cli_LzmaInit(L, 0);
107
inbytes = L->avail_in;
108
if(~L->usize && L->avail_out > L->usize) {
110
finish = LZMA_FINISH_END;
112
outbytes = L->avail_out;
113
finish = LZMA_FINISH_ANY;
115
res = LzmaDec_DecodeToBuf(&L->state, L->next_out, &outbytes, L->next_in, &inbytes, finish, &status);
116
L->avail_in -= inbytes;
117
L->next_in += inbytes;
118
L->avail_out -= outbytes;
119
L->next_out += outbytes;
120
if(~L->usize) L->usize -= outbytes;
122
return LZMA_RESULT_DATA_ERROR;
123
if(!L->usize || status == LZMA_STATUS_FINISHED_WITH_MARK)
124
return LZMA_STREAM_END;
125
return LZMA_RESULT_OK;