Coverage Report

Created: 2026-07-25 07:06

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libtiff/libtiff/tif_zip.c
Line
Count
Source
1
/*
2
 * Copyright (c) 1995-1997 Sam Leffler
3
 * Copyright (c) 1995-1997 Silicon Graphics, Inc.
4
 *
5
 * Permission to use, copy, modify, distribute, and sell this software and
6
 * its documentation for any purpose is hereby granted without fee, provided
7
 * that (i) the above copyright notices and this permission notice appear in
8
 * all copies of the software and related documentation, and (ii) the names of
9
 * Sam Leffler and Silicon Graphics may not be used in any advertising or
10
 * publicity relating to the software without the specific, prior written
11
 * permission of Sam Leffler and Silicon Graphics.
12
 *
13
 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
14
 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
15
 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
16
 *
17
 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
18
 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
19
 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
20
 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
21
 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
22
 * OF THIS SOFTWARE.
23
 */
24
25
#include "tiffiop.h"
26
#ifdef ZIP_SUPPORT
27
/*
28
 * TIFF Library.
29
 *
30
 * ZIP (aka Deflate) Compression Support
31
 *
32
 * This file is an interface to the zlib library written by
33
 * Jean-loup Gailly and Mark Adler.  You must use version 1.0 or later
34
 * of the library.
35
 *
36
 * Optionally, libdeflate (https://github.com/ebiggers/libdeflate) may be used
37
 * to do the compression and decompression, but only for whole strips and tiles.
38
 * For scanline access, zlib will be sued as a fallback.
39
 */
40
#include "tif_predict.h"
41
#include "zlib.h"
42
43
#if LIBDEFLATE_SUPPORT
44
#include "libdeflate.h"
45
#endif
46
3.85k
#define LIBDEFLATE_MAX_COMPRESSION_LEVEL 12
47
48
#include <stdio.h>
49
50
/*
51
 * Sigh, ZLIB_VERSION is defined as a string so there's no
52
 * way to do a proper check here.  Instead we guess based
53
 * on the presence of #defines that were added between the
54
 * 0.95 and 1.0 distributions.
55
 */
56
#if !defined(Z_NO_COMPRESSION) || !defined(Z_DEFLATED)
57
#error "Antiquated ZLIB software; you must use version 1.0 or later"
58
#endif
59
60
812
#define SAFE_MSG(sp) ((sp)->stream.msg == NULL ? "" : (sp)->stream.msg)
61
62
/*
63
 * State block for each open TIFF
64
 * file using ZIP compression/decompression.
65
 */
66
typedef struct
67
{
68
    TIFFPredictorState predict;
69
    z_stream stream;
70
    int read_error; /* whether a read error has occurred, and which should cause
71
                       further reads in the same strip/tile to be aborted */
72
    int zipquality; /* compression level */
73
    int state;      /* state flags */
74
    int subcodec;   /* DEFLATE_SUBCODEC_ZLIB or DEFLATE_SUBCODEC_LIBDEFLATE */
75
#if LIBDEFLATE_SUPPORT
76
    int libdeflate_state; /* -1 = until first time ZIPEncode() / ZIPDecode() is
77
                             called, 0 = use zlib, 1 = use libdeflate */
78
    struct libdeflate_decompressor *libdeflate_dec;
79
    struct libdeflate_compressor *libdeflate_enc;
80
#endif
81
58.9k
#define ZSTATE_INIT_DECODE 0x01
82
45.5k
#define ZSTATE_INIT_ENCODE 0x02
83
84
    TIFFVGetMethod vgetparent; /* super-class method */
85
    TIFFVSetMethod vsetparent; /* super-class method */
86
} ZIPState;
87
88
1.70M
#define GetZIPState(tif) ((ZIPState *)(tif)->tif_data)
89
347k
#define ZIPDecoderState(tif) GetZIPState(tif)
90
883k
#define ZIPEncoderState(tif) GetZIPState(tif)
91
92
static int ZIPEncode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s);
93
static int ZIPDecode(TIFF *tif, uint8_t *op, tmsize_t occ, uint16_t s);
94
95
static int ZIPFixupTags(TIFF *tif)
96
6.46k
{
97
6.46k
    (void)tif;
98
6.46k
    return (1);
99
6.46k
}
100
101
static int ZIPSetupDecode(TIFF *tif)
102
4.92k
{
103
4.92k
    static const char module[] = "ZIPSetupDecode";
104
4.92k
    ZIPState *sp = ZIPDecoderState(tif);
105
106
4.92k
    assert(sp != NULL);
107
108
    /* if we were last encoding, terminate this mode */
109
4.92k
    if (sp->state & ZSTATE_INIT_ENCODE)
110
0
    {
111
0
        deflateEnd(&sp->stream);
112
0
        sp->state = 0;
113
0
    }
114
115
    /* This function can possibly be called several times by */
116
    /* PredictorSetupDecode() if this function succeeds but */
117
    /* PredictorSetup() fails */
118
4.92k
    if ((sp->state & ZSTATE_INIT_DECODE) == 0 &&
119
4.92k
        inflateInit(&sp->stream) != Z_OK)
120
0
    {
121
0
        TIFFErrorExtR(tif, module, "%s", SAFE_MSG(sp));
122
0
        return (0);
123
0
    }
124
4.92k
    else
125
4.92k
    {
126
4.92k
        sp->state |= ZSTATE_INIT_DECODE;
127
4.92k
        return (1);
128
4.92k
    }
129
4.92k
}
130
131
static inline uint64_t TIFF_MIN_UINT64(uint64_t a, uint64_t b)
132
1.49M
{
133
1.49M
    return a < b ? a : b;
134
1.49M
}
135
136
static inline uInt TIFF_CLAMP_UINT64_TO_INT32_MAX(uint64_t v)
137
1.49M
{
138
1.49M
    return (uInt)TIFF_MIN_UINT64(v, INT32_MAX);
139
1.49M
}
140
141
/*
142
 * Setup state for decoding a strip.
143
 */
