Coverage Report

Created: 2026-10-28 07:26

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libzip/lib/zip_algorithm_xz.c
Line
Count
Source
1
/*
2
  zip_algorithm_xz.c -- LZMA/XZ (de)compression routines
3
  Bazed on zip_algorithm_deflate.c -- deflate (de)compression routines
4
  Copyright (C) 2017-2025 Dieter Baron and Thomas Klausner
5
6
  This file is part of libzip, a library to manipulate ZIP archives.
7
  The authors can be contacted at <info@libzip.org>
8
9
  Redistribution and use in source and binary forms, with or without
10
  modification, are permitted provided that the following conditions
11
  are met:
12
  1. Redistributions of source code must retain the above copyright
13
     notice, this list of conditions and the following disclaimer.
14
  2. Redistributions in binary form must reproduce the above copyright
15
     notice, this list of conditions and the following disclaimer in
16
     the documentation and/or other materials provided with the
17
     distribution.
18
  3. The names of the authors may not be used to endorse or promote
19
     products derived from this software without specific prior
20
     written permission.
21
22
  THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS
23
  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
24
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25
  ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
26
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27
  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
28
  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
30
  IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
31
  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
32
  IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33
*/
34
35
#include "zipint.h"
36
37
#include <limits.h>
38
#include <lzma.h>
39
#include <stdlib.h>
40
#include <string.h>
41
#include <zlib.h>
42
43
enum header_state {
44
    INCOMPLETE,
45
    OUTPUT,
46
    DONE
47
};
48
49
0
#define HEADER_BYTES_ZIP 9
50
0
#define HEADER_MAGIC_LENGTH 4
51
#define HEADER_MAGIC1_OFFSET 0
52
0
#define HEADER_MAGIC2_OFFSET 2
53
0
#define HEADER_SIZE_OFFSET 9
54
0
#define HEADER_SIZE_LENGTH 8
55
0
#define HEADER_PARAMETERS_LENGTH 5
56
0
#define HEADER_LZMA_ALONE_LENGTH (HEADER_PARAMETERS_LENGTH + HEADER_SIZE_LENGTH)
57
58
struct ctx {
59
    zip_error_t *error;
60
    bool compress;
61
    zip_uint32_t compression_flags;
62
    bool end_of_input;
63
    lzma_stream zstr;
64
    zip_uint16_t method;
65
    /* header member is used for converting from zip to "lzma alone"
66
     * format
67
     *
68
     * "lzma alone" file format starts with:
69
     * 5 bytes lzma parameters
70
     * 8 bytes uncompressed size
71
     * compressed data
72
     *
73
     * zip archive on-disk format starts with
74
     * 4 bytes magic (first two bytes vary, e.g. 0x0914 or 0x1002, next bytes are 0x0500)
75
     * 5 bytes lzma parameters
76
     * compressed data
77
     *
78
     * we read the data into a header of the form
79
     * 4 bytes magic
80
     * 5 bytes lzma parameters
81
     * 8 bytes uncompressed size
82
     */
83
    zip_uint8_t header[HEADER_MAGIC_LENGTH + HEADER_LZMA_ALONE_LENGTH];
84
    zip_uint8_t header_bytes_offset;
85
    enum header_state header_state;
86
    zip_uint64_t uncompresssed_size;
87
};
88
89
90
0
static zip_uint64_t maximum_compressed_size(zip_uint64_t uncompressed_size) {
91
    /*
92
     According to https://sourceforge.net/p/sevenzip/discussion/45797/thread/b6bd62f8/
93
94
     1) you can use
95
     outSize = 1.10 * originalSize + 64 KB.
96
     in most cases outSize is less then 1.02 from originalSize.
97
     2) You can try LZMA2, where
98
     outSize can be = 1.001 * originalSize + 1 KB.
99
     */
100
    /* 13 bytes added for lzma alone header */
101
0
    zip_uint64_t compressed_size = (zip_uint64_t)((double)uncompressed_size * 1.1) + 64 * 1024 + 13;
102
103
0
    if (compressed_size < uncompressed_size) {
104
0
        return ZIP_UINT64_MAX;
105
0
    }
106
0
    return compressed_size;
107
0
}
108
109
110
0
static void *allocate(bool compress, zip_uint32_t compression_flags, zip_error_t *error, zip_uint16_t method) {
111
0
    struct ctx *ctx;
112
113
0
    if ((ctx = (struct ctx *)malloc(sizeof(*ctx))) == NULL) {
114
0
        zip_error_set(error, ZIP_ER_MEMORY, 0);
115
0
        return NULL;
116
0
    }
117
118
0
    ctx->error = error;
119
0
    ctx->compress = compress;
120
0
    if (compression_flags <= 9) {
121
0
        ctx->compression_flags = compression_flags;
122
0
    }
123
0
    else {
124
0
        ctx->compression_flags = 6; /* default value */
125
0
    }
126
0
    ctx->compression_flags |= LZMA_PRESET_EXTREME;
127
0
    ctx->end_of_input = false;
128
0
    memset(ctx->header, 0, sizeof(ctx->header));
129
0
    ctx->header_bytes_offset = 0;
130
0
    if (method == ZIP_CM_LZMA) {
131
0
        ctx->header_state = INCOMPLETE;
132
0
    }
133
0
    else {
134
0
        ctx->header_state = DONE;
135
0
    }
136
0
    memset(&ctx->zstr, 0, sizeof(ctx->zstr));
137
0
    ctx->method = method;
138
0
    return ctx;
139
0
}
140
141
142
0
static void *compress_allocate(zip_uint16_t method, zip_uint32_t compression_flags, zip_error_t *error) {
143
0
    return allocate(true, compression_flags, error, method);
144
0
}
145
146
147
0
static void *decompress_allocate(zip_uint16_t method, zip_uint32_t compression_flags, zip_error_t *error) {
148
0
    return allocate(false, compression_flags, error, method);
149
0
}
150
151
152
0
static void deallocate(void *ud) {
153
0
    struct ctx *ctx = (struct ctx *)ud;
154
0
    free(ctx);
155
0
}
156
157
158
0
static zip_uint16_t general_purpose_bit_flags(void *ud) {
159
0
    struct ctx *ctx = (struct ctx *)ud;
160
161
0
    if (!ctx->compress) {
162
0
        return 0;
163
0
    }
164
165
0
    if (ctx->method == ZIP_CM_LZMA) {
166
        /* liblzma always returns an EOS/EOPM marker, see
167
         * https://sourceforge.net/p/lzmautils/discussion/708858/thread/84c5dbb9/#a5e4/3764 */
168
0
        return 1 << 1;
169
0
    }
170
0
    return 0;
171
0
}
172
173
0
static int map_error(lzma_ret ret) {
174
0
    switch (ret) {
175
0
    case LZMA_DATA_ERROR:
176
0
    case LZMA_UNSUPPORTED_CHECK:
177
0
        return ZIP_ER_COMPRESSED_DATA;
178
179
0
    case LZMA_MEM_ERROR:
180
0
    case LZMA_MEMLIMIT_ERROR:
181
0
        return ZIP_ER_MEMORY;
182
183
0
    case LZMA_OPTIONS_ERROR:
184
0
        return ZIP_ER_INVAL;
185
186
0
    default:
187
0
        return ZIP_ER_INTERNAL;
188
0
    }
189
0
}
190
191
192
0
static bool start(void *ud, zip_stat_t *st, zip_file_attributes_t *attributes) {
193
0
    struct ctx *ctx = (struct ctx *)ud;
194
0
    lzma_ret ret;
195
196
0
    lzma_options_lzma opt_lzma;
197
0
    lzma_lzma_preset(&opt_lzma, ctx->compression_flags);
198
0
    lzma_filter filters[] = {
199
0
        {.id = (ctx->method == ZIP_CM_LZMA ? LZMA_FILTER_LZMA1 : LZMA_FILTER_LZMA2), .options = &opt_lzma},
200
0
        {.id = LZMA_VLI_UNKNOWN, .options = NULL},
201
0
    };
202
203
0
    ctx->zstr.avail_in = 0;
204
0
    ctx->zstr.next_in = NULL;
205
0
    ctx->zstr.avail_out = 0;
206
0
    ctx->zstr.next_out = NULL;
207
208
0
    if (ctx->compress) {
209
0
        if (ctx->method == ZIP_CM_LZMA) {
210
0
            ret = lzma_alone_encoder(&ctx->zstr, filters[0].options);
211
0
        }
212
0
        else {
213
0
            ret = lzma_stream_encoder(&ctx->zstr, filters, LZMA_CHECK_CRC64);
214
0
        }
215
0
    }
216
0
    else {
217
0
        if (ctx->method == ZIP_CM_LZMA) {
218
0
            ret = lzma_alone_decoder(&ctx->zstr, LZMA_WINDOW_LIMIT);
219
0
        }
220
0
        else {
221
0
            ret = lzma_stream_decoder(&ctx->zstr, LZMA_WINDOW_LIMIT, LZMA_CONCATENATED);
222
0
        }
223
0
    }
224
225
0
    if (ret != LZMA_OK) {
226
0
        zip_error_set(ctx->error, map_error(ret), 0);
227
0
        return false;
228
0
    }
229
230
    /* If general purpose bits 1 & 2 are both zero, write real uncompressed size in header. */
231
0
    if ((attributes->valid & ZIP_FILE_ATTRIBUTES_GENERAL_PURPOSE_BIT_FLAGS) && (attributes->general_purpose_bit_mask & 0x6) == 0x6 && (attributes->general_purpose_bit_flags & 0x06) == 0 && (st->valid & ZIP_STAT_SIZE)) {
232
0
        ctx->uncompresssed_size = st->size;
233
0
    }
234
0
    else {
235
0
        ctx->uncompresssed_size = ZIP_UINT64_MAX;
236
0
    }
237
238
0
    return true;
239
0
}
240
241
242
0
static bool end(void *ud) {
243
0
    struct ctx *ctx = (struct ctx *)ud;
244
245
0
    lzma_end(&ctx->zstr);
246
0
    return true;
247
0
}
248
249
250
0
static bool input(void *ud, zip_uint8_t *data, zip_uint64_t length) {
251
0
    struct ctx *ctx = (struct ctx *)ud;
252
253
0
    if (length > UINT_MAX || ctx->zstr.avail_in > 0) {
254
0
        zip_error_set(ctx->error, ZIP_ER_INVAL, 0);
255
0
        return false;
256
0
    }
257
258
    /* For decompression of LZMA1: Have we read the full "lzma alone" header yet? */
259
0
    if (ctx->method == ZIP_CM_LZMA && !ctx->compress && ctx->header_state == INCOMPLETE) {
260
        /* if not, get more of the data */
261
0
        zip_uint8_t got = (zip_uint8_t)ZIP_MIN(HEADER_BYTES_ZIP - ctx->header_bytes_offset, length);
262
0
        (void)memcpy_s(ctx->header + ctx->header_bytes_offset, sizeof(ctx->header) - ctx->header_bytes_offset, data, got);
263
0
        ctx->header_bytes_offset += got;
264
0
        length -= got;
265
0
        data += got;
266
        /* Do we have a complete header now? */
267
0
        if (ctx->header_bytes_offset == HEADER_BYTES_ZIP) {
268
0
            Bytef empty_buffer[1];
269
0
            zip_buffer_t *buffer;
270
            /* check magic */
271
0
            if (ctx->header[HEADER_MAGIC2_OFFSET] != 0x05 || ctx->header[HEADER_MAGIC2_OFFSET + 1] != 0x00) {
272
                /* magic does not match */
273
0
                zip_error_set(ctx->error, ZIP_ER_COMPRESSED_DATA, 0);
274
0
                return false;
275
0
            }
276
            /* set size of uncompressed data in "lzma alone" header to "unknown" */
277
0
            if ((buffer = _zip_buffer_new(ctx->header + HEADER_SIZE_OFFSET, HEADER_SIZE_LENGTH)) == NULL) {
278
0
                zip_error_set(ctx->error, ZIP_ER_MEMORY, 0);
279
0
                return false;
280
0
            }
281
0
            _zip_buffer_put_64(buffer, ctx->uncompresssed_size);
282
0
            _zip_buffer_free(buffer);
283
            /* Feed header into "lzma alone" decoder, for
284
             * initialization; this should not produce output. */
285
0
            ctx->zstr.next_in = (void *)(ctx->header + HEADER_MAGIC_LENGTH);
286
0
            ctx->zstr.avail_in = HEADER_LZMA_ALONE_LENGTH;
287
0
            ctx->zstr.total_in = 0;
288
0
            ctx->zstr.next_out = empty_buffer;
289
0
            ctx->zstr.avail_out = sizeof(*empty_buffer);
290
0
            ctx->zstr.total_out = 0;
291
            /* this just initializes the decoder and does not produce output, so it consumes the complete header */
292
0
            if (lzma_code(&ctx->zstr, LZMA_RUN) != LZMA_OK || ctx->zstr.total_out > 0) {
293
0
                zip_error_set(ctx->error, ZIP_ER_COMPRESSED_DATA, 0);
294
0
                return false;
295
0
            }
296
0
            ctx->header_state = DONE;
297
0
        }
298
0
    }
299
0
    ctx->zstr.avail_in = (uInt)length;
300
0
    ctx->zstr.next_in = (Bytef *)data;
301
302
0
    return true;
303
0
}
304
305
306
0
static bool end_of_input(void *ud) {
307
0
    struct ctx *ctx = (struct ctx *)ud;
308
309
0
    ctx->end_of_input = true;
310
0
    return ctx->zstr.avail_in != 0;
311
0
}
312
313
314
0
static zip_compression_status_t process(void *ud, zip_uint8_t *data, zip_uint64_t *length) {
315
0
    struct ctx *ctx = (struct ctx *)ud;
316
0
    uInt avail_out;
317
0
    lzma_ret ret;
318
    /* for compression of LZMA1 */
319
0
    if (ctx->method == ZIP_CM_LZMA && ctx->compress) {
320
0
        if (ctx->header_state == INCOMPLETE) {
321
            /* write magic to output buffer */
322
0
            ctx->header[0] = 0x09;
323
0
            ctx->header[1] = 0x14;
324
0
            ctx->header[2] = 0x05;
325
0
            ctx->header[3] = 0x00;
326
            /* generate lzma parameters into output buffer */
327
0
            ctx->zstr.avail_out = HEADER_LZMA_ALONE_LENGTH;
328
0
            ctx->zstr.next_out = ctx->header + HEADER_MAGIC_LENGTH;
329
0
            ret = lzma_code(&ctx->zstr, LZMA_RUN);
330
0
            if (ret != LZMA_OK || ctx->zstr.avail_out != 0) {
331
                /* assume that the whole header will be provided with the first call to lzma_code */
332
0
                return ZIP_COMPRESSION_ERROR;
333
0
            }
334
0
            ctx->header_state = OUTPUT;
335
0
        }
336
0
        if (ctx->header_state == OUTPUT) {
337
            /* write header */
338
0
            zip_uint8_t write_len = (zip_uint8_t)ZIP_MIN(HEADER_BYTES_ZIP - ctx->header_bytes_offset, *length);
339
0
            (void)memcpy_s(data, *length, ctx->header + ctx->header_bytes_offset, write_len);
340
0
            ctx->header_bytes_offset += write_len;
341
0
            *length = write_len;
342
0
            if (ctx->header_bytes_offset == HEADER_BYTES_ZIP) {
343
0
                ctx->header_state = DONE;
344
0
            }
345
0
            return ZIP_COMPRESSION_OK;
346
0
        }
347
0
    }
348
349
0
    avail_out = (uInt)ZIP_MIN(UINT_MAX, *length);
350
0
    ctx->zstr.avail_out = avail_out;
351
0
    ctx->zstr.next_out = (Bytef *)data;
352
353
0
    ret = lzma_code(&ctx->zstr, ctx->end_of_input ? LZMA_FINISH : LZMA_RUN);
354
0
    *length = avail_out - ctx->zstr.avail_out;
355
356
0
    switch (ret) {
357
0
    case LZMA_OK:
358
0
        return ZIP_COMPRESSION_OK;
359
360
0
    case LZMA_STREAM_END:
361
0
        return ZIP_COMPRESSION_END;
362
363
0
    case LZMA_BUF_ERROR:
364
0
        if (ctx->zstr.avail_in == 0) {
365
0
            return ZIP_COMPRESSION_NEED_DATA;
366
0
        }
367
368
        /* fallthrough */
369
0
    default:
370
0
        zip_error_set(ctx->error, map_error(ret), 0);
371
0
        return ZIP_COMPRESSION_ERROR;
372
0
    }
373
0
}
374
375
/* Version Required should be set to 63 (6.3) because this compression
376
   method was only defined in appnote.txt version 6.3.8, but Winzip
377
   does not unpack it if the value is not 20. */
378
379
/* clang-format off */
380
381
zip_compression_algorithm_t zip_algorithm_xz_compress = {
382
    maximum_compressed_size,
383
    compress_allocate,
384
    deallocate,
385
    general_purpose_bit_flags,
386
    20,
387
    start,
388
    end,
389
    input,
390
    end_of_input,
391
    process
392
};
393
394
395
zip_compression_algorithm_t zip_algorithm_xz_decompress = {
396
    maximum_compressed_size,
397
    decompress_allocate,
398
    deallocate,
399
    general_purpose_bit_flags,
400
    20,
401
    start,
402
    end,
403
    input,
404
    end_of_input,
405
    process
406
};
407
408
/* clang-format on */