Coverage Report

Created: 2026-10-28 07:06

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/qpdf/libqpdf/Pl_Flate.cc
Line
Count
Source
1
#include <qpdf/Pl_Flate.hh>
2
3
#include <climits>
4
#include <cstring>
5
#include <zlib.h>
6
7
#include <qpdf/QIntC.hh>
8
#include <qpdf/QUtil.hh>
9
#include <qpdf/Util.hh>
10
#include <qpdf/global_private.hh>
11
#include <qpdf/qpdf-config.h>
12
13
#ifdef ZOPFLI
14
# include <zopfli.h>
15
#endif
16
17
using namespace qpdf;
18
19
namespace
20
{
21
    static unsigned long long const& memory_limit{global::Limits::flate_max_memory()};
22
} // namespace
23
24
int Pl_Flate::compression_level = Z_DEFAULT_COMPRESSION;
25
26
Pl_Flate::Members::Members(size_t out_bufsize, action_e action) :
27
510k
    out_bufsize(out_bufsize),
28
510k
    action(action),
29
510k
    initialized(false),
30
510k
    zdata(nullptr)
31
510k
{
32
510k
    this->outbuf = QUtil::make_shared_array<unsigned char>(out_bufsize);
33
    // Indirect through zdata to reach the z_stream so we don't have to include zlib.h in
34
    // Pl_Flate.hh.  This means people using shared library versions of qpdf don't have to have zlib
35
    // development files available, which particularly helps in a Windows environment.
36
510k
    zdata = new z_stream;
37
38
510k
    util::no_ci_rt_error_if(
39
510k
        out_bufsize > UINT_MAX,
40
510k
        "Pl_Flate: zlib doesn't support buffer sizes larger than unsigned int");
41
42
510k
    z_stream& zstream = *(static_cast<z_stream*>(this->zdata));
43
510k
    zstream.zalloc = nullptr;
44
510k
    zstream.zfree = nullptr;
45
510k
    zstream.opaque = nullptr;
46
510k
    zstream.next_in = nullptr;
47
510k
    zstream.avail_in = 0;
48
510k
    zstream.next_out = this->outbuf.get();
49
510k
    zstream.avail_out = QIntC::to_uint(out_bufsize);
50
51
510k
    if (action == a_deflate && Pl_Flate::zopfli_enabled()) {
52
0
        zopfli_buf = std::make_unique<std::string>();
53
0
    }
54
510k
}
55
56
Pl_Flate::Members::~Members()
57
510k
{
58
510k
    if (initialized) {
59
41.3k
        z_stream& zstream = *(static_cast<z_stream*>(zdata));
60
41.3k
        if (action == a_deflate) {
61
8.15k
            deflateEnd(&zstream);
62
33.2k
        } else {
63
33.2k
            inflateEnd(&zstream);
64
33.2k
        }
65
41.3k
    }
66
67
510k
    delete static_cast<z_stream*>(this->zdata);
68
510k
    zdata = nullptr;
69
510k
}
70
71
Pl_Flate::Pl_Flate(
72
    char const* identifier, Pipeline* next, action_e action, unsigned int out_bufsize_int) :
73
510k
    Pipeline(identifier, next),
74
510k
    m(std::make_unique<Members>(QIntC::to_size(out_bufsize_int), action))