144
static int ZIPPreDecode(TIFF *tif, uint16_t s)
145
20.6k
{
146
20.6k
    ZIPState *sp = ZIPDecoderState(tif);
147
148
20.6k
    (void)s;
149
20.6k
    assert(sp != NULL);
150
151
20.6k
    if ((sp->state & ZSTATE_INIT_DECODE) == 0)
152
0
        tif->tif_setupdecode(tif);
153
154
20.6k
#if LIBDEFLATE_SUPPORT
155
20.6k
    sp->libdeflate_state = -1;
156
20.6k
#endif
157
20.6k
    sp->stream.next_in = tif->tif_rawdata;
158
20.6k
    assert(sizeof(sp->stream.avail_in) == 4); /* if this assert gets raised,
159
         we need to simplify this code to reflect a ZLib that is likely updated
160
         to deal with 8byte memory sizes, though this code will respond
161
         appropriately even before we simplify it */
162
20.6k
    sp->stream.avail_in =
163
20.6k
        TIFF_CLAMP_UINT64_TO_INT32_MAX((uint64_t)tif->tif_rawcc);
164
20.6k
    if (inflateReset(&sp->stream) == Z_OK)
165
20.6k
    {
166
20.6k
        sp->read_error = 0;
167
20.6k
        return 1;
168
20.6k
    }
169
0
    return 0;
170
20.6k
}
171
172
static int ZIPDecode(TIFF *tif, uint8_t *op, tmsize_t occ, uint16_t s)
173
321k
{
174
321k
    static const char module[] = "ZIPDecode";
175
321k
    ZIPState *sp = ZIPDecoderState(tif);
176
177
321k
    (void)s;
178
321k
    assert(sp != NULL);
179
321k
    assert(sp->state == ZSTATE_INIT_DECODE);
180
181
321k
    if (sp->read_error)
182
0
    {
183
0
        memset(op, 0, (size_t)occ);
184
0
        TIFFErrorExtR(tif, module,
185
0
                      "ZIPDecode: Scanline %" PRIu32 " cannot be read due to "
186
0
                      "previous error",
187
0
                      tif->tif_dir.td_row);
188
0
        return 0;
189
0
    }
190
191
321k
#if LIBDEFLATE_SUPPORT
192
321k
    if (sp->libdeflate_state == 1)
193
0
        return 0;
194
195
    /* If we have libdeflate support and we are asked to read a whole */
196
    /* strip/tile, then go for using it */
197
321k
    do
198
321k
    {
199
321k
        TIFFDirectory *td = &tif->tif_dir;
200
201
321k
        if (sp->libdeflate_state == 0)
202
301k
            break;
203
20.6k
        if (sp->subcodec == DEFLATE_SUBCODEC_ZLIB)
204
0
            break;
205
206
        /* Check if we are in the situation where we can use libdeflate */
207
20.6k
        if (isTiled(tif))
208
980
        {
209
980
            if (TIFFTileSize64(tif) != (uint64_t)occ)
210
0
                break;
211
980
        }
212
19.6k
        else
213
19.6k
        {
214
19.6k
            uint32_t strip_height = td->td_imagelength - tif->tif_dir.td_row;
215
19.6k
            if (strip_height > td->td_rowsperstrip)
216
15.7k
                strip_height = td->td_rowsperstrip;
217
19.6k
            if (TIFFVStripSize64(tif, strip_height) != (uint64_t)occ)
218
1.20k
                break;
219
19.6k
        }
220
221
        /* Check for overflow */
222
19.4k
        if ((size_t)tif->tif_rawcc != (uint64_t)tif->tif_rawcc)
223
0
            break;
224
19.4k
        if ((size_t)occ != (uint64_t)occ)
225
0
            break;
226
227
        /* Go for decompression using libdeflate */
228
19.4k
        {
229
19.4k
            enum libdeflate_result res;
230
19.4k
            if (sp->libdeflate_dec == NULL)
231
3.70k
            {
232
3.70k
                sp->libdeflate_dec = libdeflate_alloc_decompressor();
233
3.70k
                if (sp->libdeflate_dec == NULL)
234
0
                {
235
0
                    break;
236
0
                }
237
3.70k
            }
238
239
19.4k
            sp->libdeflate_state = 1;
240
241
19.4k
            res = libdeflate_zlib_decompress(sp->libdeflate_dec, tif->tif_rawcp,
242
19.4k
                                             (size_t)tif->tif_rawcc, op,
243
19.4k
                                             (size_t)occ, NULL);
244
245
19.4k
            tif->tif_rawcp += tif->tif_rawcc;
246
19.4k
            tif->tif_rawcc = 0;
247
248
            /* We accept LIBDEFLATE_INSUFFICIENT_SPACE has a return */
249
            /* There are odd files in the wild where the last strip, when */
250
            /* it is smaller in height than td_rowsperstrip, actually contains
251
             */
252
            /* data for td_rowsperstrip lines. Just ignore that silently. */
253
19.4k
            if (res != LIBDEFLATE_SUCCESS &&
254
18.2k
                res != LIBDEFLATE_INSUFFICIENT_SPACE)
255
13.6k
            {
256
13.6k
                memset(op, 0, (size_t)occ);
257
13.6k
                TIFFErrorExtR(tif, module, "Decoding error at scanline %lu",
258
13.6k
                              (unsigned long)tif->tif_dir.td_row);
259
13.6k
                sp->read_error = 1;
260
13.6k
                return 0;
261
13.6k
            }
262
263
5.77k
            return 1;
264
19.4k
        }
265
19.4k
    } while (0);
266
302k
    sp->libdeflate_state = 0;
267
302k
#endif /* LIBDEFLATE_SUPPORT */
268
269
302k
    sp->stream.next_in = tif->tif_rawcp;
270
271
302k
    sp->stream.next_out = op;
272
302k
    assert(sizeof(sp->stream.avail_out) == 4); /* if this assert gets raised,
273
         we need to simplify this code to reflect a ZLib that is likely updated
274
         to deal with 8byte memory sizes, though this code will respond
275
         appropriately even before we simplify it */
276
302k
    do
277
302k
    {
278
302k
        int state;
279
302k
        uInt avail_in_before =
280
302k
            TIFF_CLAMP_UINT64_TO_INT32_MAX((uint64_t)tif->tif_rawcc);
281
302k
        uInt avail_out_before = TIFF_CLAMP_UINT64_TO_INT32_MAX((uint64_t)occ);
282
302k
        sp->stream.avail_in = avail_in_before;
283
302k
        sp->stream.avail_out = avail_out_before;
284
302k
        state = inflate(&sp->stream, Z_PARTIAL_FLUSH);
285
302k
        tif->tif_rawcc -= (avail_in_before - sp->stream.avail_in);
286
302k
        occ -= (avail_out_before - sp->stream.avail_out);
287
302k
        if (state == Z_STREAM_END)
288
10
            break;
289
302k
        if (state == Z_DATA_ERROR)
290
211
        {
291
211
            memset(sp->stream.next_out, 0, (size_t)occ);
292
211
            TIFFErrorExtR(tif, module, "Decoding error at scanline %lu, %s",
293
211
                          (unsigned long)tif->tif_dir.td_row, SAFE_MSG(sp));
294
211
            sp->read_error = 1;
295
211
            return (0);
296
211
        }
297
302k
        if (state != Z_OK)
298
601
        {
299
601
            memset(sp->stream.next_out, 0, (size_t)occ);
300
601
            TIFFErrorExtR(tif, module, "ZLib error: %s", SAFE_MSG(sp));
301
601
            sp->read_error = 1;
302
601
            return (0);
303
601
        }
304
302k
    } while (occ > 0);
305
301k
    if (occ != 0)
306
7
    {
307
7
        TIFFErrorExtR(tif, module,
308
7
                      "Not enough data at scanline %lu (short %" PRIu64
309
7
                      " bytes)",
310
7
                      (unsigned long)tif->tif_dir.td_row, (uint64_t)occ);
311
7
        memset(sp->stream.next_out, 0, (size_t)occ);
312
7
        sp->read_error = 1;
313
7
        return (0);
314
7
    }
315
316
301k
    tif->tif_rawcp = sp->stream.next_in;
317
318
301k
    return (1);
319
301k
}
320
321
static int ZIPSetupEncode(TIFF *tif)
322
3.85k
{
323
3.85k
    static const char module[] = "ZIPSetupEncode";
324
3.85k
    ZIPState *sp = ZIPEncoderState(tif);
325
3.85k
    int cappedQuality;
326
327
3.85k
    assert(sp != NULL);
328
3.85k
    if (sp->state & ZSTATE_INIT_DECODE)
329
0
    {
330
0
        inflateEnd(&sp->stream);
331
0
        sp->state = 0;
332
0
    }
333
334
3.85k
    cappedQuality = sp->zipquality;
335
3.85k
    if (cappedQuality > Z_BEST_COMPRESSION)
336
0
        cappedQuality = Z_BEST_COMPRESSION;
337
338
3.85k
    if (deflateInit(&sp->stream, cappedQuality) != Z_OK)
339
0
    {
340
0
        TIFFErrorExtR(tif, module, "%s", SAFE_MSG(sp));
341
0
        return (0);
342
0
    }
343
3.85k
    else
344
3.85k
    {
345
3.85k
        sp->state |= ZSTATE_INIT_ENCODE;
346
3.85k
        return (1);
347
3.85k
    }
348
3.85k
}
349
350
/*
351
 * Reset encoding state at the start of a strip.
352
 */
