Coverage Report

Created: 2026-02-26 06:40

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