75
510k
{
76
510k
    util::assertion(next, "Attempt to create Pl_Flate with nullptr as next");
77
510k
}
78
79
// Must be explicit and not inline -- see QPDF_DLL_CLASS in README-maintainer
80
510k
Pl_Flate::~Pl_Flate() = default;
81
82
unsigned long long
83
Pl_Flate::memory_limit()
84
66.5k
{
85
66.5k
    return ::memory_limit;
86
66.5k
}
87
88
void
89
Pl_Flate::memory_limit(unsigned long long limit)
90
0
{
91
0
    global::Limits::flate_max_memory(limit);
92
0
}
93
94
void
95
Pl_Flate::setWarnCallback(std::function<void(char const*, int)> callback)
96
185k
{
97
185k
    m->callback = callback;
98
185k
}
99
100
void
101
Pl_Flate::warn(char const* msg, int code)
102
52.3k
{
103
52.3k
    if (m->callback) {
104
52.3k
        m->callback(msg, code);
105
52.3k
    }
106
52.3k
}
107
108
void
109
Pl_Flate::write(unsigned char const* data, size_t len)
110
32.7M
{
111
32.7M
    util::assertion(
112
32.7M
        m->outbuf.get(), identifier + ": Pl_Flate: write() called after finish() called");
113
32.7M
    if (m->zopfli_buf) {
114
0
        m->zopfli_buf->append(reinterpret_cast<char const*>(data), len);
115
0
        return;
116
0
    }
117
118
    // Write in chunks in case len is too big to fit in an int. Assume int is at least 32 bits.
119
32.7M
    static size_t const max_bytes = 1 << 30;
120
32.7M
    size_t bytes_left = len;
121
32.7M
    unsigned char const* buf = data;
122
65.4M
    while (bytes_left > 0) {
123
32.7M
        size_t bytes = (bytes_left >= max_bytes ? max_bytes : bytes_left);
124
32.7M
        handleData(buf, bytes, (m->action == a_inflate ? Z_SYNC_FLUSH : Z_NO_FLUSH));
125
32.7M
        bytes_left -= bytes;
126
32.7M
        buf += bytes;
127
32.7M
    }
128
32.7M
}
129
130
void
131
Pl_Flate::handleData(unsigned char const* data, size_t len, int flush)
132
33.1M
{
133
33.1M
    util::no_ci_rt_error_if(
134
33.1M
        len > UINT_MAX, "Pl_Flate: zlib doesn't support data blocks larger than int");
135
33.1M
    z_stream& zstream = *(static_cast<z_stream*>(m->zdata));
136
    // zlib is known not to modify the data pointed to by next_in but doesn't declare the field
137
    // value const unless compiled to do so.
138
33.1M
    zstream.next_in = const_cast<unsigned char*>(data);
139
33.1M
    zstream.avail_in = QIntC::to_uint(len);
140
141
33.1M
    if (!m->initialized) {
142
437k
        int err = Z_OK;
143
144
        // deflateInit and inflateInit are macros that use old-style casts.
145
437k
#if ((defined(__GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406) || defined(__clang__))
146
437k
# pragma GCC diagnostic push
147
437k
# pragma GCC diagnostic ignored "-Wold-style-cast"
148
437k
#endif
149
437k
        if (m->action == a_deflate) {
150
280k
            err = deflateInit(&zstream, compression_level);
151
280k
        } else {
152
156k
            err = inflateInit(&zstream);
153
156k
        }
154
437k
#if ((defined(__GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406) || defined(__clang__))
155
437k
# pragma GCC diagnostic pop
156
437k
#endif
157
158
437k
        checkError("Init", err);
159
437k
        m->initialized = true;
160
437k
    }
161
162
33.1M
    int err = Z_OK;
163
164
33.1M
    bool done = false;
165
66.2M
    while (!done) {
166
33.1M
        if (m->action == a_deflate) {
167
31.2M
            err = deflate(&zstream, flush);
168
31.2M
        } else {
169
1.85M
            err = inflate(&zstream, flush);
170
1.85M
        }
171
33.1M
        if ((m->action == a_inflate) && (err != Z_OK) && zstream.msg &&
172
113k
            (strcmp(zstream.msg, "incorrect data check") == 0)) {
173
            // Other PDF readers ignore this specific error. Combining this with Z_SYNC_FLUSH
174
            // enables qpdf to handle some broken zlib streams without losing data.
175
54.0k
            err = Z_STREAM_END;
176
54.0k
        }
177
33.1M
        switch (err) {
178
52.3k
        case Z_BUF_ERROR:
179
            // Probably shouldn't be able to happen, but possible as a boundary condition: if the
180
            // last call to inflate exactly filled the output buffer, it's possible that the next
181
            // call to inflate could have nothing to do. There are PDF files in the wild that have
182
            // this error (including at least one in qpdf's test suite). In some cases, we want to
183
            // know about this, because it indicates incorrect compression, so call a callback if
184
            // provided.
185
52.3k
            warn("input stream is complete but output may still be valid", err);
186
52.3k
            done = true;
187
52.3k
            break;
188
189
435k
        case Z_STREAM_END:
190
435k
            done = true;
191
            // fall through
192
193
33.0M
        case Z_OK:
194
33.0M
            {
195
33.0M
                if ((zstream.avail_in == 0) && (zstream.avail_out > 0)) {
196
                    // There is nothing left to read, and there was sufficient buffer space to write
197
                    // everything we needed, so we're done for now.
198
32.9M
                    done = true;
199
32.9M
                }
200
33.0M
                uLong ready = QIntC::to_ulong(m->out_bufsize - zstream.avail_out);
201
33.0M
                if (ready > 0) {
202
2.08M
                    if (::memory_limit && m->action != a_deflate) {
203
1.49M
                        m->written += ready;
204
1.49M
                        if (m->written > ::memory_limit) {
205
707
                            throw std::runtime_error("PL_Flate memory limit exceeded");
206
707
                        }
207
1.49M
                    }
208
2.08M
                    next()->write(m->outbuf.get(), ready);
209
2.08M
                    zstream.next_out = m->outbuf.get();
210
2.08M
                    zstream.avail_out = QIntC::to_uint(m->out_bufsize);
211
2.08M
                }
212
33.0M
            }
213
33.0M
            break;
214
215
33.0M
        default:
216
60.0k
            checkError("data", err);
217
33.1M
        }
218
33.1M
    }
219
33.1M
}
220
221
void
222
Pl_Flate::finish()
223
461k
{
224
461k
    if (m->written > ::memory_limit) {
225
601
        throw std::runtime_error("PL_Flate memory limit exceeded");
226
601
    }
227
461k
    try {
228
461k
        if (m->zopfli_buf) {
229
0
            finish_zopfli();
230
461k
        } else if (m->outbuf.get()) {
231
461k
            if (m->initialized) {
232
420k
                z_stream& zstream = *(static_cast<z_stream*>(m->zdata));
233
420k
                unsigned char buf[1];
234
420k
                buf[0] = '\0';
235
420k
                handleData(buf, 0, Z_FINISH);
236
420k
                int err = Z_OK;
237
420k
                if (m->action == a_deflate) {
238
272k
                    err = deflateEnd(&zstream);
239
272k
                } else {
240
147k
                    err = inflateEnd(&zstream);
241
147k
                }
242
420k
                m->initialized = false;
243
420k
                checkError("End", err);
244
420k
            }
245
246
461k
            m->outbuf = nullptr;
247
461k
        }
248
461k
    } catch (std::exception& e) {
249
24.3k
        try {
250
24.3k
            next()->finish();
251
24.3k
        } catch (...) {
252
            // ignore secondary exception
253
161
        }
254
24.3k
        throw std::runtime_error(e.what());
255
24.3k
    }
256
436k
    next()->finish();
257
436k
}
258
259
void
260
Pl_Flate::setCompressionLevel(int level)
261
0
{
262
0
    compression_level = level;
263
0
}
264
265
void
266
Pl_Flate::checkError(char const* prefix, int error_code)
267
893k
{
268
893k
    z_stream& zstream = *(static_cast<z_stream*>(m->zdata));
269
893k
    if (error_code != Z_OK) {
270
60.0k
        char const* action_str = (m->action == a_deflate ? "deflate" : "inflate");
271
60.0k
        std::string msg = identifier + ": " + action_str + ": " + prefix + ": ";
272
273
60.0k
        if (zstream.msg) {
274
59.1k
            msg += zstream.msg;
275
59.1k
        } else {
276
914
            switch (error_code) {
277
0
            case Z_ERRNO:
278
0
                msg += "zlib system error";
279
0
                break;
280
281
0
            case Z_STREAM_ERROR:
282
0
                msg += "zlib stream error";
283
0
                break;
284
285
0
            case Z_DATA_ERROR:
286
0
                msg += "zlib data error";
287
0
                break;
288
289
0
            case Z_MEM_ERROR:
290
0
                msg += "zlib memory error";
291
0
                break;
292
293
0
            case Z_BUF_ERROR:
294
0
                msg += "zlib buffer error";
295
0
                break;
296
297
0
            case Z_VERSION_ERROR:
298
0
                msg += "zlib version error";
299
0
                break;
300
301
914
            default:
302
914
                msg += std::string("zlib unknown error (") + std::to_string(error_code) + ")";
303
914
                break;
304
914
            }
305
914
        }
306
307
60.0k
        throw std::runtime_error(msg);
308
60.0k
    }
309
893k
}
310
311
void
312
Pl_Flate::finish_zopfli()
313
0
{
314
#ifdef ZOPFLI
315
    if (!m->zopfli_buf) {
316
        return;
317
    }
318
    auto buf = std::move(*m->zopfli_buf.release());
319
    ZopfliOptions z_opt;
320
    ZopfliInitOptions(&z_opt);
321
    unsigned char* out{nullptr};
322
    size_t out_size{0};
323
    ZopfliCompress(
324
        &z_opt,
325
        ZOPFLI_FORMAT_ZLIB,
326
        reinterpret_cast<unsigned char const*>(buf.c_str()),
327
        buf.size(),
328
        &out,
329
        &out_size);
330
    std::unique_ptr<unsigned char, decltype(&free)> p(out, &free);
331
    next()->write(out, out_size);
332
    // next()->finish is called by finish()
333
#endif
334
0
}
335
336
bool
337
Pl_Flate::zopfli_supported()
338
329k
{
339
#ifdef ZOPFLI
340
    return true;
341
#else
342
329k
    return false;
343
329k
#endif
344
329k
}
345
346
bool
347
Pl_Flate::zopfli_enabled()
348
329k
{
349
329k
    if (zopfli_supported()) {
350
0
        std::string value;
351
0
        static bool enabled = QUtil::get_env("QPDF_ZOPFLI", &value) && value != "disabled";
352
0
        return enabled;
353
329k
    } else {
354
329k
        return false;
355
329k
    }
356
329k
}
357
358
bool
359
Pl_Flate::zopfli_check_env(QPDFLogger* logger)
360
0
{
361
0
    if (Pl_Flate::zopfli_supported()) {
362
0
        return true;
363
0
    }
364
0
    std::string value;
365
0
    auto is_set = QUtil::get_env("QPDF_ZOPFLI", &value);
366
0
    if (!is_set || value == "disabled" || value == "silent") {
367
0
        return true;
368
0
    }
369
0
    if (!logger) {
370
0
        logger = QPDFLogger::defaultLogger().get();
371
0
    }
372
373
    // This behavior is known in QPDFJob (for the --zopfli argument), Pl_Flate.hh, README.md,
374
    // and the manual. Do a case-insensitive search for zopfli if changing the behavior.
375
0
    if (value == "force") {
376
0
        throw std::runtime_error("QPDF_ZOPFLI=force, and zopfli support is not enabled");
377
0
    }
378
0
    logger->warn("QPDF_ZOPFLI is set, but libqpdf was not built with zopfli support\n");
379
0
    logger->warn(
380
0
        "Set QPDF_ZOPFLI=silent to suppress this warning and use zopfli when available.\n");
381
0
    return false;
382
0
}