353
static int ZIPPreEncode(TIFF *tif, uint16_t s)
354
4.44k
{
355
4.44k
    ZIPState *sp = ZIPEncoderState(tif);
356
357
4.44k
    (void)s;
358
4.44k
    assert(sp != NULL);
359
4.44k
    if (sp->state != ZSTATE_INIT_ENCODE)
360
0
        tif->tif_setupencode(tif);
361
362
4.44k
#if LIBDEFLATE_SUPPORT
363
4.44k
    sp->libdeflate_state = -1;
364
4.44k
#endif
365
4.44k
    sp->stream.next_out = tif->tif_rawdata;
366
4.44k
    assert(sizeof(sp->stream.avail_out) == 4); /* if this assert gets raised,
367
         we need to simplify this code to reflect a ZLib that is likely updated
368
         to deal with 8byte memory sizes, though this code will respond
369
         appropriately even before we simplify it */
370
4.44k
    sp->stream.avail_out = (uint64_t)tif->tif_rawdatasize <= 0xFFFFFFFFU
371
4.44k
                               ? (uInt)tif->tif_rawdatasize
372
4.44k
                               : 0xFFFFFFFFU;
373
4.44k
    return (deflateReset(&sp->stream) == Z_OK);
374
4.44k
}
375
376
/*
377
 * Encode a chunk of pixels.
378
 */
