Coverage Report

Created: 2025-07-12 06:26

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