379
static int ZIPEncode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
380
870k
{
381
870k
    static const char module[] = "ZIPEncode";
382
870k
    ZIPState *sp = ZIPEncoderState(tif);
383
384
870k
    assert(sp != NULL);
385
870k
    assert(sp->state == ZSTATE_INIT_ENCODE);
386
387
870k
    (void)s;
388
389
870k
#if LIBDEFLATE_SUPPORT
390
870k
    if (sp->libdeflate_state == 1)
391
0
        return 0;
392
393
    /* If we have libdeflate support and we are asked to write a whole */
394
    /* strip/tile, then go for using it */
395
870k
    do
396
870k
    {
397
870k
        TIFFDirectory *td = &tif->tif_dir;
398
399
870k
        if (sp->libdeflate_state == 0)
400
866k
            break;
401
4.44k
        if (sp->subcodec == DEFLATE_SUBCODEC_ZLIB)
402
0
            break;
403
404
        /* Libdeflate does not support the 0-compression level */
405
4.44k
        if (sp->zipquality == Z_NO_COMPRESSION)
406
0
            break;
407
408
        /* Check if we are in the situation where we can use libdeflate */
409
4.44k
        if (isTiled(tif))
410
0
        {
411
0
            if (TIFFTileSize64(tif) != (uint64_t)cc)
412
0
                break;
413
0
        }
414
4.44k
        else
415
4.44k
        {
416
4.44k
            uint32_t strip_height = td->td_imagelength - tif->tif_dir.td_row;
417
4.44k
            if (strip_height > td->td_rowsperstrip)
418
335
                strip_height = td->td_rowsperstrip;
419
4.44k
            if (TIFFVStripSize64(tif, strip_height) != (uint64_t)cc)
420
3.14k
                break;
421
4.44k
        }
422
423
        /* Check for overflow */
424
1.29k
        if ((size_t)tif->tif_rawdatasize != (uint64_t)tif->tif_rawdatasize)
425
0
            break;
426
1.29k
        if ((size_t)cc != (uint64_t)cc)
427
0
            break;
428
429
        /* Go for compression using libdeflate */
430
1.29k
        {
431
1.29k
            size_t nCompressedBytes;
432
1.29k
            if (sp->libdeflate_enc == NULL)
433
1.17k
            {
434
                /* To get results as good as zlib, we asked for an extra */
435
                /* level of compression */
436
1.17k
                sp->libdeflate_enc = libdeflate_alloc_compressor(
437
1.17k
                    sp->zipquality == Z_DEFAULT_COMPRESSION ? 7
438
1.17k
                    : sp->zipquality >= 6 && sp->zipquality <= 9
439
1.17k
                        ? sp->zipquality + 1
440
1.17k
                        : sp->zipquality);
441
1.17k
                if (sp->libdeflate_enc == NULL)
442
0
                {
443
0
                    TIFFErrorExtR(tif, module, "Cannot allocate compressor");
444
0
                    break;
445
0
                }
446
1.17k
            }
447
448
            /* Make sure the output buffer is large enough for the worse case.
449
             */
450
            /* In TIFFWriteBufferSetup(), when libtiff allocates the buffer */
451
            /* we've taken a 10% margin over the uncompressed size, which should
452
             */
453
            /* be large enough even for the the worse case scenario. */
454
1.29k
            if (libdeflate_zlib_compress_bound(sp->libdeflate_enc, (size_t)cc) >
455
1.29k
                (size_t)tif->tif_rawdatasize)
456
0
            {
457
0
                break;
458
0
            }
459
460
1.29k
            sp->libdeflate_state = 1;
461
1.29k
            nCompressedBytes = libdeflate_zlib_compress(
462
1.29k
                sp->libdeflate_enc, bp, (size_t)cc, tif->tif_rawdata,
463
1.29k
                (size_t)tif->tif_rawdatasize);
464
465
1.29k
            if (nCompressedBytes == 0)
466
0
            {
467
0
                TIFFErrorExtR(tif, module, "Encoder error at scanline %lu",
468
0
                              (unsigned long)tif->tif_dir.td_row);
469
0
                return 0;
470
0
            }
471
472
1.29k
            tif->tif_rawcc = (tmsize_t)nCompressedBytes;
473
474
1.29k
            if (!TIFFFlushData1(tif))
475
0
                return 0;
476
477
1.29k
            return 1;
478
1.29k
        }
479
1.29k
    } while (0);
480
869k
    sp->libdeflate_state = 0;
481
869k
#endif /* LIBDEFLATE_SUPPORT */
482
483
869k
    sp->stream.next_in = bp;
484
869k
    assert(sizeof(sp->stream.avail_in) == 4); /* if this assert gets raised,
485
         we need to simplify this code to reflect a ZLib that is likely updated
486
         to deal with 8byte memory sizes, though this code will respond
487
         appropriately even before we simplify it */
488
869k
    do
489
869k
    {
490
869k
        uInt avail_in_before = TIFF_CLAMP_UINT64_TO_INT32_MAX((uint64_t)cc);
491
869k
        sp->stream.avail_in = avail_in_before;
492
869k
        if (deflate(&sp->stream, Z_NO_FLUSH) != Z_OK)
493
0
        {
494
0
            TIFFErrorExtR(tif, module, "Encoder error: %s", SAFE_MSG(sp));
495
0
            return (0);
496
0
        }
497
869k
        if (sp->stream.avail_out == 0)
498
0
        {
499
0
            tif->tif_rawcc = tif->tif_rawdatasize;
500
0
            if (!TIFFFlushData1(tif))
501
0
                return 0;
502
0
            sp->stream.next_out = tif->tif_rawdata;
503
0
            sp->stream.avail_out =
504
0
                TIFF_CLAMP_UINT64_TO_INT32_MAX((uint64_t)tif->tif_rawdatasize);
505
0
        }
506
869k
        cc -= (avail_in_before - sp->stream.avail_in);
507
869k
    } while (cc > 0);
508
869k
    return (1);
509
869k
}
510
511
/*
512
 * Finish off an encoded strip by flushing the last
513
 * string and tacking on an End Of Information code.
514
 */
515
static int ZIPPostEncode(TIFF *tif)
516
4.44k
{
517
4.44k
    static const char module[] = "ZIPPostEncode";
518
4.44k
    ZIPState *sp = ZIPEncoderState(tif);
519
4.44k
    int state;
520
521
4.44k
#if LIBDEFLATE_SUPPORT
522
4.44k
    if (sp->libdeflate_state == 1)
523
1.29k
        return 1;
524
3.14k
#endif
525
526
3.14k
    sp->stream.avail_in = 0;
527
3.14k
    do
528
3.14k
    {
529
3.14k
        state = deflate(&sp->stream, Z_FINISH);
530
3.14k
        switch (state)
531
3.14k
        {
532
3.14k
            case Z_STREAM_END:
533
3.14k
            case Z_OK:
534
3.14k
                if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize)
535
3.14k
                {
536
3.14k
                    tif->tif_rawcc =
537
3.14k
                        tif->tif_rawdatasize - sp->stream.avail_out;
538
3.14k
                    if (!TIFFFlushData1(tif))
539
11
                        return 0;
540
3.13k
                    sp->stream.next_out = tif->tif_rawdata;
541
3.13k
                    sp->stream.avail_out =
542
3.13k
                        (uint64_t)tif->tif_rawdatasize <= 0xFFFFFFFFU
543
3.13k
                            ? (uInt)tif->tif_rawdatasize
544
3.13k
                            : 0xFFFFFFFFU;
545
3.13k
                }
546
3.13k
                break;
547
3.13k
            default:
548
0
                TIFFErrorExtR(tif, module, "ZLib error: %s", SAFE_MSG(sp));
549
0
                return (0);
550
3.14k
        }
551
3.14k
    } while (state != Z_STREAM_END);
552
3.13k
    return (1);
553
3.14k
}
554
555
static void ZIPCleanup(TIFF *tif)
556
28.4k
{
557
28.4k
    ZIPState *sp = GetZIPState(tif);
558
559
28.4k
    assert(sp != 0);
560
561
28.4k
    (void)TIFFPredictorCleanup(tif);
562
563
28.4k
    tif->tif_tagmethods.vgetfield = sp->vgetparent;
564
28.4k
    tif->tif_tagmethods.vsetfield = sp->vsetparent;
565
566
28.4k
    if (sp->state & ZSTATE_INIT_ENCODE)
567
3.85k
    {
568
3.85k
        deflateEnd(&sp->stream);
569
3.85k
        sp->state = 0;
570
3.85k
    }
571
24.6k
    else if (sp->state & ZSTATE_INIT_DECODE)
572
4.92k
    {
573
4.92k
        inflateEnd(&sp->stream);
574
4.92k
        sp->state = 0;
575
4.92k
    }
576
577
28.4k
#if LIBDEFLATE_SUPPORT
578
28.4k
    if (sp->libdeflate_dec)
579
3.70k
        libdeflate_free_decompressor(sp->libdeflate_dec);
580
28.4k
    if (sp->libdeflate_enc)
581
1.17k
        libdeflate_free_compressor(sp->libdeflate_enc);
582
28.4k
#endif
583
584
28.4k
    _TIFFfreeExt(tif, sp);
585
28.4k
    tif->tif_data = NULL;
586
587
28.4k
    _TIFFSetDefaultCompressionState(tif);
588
28.4k
}
589
590
static int ZIPVSetField(TIFF *tif, uint32_t tag, va_list ap)
591
142k
{
592
142k
    static const char module[] = "ZIPVSetField";
593
142k
    ZIPState *sp = GetZIPState(tif);
594
595
142k
    switch (tag)
596
142k
    {
597
3.85k
        case TIFFTAG_ZIPQUALITY:
598
3.85k
            sp->zipquality = (int)va_arg(ap, int);
599
3.85k
            if (sp->zipquality < Z_DEFAULT_COMPRESSION ||
600
3.85k
                sp->zipquality > LIBDEFLATE_MAX_COMPRESSION_LEVEL)
601
0
            {
602
0
                TIFFErrorExtR(
603
0
                    tif, module,
604
0
                    "Invalid ZipQuality value. Should be in [-1,%d] range",
605
0
                    LIBDEFLATE_MAX_COMPRESSION_LEVEL);
606
0
                return 0;
607
0
            }
608
609
3.85k
            if (sp->state & ZSTATE_INIT_ENCODE)
610
0
            {
611
0
                int cappedQuality = sp->zipquality;
612
0
                if (cappedQuality > Z_BEST_COMPRESSION)
613
0
                    cappedQuality = Z_BEST_COMPRESSION;
614
0
                if (deflateParams(&sp->stream, cappedQuality,
615
0
                                  Z_DEFAULT_STRATEGY) != Z_OK)
616
0
                {
617
0
                    TIFFErrorExtR(tif, module, "ZLib error: %s", SAFE_MSG(sp));
618
0
                    return (0);
619
0
                }
620
0
            }
621
622
3.85k
#if LIBDEFLATE_SUPPORT
623
3.85k
            if (sp->libdeflate_enc)
624
0
            {
625
0
                libdeflate_free_compressor(sp->libdeflate_enc);
626
0
                sp->libdeflate_enc = NULL;
627
0
            }
628
3.85k
#endif
629
630
3.85k
            return (1);
631
632
0
        case TIFFTAG_DEFLATE_SUBCODEC:
633
0
            sp->subcodec = (int)va_arg(ap, int);
634
0
            if (sp->subcodec != DEFLATE_SUBCODEC_ZLIB &&
635
0
                sp->subcodec != DEFLATE_SUBCODEC_LIBDEFLATE)
636
0
            {
637
0
                TIFFErrorExtR(tif, module, "Invalid DeflateCodec value.");
638
0
                return 0;
639
0
            }
640
#if !LIBDEFLATE_SUPPORT
641
            if (sp->subcodec == DEFLATE_SUBCODEC_LIBDEFLATE)
642
            {
643
                TIFFErrorExtR(tif, module,
644
                              "DeflateCodec = DEFLATE_SUBCODEC_LIBDEFLATE "
645
                              "unsupported in this build");
646
                return 0;
647
            }
648
#endif
649
0
            return 1;
650
651
138k
        default:
652
138k
            return (*sp->vsetparent)(tif, tag, ap);
653
142k
    }
654
    /*NOTREACHED*/
655
142k
}
656
657
static int ZIPVGetField(TIFF *tif, uint32_t tag, va_list ap)
658
279k
{
659
279k
    ZIPState *sp = GetZIPState(tif);
660
661
279k
    switch (tag)
662
279k
    {
663
0
        case TIFFTAG_ZIPQUALITY:
664
0
            *va_arg(ap, int *) = sp->zipquality;
665
0
            break;
666
667
0
        case TIFFTAG_DEFLATE_SUBCODEC:
668
0
            *va_arg(ap, int *) = sp->subcodec;
669
0
            break;
670
671
279k
        default:
672
279k
            return (*sp->vgetparent)(tif, tag, ap);
673
279k
    }
674
0
    return (1);
675
279k
}
676
677
static const TIFFField zipFields[] = {
678
    {TIFFTAG_ZIPQUALITY, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, FIELD_PSEUDO, TRUE,
679
     FALSE, "", NULL},
680
    {TIFFTAG_DEFLATE_SUBCODEC, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, FIELD_PSEUDO,
681
     TRUE, FALSE, "", NULL},
682
};
683
684
static void *TIFF_zalloc(void *opaque, unsigned int items, unsigned int size)
685
25.2k
{
686
25.2k
    static const char module[] = "TIFF_zalloc";
687
25.2k
    TIFF *tif = (TIFF *)opaque;
688
689
25.2k
    if (items > ~(size_t)0 / size)
690
0
    {
691
0
        TIFFErrorExtR(tif, module, "Overflow");
692
0
        return NULL;
693
0
    }
694
695
25.2k
    return _TIFFmallocExt(tif, items * size);
696
25.2k
}
697
698
static void TIFF_zfree(void *opaque, void *ptr)
699
25.2k
{
700
25.2k
    _TIFFfreeExt((TIFF *)opaque, ptr);
701
25.2k
}
702
703
static uint64_t ZIPGetMaxCompressionRatio(TIFF *tif)
704
0
{
705
0
    (void)tif;
706
    /* cf https://zlib.net/zlib_tech.html */
707
0
    return 1032;
708
0
}
709
710
int TIFFInitZIP(TIFF *tif, int scheme)
711
28.4k
{
712
28.4k
    static const char module[] = "TIFFInitZIP";
713
28.4k
    ZIPState *sp;
714
715
28.4k
    assert((scheme == COMPRESSION_DEFLATE) ||
716
28.4k
           (scheme == COMPRESSION_ADOBE_DEFLATE));
717
#ifdef NDEBUG
718
    (void)scheme;
719
#endif
720
721
    /*
722
     * Merge codec-specific tag information.
723
     */
724
28.4k
    if (!_TIFFMergeFields(tif, zipFields, TIFFArrayCount(zipFields)))
725
0
    {
726
0
        TIFFErrorExtR(tif, module,
727
0
                      "Merging Deflate codec-specific tags failed");
728
0
        return 0;
729
0
    }
730
731
    /*
732
     * Allocate state block so tag methods have storage to record values.
733
     */
734
28.4k
    tif->tif_data = (uint8_t *)_TIFFcallocExt(tif, sizeof(ZIPState), 1);
735
28.4k
    if (tif->tif_data == NULL)
736
0
        goto bad;
737
28.4k
    sp = GetZIPState(tif);
738
28.4k
    sp->stream.zalloc = TIFF_zalloc;
739
28.4k
    sp->stream.zfree = TIFF_zfree;
740
28.4k
    sp->stream.opaque = tif;
741
28.4k
    sp->stream.data_type = Z_BINARY;
742
743
    /*
744
     * Override parent get/set field methods.
745
     */
746
28.4k
    sp->vgetparent = tif->tif_tagmethods.vgetfield;
747
28.4k
    tif->tif_tagmethods.vgetfield = ZIPVGetField; /* hook for codec tags */
748
28.4k
    sp->vsetparent = tif->tif_tagmethods.vsetfield;
749
28.4k
    tif->tif_tagmethods.vsetfield = ZIPVSetField; /* hook for codec tags */
750
751
    /* Default values for codec-specific fields */
752
28.4k
    sp->zipquality = Z_DEFAULT_COMPRESSION; /* default comp. level */
753
28.4k
    sp->state = 0;
754
28.4k
#if LIBDEFLATE_SUPPORT
755
28.4k
    sp->subcodec = DEFLATE_SUBCODEC_LIBDEFLATE;
756
#else
757
    sp->subcodec = DEFLATE_SUBCODEC_ZLIB;
758
#endif
759
760
    /*
761
     * Install codec methods.
762
     */
763
28.4k
    tif->tif_fixuptags = ZIPFixupTags;
764
28.4k
    tif->tif_setupdecode = ZIPSetupDecode;
765
28.4k
    tif->tif_predecode = ZIPPreDecode;
766
28.4k
    tif->tif_decoderow = ZIPDecode;
767
28.4k
    tif->tif_decodestrip = ZIPDecode;
768
28.4k
    tif->tif_decodetile = ZIPDecode;
769
28.4k
    tif->tif_setupencode = ZIPSetupEncode;
770
28.4k
    tif->tif_preencode = ZIPPreEncode;
771
28.4k
    tif->tif_postencode = ZIPPostEncode;
772
28.4k
    tif->tif_encoderow = ZIPEncode;
773
28.4k
    tif->tif_encodestrip = ZIPEncode;
774
28.4k
    tif->tif_encodetile = ZIPEncode;
775
28.4k
    tif->tif_cleanup = ZIPCleanup;
776
28.4k
    tif->tif_getmaxcompressionratio = ZIPGetMaxCompressionRatio;
777
    /*
778
     * Setup predictor setup.
779
     */
780
28.4k
    (void)TIFFPredictorInit(tif);
781
28.4k
    return (1);
782
0
bad:
783
0
    TIFFErrorExtR(tif, module, "No space for ZIP state block");
784
0
    return (0);
785
28.4k
}
786
#endif /* ZIP_SUPPORT */