Coverage Report

Created: 2026-09-14 06:17

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/qpdf/libqpdf/QPDF_json.cc
Line
Count
Source
1
#include <qpdf/QPDF.hh>
2
3
#include <qpdf/FileInputSource.hh>
4
#include <qpdf/InputSource_private.hh>
5
#include <qpdf/JSON_writer.hh>
6
#include <qpdf/Pl_Base64.hh>
7
#include <qpdf/Pl_StdioFile.hh>
8
#include <qpdf/QIntC.hh>
9
#include <qpdf/QPDFObjectHandle_private.hh>
10
#include <qpdf/QPDFObject_private.hh>
11
#include <qpdf/QTC.hh>
12
#include <qpdf/QUtil.hh>
13
#include <qpdf/Util.hh>
14
15
#include <algorithm>
16
#include <cstring>
17
18
using namespace qpdf;
19
20
// This chart shows an example of the state transitions that would occur in parsing a minimal file.
21
22
//                                |
23
// {                              |   -> st_top
24
//   "qpdf": [                    |   -> st_qpdf
25
//     {                          |   -> st_qpdf_meta
26
//       ...                      |   ...
27
//     },                         |   ...
28
//     {                          |   -> st_objects
29
//       "obj:1 0 R": {           |   -> st_object_top
30
//         "value": {             |   -> st_object
31
//           "/Pages": "2 0 R",   |   ...
32
//           "/Type": "/Catalog"  |   ...
33
//         }                      |   <- st_object_top
34
//       },                       |   <- st_objects
35
//       "obj:2 0 R": {           |   -> st_object_top
36
//         "value": 12            |   -> st_object
37
//         }                      |   <- st_object_top
38
//       },                       |   <- st_objects
39
//       "obj:4 0 R": {           |   -> st_object_top
40
//         "stream": {            |   -> st_stream
41
//           "data": "cG90YXRv",  |   ...
42
//           "dict": {            |   -> st_object
43
//             "/K": true         |   ...
44
//           }                    |   <- st_stream
45
//         }                      |   <- st_object_top
46
//       },                       |   <- st_objects
47
//       "trailer": {             |   -> st_trailer
48
//         "value": {             |   -> st_object
49
//           "/Root": "1 0 R",    |   ...
50
//           "/Size": 7           |   ...
51
//         }                      |   <- st_trailer
52
//       }                        |   <- st_objects
53
//     }                          |   <- st_qpdf
54
//   ]                            |   <- st_top
55
// }                              |
56
57
static char const* JSON_PDF = (
58
    // force line break
59
    "%PDF-1.3\n"
60
    "xref\n"
61
    "0 1\n"
62
    "0000000000 65535 f \n"
63
    "trailer << /Size 1 >>\n"
64
    "startxref\n"
65
    "9\n"
66
    "%%EOF\n");
67
68
// Validator methods -- these are much more performant than std::regex.
69
static bool
70
is_indirect_object(std::string const& v, int& obj, int& gen)
71
1.31M
{
72
1.31M
    char const* p = v.c_str();
73
1.31M
    std::string o_str;
74
1.31M
    std::string g_str;
75
1.31M
    if (!util::is_digit(*p)) {
76
89.2k
        return false;
77
89.2k
    }
78
2.61M
    while (util::is_digit(*p)) {
79
1.38M
        o_str.append(1, *p++);
80
1.38M
    }
81
1.22M
    if (*p != ' ') {
82
4.26k
        return false;
83
4.26k
    }
84
5.04M
    while (*p == ' ') {
85
3.82M
        ++p;
86
3.82M
    }
87
1.22M
    if (!util::is_digit(*p)) {
88
2.80k
        return false;
89
2.80k
    }
90
18.2M
    while (util::is_digit(*p)) {
91
16.9M
        g_str.append(1, *p++);
92
16.9M
    }
93
1.21M
    if (*p != ' ') {
94
1.88k
        return false;
95
1.88k
    }
96
10.9M
    while (*p == ' ') {
97
9.72M
        ++p;
98
9.72M
    }
99
1.21M
    if (*p++ != 'R') {
100
2.66k
        return false;
101
2.66k
    }
102
1.21M
    if (*p) {
103
1.85k
        return false;
104
1.85k
    }
105
1.21M
    obj = QUtil::string_to_int(o_str.c_str());
106
1.21M
    gen = QUtil::string_to_int(g_str.c_str());
107
1.21M
    return obj > 0;
108
1.21M
}
109
110
static bool
111
is_obj_key(std::string const& v, int& obj, int& gen)
112
41.6k
{
113
41.6k
    if (v.substr(0, 4) != "obj:") {
114
8.35k
        return false;
115
8.35k
    }
116
33.2k
    return is_indirect_object(v.substr(4), obj, gen);
117
41.6k
}
118
119
static bool
120
is_unicode_string(std::string const& v, std::string& str)
121
98.8k
{
122
98.8k
    if (v.substr(0, 2) == "u:") {
123
10.3k
        str = v.substr(2);
124
10.3k
        return true;
125
10.3k
    }
126
88.4k
    return false;
127
98.8k
}
128
129
static bool
130
is_binary_string(std::string const& v, std::string& str)
131
88.4k
{
132
88.4k
    if (v.substr(0, 2) == "b:") {
133
5.10k
        str = v.substr(2);
134
5.10k
        int count = 0;
135
54.1k
        for (char c: str) {
136
54.1k
            if (!util::is_hex_digit(c)) {
137
2.01k
                return false;
138
2.01k
            }
139
52.1k
            ++count;
140
52.1k
        }
141
3.09k
        return (count % 2 == 0);
142
5.10k
    }
143
83.3k
    return false;
144
88.4k
}
145
146
static bool
147
is_name(std::string const& v)
148
86.2k
{
149
86.2k
    return v.starts_with('/');
150
86.2k
}
151
152
static bool
153
is_pdf_name(std::string const& v)
154
302k
{
155
302k
    return v.starts_with("n:/");
156
302k
}
157
158
bool
159
QPDF::test_json_validators()
160
0
{
161
0
    bool passed = true;
162
0
    auto check_fn = [&passed](char const* msg, bool expr) {
163
0
        if (!expr) {
164
0
            passed = false;
165
0
            std::cerr << msg << '\n';
166
0
        }
167
0
    };
168
0
#define check(expr) check_fn(#expr, expr)
169
170
0
    int obj = 0;
171
0
    int gen = 0;
172
0
    check(!is_indirect_object("", obj, gen));
173
0
    check(!is_indirect_object("12", obj, gen));
174
0
    check(!is_indirect_object("x12 0 R", obj, gen));
175
0
    check(!is_indirect_object("12 0 Rx", obj, gen));
176
0
    check(!is_indirect_object("12 0R", obj, gen));
177
0
    check(is_indirect_object("52 1 R", obj, gen));
178
0
    check(obj == 52);
179
0
    check(gen == 1);
180
0
    check(is_indirect_object("53  20  R", obj, gen));
181
0
    check(obj == 53);
182
0
    check(gen == 20);
183
0
    check(!is_obj_key("", obj, gen));
184
0
    check(!is_obj_key("obj:x", obj, gen));
185
0
    check(!is_obj_key("obj:x", obj, gen));
186
0
    check(is_obj_key("obj:12 13 R", obj, gen));
187
0
    check(obj == 12);
188
0
    check(gen == 13);
189
0
    std::string str;
190
0
    check(!is_unicode_string("", str));
191
0
    check(!is_unicode_string("xyz", str));
192
0
    check(!is_unicode_string("x:", str));
193
0
    check(is_unicode_string("u:potato", str));
194
0
    check(str == "potato");
195
0
    check(is_unicode_string("u:", str));
196
0
    check(str.empty());
197
0
    check(!is_binary_string("", str));
198
0
    check(!is_binary_string("x:", str));
199
0
    check(!is_binary_string("b:1", str));
200
0
    check(!is_binary_string("b:123", str));
201
0
    check(!is_binary_string("b:gh", str));
202
0
    check(is_binary_string("b:", str));
203
0
    check(is_binary_string("b:12", str));
204
0
    check(is_binary_string("b:123aBC", str));
205
0
    check(!is_name(""));
206
0
    check(is_name("/"));
207
0
    check(!is_name("xyz"));
208
0
    check(is_name("/Potato"));
209
0
    check(is_name("/Potato Salad"));
210
0
    check(!is_pdf_name("n:"));
211
0
    check(is_pdf_name("n:/"));
212
0
    check(!is_pdf_name("n:xyz"));
213
0
    check(is_pdf_name("n:/Potato"));
214
0
    check(is_pdf_name("n:/Potato Salad"));
215
216
0
    return passed;
217
0
#undef check_arg
218
0
}
219
220
static std::function<void(Pipeline*)>
221
provide_data(std::shared_ptr<InputSource> is, qpdf_offset_t start, qpdf_offset_t end)
222
11.7k
{
223
11.7k
    return [is, start, end](Pipeline* p) {
224
0
        auto data = is->read(QIntC::to_size(end - start), start);
225
0
        data = Pl_Base64::decode(data);
226
0
        p->write(reinterpret_cast<const unsigned char*>(data.data()), data.size());
227
0
        p->finish();
228
0
    };
229
11.7k
}
230
231
class QPDF::JSONReactor: public JSON::Reactor
232
{
233
  public:
234
    JSONReactor(QPDF& pdf, std::shared_ptr<InputSource> is, bool must_be_complete) :
235
15.8k
        pdf(pdf),
236
15.8k
        is(is),
237
15.8k
        must_be_complete(must_be_complete),
238
        descr(
239
15.8k
            std::make_shared<QPDFObject::Description>(
240
15.8k
                QPDFObject::JSON_Descr(std::make_shared<std::string>(is->getName()), "")))
241
15.8k
    {
242
15.8k
    }
243
15.8k
    ~JSONReactor() override = default;
244
    void dictionaryStart() override;
245
    void arrayStart() override;
246
    void containerEnd(JSON const& value) override;
247
    void topLevelScalar() override;
248
    bool dictionaryItem(std::string const& key, JSON const& value) override;
249
    bool arrayItem(JSON const& value) override;
250
251
    bool anyErrors() const;
252
253
  private:
254
    enum state_e {
255
        st_top,
256
        st_qpdf,
257
        st_qpdf_meta,
258
        st_objects,
259
        st_trailer,
260
        st_object_top,
261
        st_stream,
262
        st_object,
263
        st_ignore,
264
    };
265
266
    struct StackFrame
267
    {
268
        StackFrame(state_e state) :
269
68.8k
            state(state) {};
270
        StackFrame(state_e state, QPDFObjectHandle&& object) :
271
121k
            state(state),
272
121k
            object(object) {};
273
        state_e state;
274
        QPDFObjectHandle object;
275
    };
276
277
    void containerStart();
278
    bool setNextStateIfDictionary(std::string const& key, JSON const& value, state_e);
279
    void setObjectDescription(QPDFObjectHandle& oh, JSON const& value);
280
    QPDFObjectHandle makeObject(JSON const& value);
281
    void error(qpdf_offset_t offset, std::string const& message);
282
    void replaceObject(QPDFObjectHandle&& replacement, JSON const& value);
283
284
    QPDF& pdf;
285
    QPDF::Doc::Objects& objects = pdf.m->objects;
286
    std::shared_ptr<InputSource> is;
287
    bool must_be_complete{true};
288
    std::shared_ptr<QPDFObject::Description> descr;
289
    bool errors{false};
290
    bool saw_qpdf{false};
291
    bool saw_qpdf_meta{false};
292
    bool saw_objects{false};
293
    bool saw_json_version{false};
294
    bool saw_pdf_version{false};
295
    bool saw_trailer{false};
296
    std::string cur_object;
297
    bool saw_value{false};
298
    bool saw_stream{false};
299
    bool saw_dict{false};
300
    bool saw_data{false};
301
    bool saw_datafile{false};
302
    bool this_stream_needs_data{false};
303
    std::vector<StackFrame> stack;
304
    QPDFObjectHandle next_obj;
305
    state_e next_state{st_top};
306
};
307
308
void
309
QPDF::JSONReactor::error(qpdf_offset_t offset, std::string const& msg)
310
105k
{
311
105k
    errors = true;
312
105k
    std::string object = this->cur_object;
313
105k
    if (is->getName() != pdf.getFilename()) {
314
0
        object += " from " + is->getName();
315
0
    }
316
105k
    pdf.warn(qpdf_e_json, object, offset, msg);
317
105k
}
318
319
bool
320
QPDF::JSONReactor::anyErrors() const
321
141
{
322
141
    return errors;
323
141
}
324
325
void
326
QPDF::JSONReactor::containerStart()
327
190k
{
328
190k
    if (next_obj) {
329
121k
        stack.emplace_back(next_state, std::move(next_obj));
330
121k
        next_obj = QPDFObjectHandle();
331
121k
    } else {
332
68.8k
        stack.emplace_back(next_state);
333
68.8k
    }
334
190k
}
335
336
void
337
QPDF::JSONReactor::dictionaryStart()
338
145k
{
339
145k
    containerStart();
340
145k
}
341
342
void
343
QPDF::JSONReactor::arrayStart()
344
45.4k
{
345
45.4k
    if (stack.empty()) {
346
694
        QTC::TC("qpdf", "QPDF_json top-level array");
347
694
        throw std::runtime_error("QPDF JSON must be a dictionary");
348
694
    }
349
44.7k
    containerStart();
350
44.7k
}
351
352
void
353
QPDF::JSONReactor::containerEnd(JSON const& value)
354
85.6k
{
355
85.6k
    auto from_state = stack.back().state;
356
85.6k
    stack.pop_back();
357
85.6k
    if (stack.empty()) {
358
167
        if (!this->saw_qpdf) {
359
40
            QTC::TC("qpdf", "QPDF_json missing qpdf");
360
40
            error(0, "\"qpdf\" object was not seen");
361
127
        } else {
362
127
            if (!this->saw_json_version) {
363
98
                QTC::TC("qpdf", "QPDF_json missing json version");
364
98
                error(0, "\"qpdf[0].jsonversion\" was not seen");
365
98
            }
366
127
            if (must_be_complete && !this->saw_pdf_version) {
367
96
                QTC::TC("qpdf", "QPDF_json missing pdf version");
368
96
                error(0, "\"qpdf[0].pdfversion\" was not seen");
369
96
            }
370
127
            if (!this->saw_objects) {
371
17
                QTC::TC("qpdf", "QPDF_json missing objects");
372
17
                error(0, "\"qpdf[1]\" was not seen");
373
110
            } else {
374
110
                if (must_be_complete && !this->saw_trailer) {
375
77
                    QTC::TC("qpdf", "QPDF_json missing trailer");
376
77
                    error(0, "\"qpdf[1].trailer\" was not seen");
377
77
                }
378
110
            }
379
127
        }
380
85.4k
    } else if (from_state == st_trailer) {
381
1.25k
        if (!saw_value) {
382
713
            QTC::TC("qpdf", "QPDF_json trailer no value");
383
713
            error(value.getStart(), "\"trailer\" is missing \"value\"");
384
713
        }
385
84.1k
    } else if (from_state == st_object_top) {
386
19.5k
        if (saw_value == saw_stream) {
387
1.44k
            QTC::TC("qpdf", "QPDF_json value stream both or neither");
388
1.44k
            error(value.getStart(), "object must have exactly one of \"value\" or \"stream\"");
389
1.44k
        }
390
19.5k
        if (saw_stream) {
391
8.61k
            if (!saw_dict) {
392
3.10k
                QTC::TC("qpdf", "QPDF_json stream no dict");
393
3.10k
                error(value.getStart(), "\"stream\" is missing \"dict\"");
394
3.10k
            }
395
8.61k
            if (saw_data == saw_datafile) {
396
2.40k
                if (this_stream_needs_data) {
397
1.21k
                    QTC::TC("qpdf", "QPDF_json data datafile both or neither");
398
1.21k
                    error(
399
1.21k
                        value.getStart(),
400
1.21k
                        "new \"stream\" must have exactly one of \"data\" or \"datafile\"");
401
1.21k
                } else if (saw_datafile) {
402
281
                    QTC::TC("qpdf", "QPDF_json data and datafile");
403
281
                    error(
404
281
                        value.getStart(),
405
281
                        "existing \"stream\" may at most one of \"data\" or \"datafile\"");
406
910
                } else {
407
910
                    QTC::TC("qpdf", "QPDF_json no stream data in update mode");
408
910
                }
409
2.40k
            }
410
8.61k
        }
411
19.5k
    }
412
85.6k
    if (!stack.empty()) {
413
85.4k
        auto state = stack.back().state;
414
85.4k
        if (state == st_objects) {
415
23.7k
            this->cur_object = "";
416
23.7k
            this->saw_dict = false;
417
23.7k
            this->saw_data = false;
418
23.7k
            this->saw_datafile = false;
419
23.7k
            this->saw_value = false;
420
23.7k
            this->saw_stream = false;
421
23.7k
        }
422
85.4k
    }
423
85.6k
}
424
425
void
426
QPDF::JSONReactor::replaceObject(QPDFObjectHandle&& replacement, JSON const& value)
427
38.4k
{
428
38.4k
    auto& tos = stack.back();
429
38.4k
    auto og = tos.object.getObjGen();
430
38.4k
    if (replacement.isIndirect() && !(replacement.isStream() && replacement.getObjGen() == og)) {
431
1.41k
        error(
432
1.41k
            replacement.offset(), "the value of an object may not be an indirect object reference");
433
1.41k
        return;
434
1.41k
    }
435
37.0k
    pdf.replaceObject(og, replacement);
436
37.0k
    next_obj = pdf.getObject(og);
437
37.0k
    setObjectDescription(tos.object, value);
438
37.0k
}
439
440
void
441
QPDF::JSONReactor::topLevelScalar()
442
126
{
443
126
    QTC::TC("qpdf", "QPDF_json top-level scalar");
444
126
    throw std::runtime_error("QPDF JSON must be a dictionary");
445
126
}
446
447
bool
448
QPDF::JSONReactor::setNextStateIfDictionary(std::string const& key, JSON const& value, state_e next)
449
79.0k
{
450
    // Use this method when the next state is for processing a nested dictionary.
451
79.0k
    if (value.isDictionary()) {
452
65.1k
        this->next_state = next;
453
65.1k
        return true;
454
65.1k
    }
455
13.9k
    error(value.getStart(), "\"" + key + "\" must be a dictionary");
456
13.9k
    return false;
457
79.0k
}
458
459
bool
460
QPDF::JSONReactor::dictionaryItem(std::string const& key, JSON const& value)
461
426k
{
462
426k
    if (stack.empty()) {
463
0
        throw std::logic_error("stack is empty in dictionaryItem");
464
0
    }
465
426k
    next_state = st_ignore;
466
426k
    auto state = stack.back().state;
467
426k
    if (state == st_ignore) {
468
13.5k
        return true; // ignore
469
13.5k
    }
470
413k
    if (state == st_top) {
471
20.1k
        if (key == "qpdf") {
472
13.3k
            saw_qpdf = true;
473
13.3k
            if (!value.isArray()) {
474
1.60k
                error(value.getStart(), "\"qpdf\" must be an array");
475
11.7k
            } else {
476
11.7k
                next_state = st_qpdf;
477
11.7k
            }
478
13.3k
            return true;
479
13.3k
        }
480
6.84k
        return true; // Ignore all other fields.
481
20.1k
    }
482
483
393k
    if (state == st_qpdf_meta) {
484
15.8k
        if (key == "pdfversion") {
485
5.40k
            saw_pdf_version = true;
486
5.40k
            std::string v;
487
5.40k
            if (value.getString(v)) {
488
3.68k
                std::string version;
489
3.68k
                char const* p = v.c_str();
490
3.68k
                if (objects.validatePDFVersion(p, version) && *p == '\0') {
491
945
                    pdf.m->pdf_version = version;
492
945
                    return true;
493
945
                }
494
3.68k
            }
495
4.46k
            error(value.getStart(), "invalid PDF version (must be \"x.y\")");
496
4.46k
            return true;
497
5.40k
        }
498
10.4k
        if (key == "jsonversion") {
499
3.19k
            saw_json_version = true;
500
3.19k
            std::string v;
501
3.19k
            if (value.getNumber(v)) {
502
2.78k
                std::string version;
503
2.78k
                if (QUtil::string_to_int(v.c_str()) == 2) {
504
609
                    return true;
505
609
                }
506
2.78k
            }
507
2.58k
            error(value.getStart(), "invalid JSON version (must be numeric value 2)");
508
2.58k
            return true;
509
3.19k
        }
510
7.21k
        if (key == "pushedinheritedpageresources") {
511
1.01k
            bool v;
512
1.01k
            if (value.getBool(v)) {
513
474
                if (!must_be_complete && v) {
514
0
                    pdf.pushInheritedAttributesToPage();
515
0
                }
516
474
                return true;
517
474
            }
518
539
            error(value.getStart(), "pushedinheritedpageresources must be a boolean");
519
539
            return true;
520
1.01k
        }
521
6.19k
        if (key == "calledgetallpages") {
522
1.30k
            bool v;
523
1.30k
            if (value.getBool(v)) {
524
614
                if (!must_be_complete && v) {
525
0
                    (void)pdf.doc().pages().all();
526
0
                }
527
614
                return true;
528
614
            }
529
688
            error(value.getStart(), "calledgetallpages must be a boolean");
530
688
            return true;
531
1.30k
        }
532
        // ignore unknown keys for forward compatibility and to skip keys we don't care about
533
        // like "maxobjectid".
534
4.89k
        return true;
535
6.19k
    }
536
537
377k
    if (state == st_objects) {
538
46.2k
        if (key == "trailer") {
539
4.59k
            saw_trailer = true;
540
4.59k
            cur_object = "trailer";
541
4.59k
            setNextStateIfDictionary(key, value, st_trailer);
542
4.59k
            return true;
543
4.59k
        }
544
545
41.6k
        int obj = 0;
546
41.6k
        int gen = 0;
547
41.6k
        if (is_obj_key(key, obj, gen)) {
548
28.9k
            cur_object = key;
549
28.9k
            if (setNextStateIfDictionary(key, value, st_object_top)) {
550
26.3k
                next_obj = objects.getObjectForJSON(obj, gen);
551
26.3k
            }
552
28.9k
            return true;
553
28.9k
        }
554
12.6k
        error(value.getStart(), "object key should be \"trailer\" or \"obj:n n R\"");
555
12.6k
        return true;
556
41.6k
    }
557
558
330k
    if (state == st_object_top) {
559
51.4k
        util::assertion(!stack.empty(), "QPDF_json: stack empty in st_object_top");
560
51.4k
        auto& tos = stack.back();
561
51.4k
        util::assertion(!!tos.object, "current object uninitialized in st_object_top");
562
51.4k
        if (key == "value") {
563
            // Don't use setNextStateIfDictionary since this can have any type.
564
32.0k
            saw_value = true;
565
32.0k
            replaceObject(makeObject(value), value);
566
32.0k
            next_state = st_object;
567
32.0k
            return true;
568
32.0k
        }
569
19.4k
        if (key == "stream") {
570
13.2k
            saw_stream = true;
571
13.2k
            if (setNextStateIfDictionary(key, value, st_stream)) {
572
12.5k
                this_stream_needs_data = false;
573
12.5k
                if (tos.object.isStream()) {
574
5.47k
                    QTC::TC("qpdf", "QPDF_json updating existing stream");
575
7.09k
                } else {
576
7.09k
                    this_stream_needs_data = true;
577
7.09k
                    replaceObject(
578
7.09k
                        qpdf::Stream(
579
7.09k
                            pdf, tos.object.getObjGen(), QPDFObjectHandle::newDictionary(), 0, 0),
580
7.09k
                        value);
581
7.09k
                }
582
12.5k
                next_obj = tos.object;
583
12.5k
                return true;
584
12.5k
            }
585
654
            return true; // Error message already given above
586
13.2k
        }
587
6.20k
        return true; // Ignore unknown keys for forward compatibility
588
19.4k
    }
589
590
279k
    if (state == st_trailer) {
591
6.45k
        if (key == "value") {
592
3.63k
            saw_value = true;
593
            // The trailer must be a dictionary, so we can use setNextStateIfDictionary.
594
3.63k
            if (setNextStateIfDictionary("trailer.value", value, st_object)) {
595
2.45k
                pdf.m->trailer = makeObject(value);
596
2.45k
                setObjectDescription(pdf.m->trailer, value);
597
2.45k
            }
598
3.63k
            return true;
599
3.63k
        }
600
2.82k
        if (key == "stream") {
601
            // Don't need to set saw_stream here since there's already an error.
602
910
            error(value.getStart(), "the trailer may not be a stream");
603
910
            return true;
604
910
        }
605
1.91k
        return true; // Ignore unknown keys for forward compatibility
606
2.82k
    }
607
608
273k
    if (state == st_stream) {
609
29.6k
        util::assertion(!stack.empty(), "stack empty in st_stream");
610
29.6k
        auto& tos = stack.back();
611
29.6k
        util::assertion(tos.object.isStream(), "current object is not stream in st_stream");
612
29.6k
        if (key == "dict") {
613
7.03k
            saw_dict = true;
614
7.03k
            if (setNextStateIfDictionary("stream.dict", value, st_object)) {
615
5.94k
                tos.object.replaceDict(makeObject(value));
616
5.94k
                return true;
617
5.94k
            }
618
1.08k
            return true; // An error had already been given by setNextStateIfDictionary
619
7.03k
        }
620
22.6k
        if (key == "data") {
621
17.4k
            saw_data = true;
622
17.4k
            std::string v;
623
17.4k
            if (!value.getString(v)) {
624
5.69k
                error(value.getStart(), "\"stream.data\" must be a string");
625
5.69k
                tos.object.replaceStreamData("", {}, {});
626
5.69k
                return true;
627
5.69k
            }
628
            // The range includes the quotes.
629
11.7k
            auto start = value.getStart() + 1;
630
11.7k
            auto end = value.getEnd() - 1;
631
11.7k
            util::assertion(end >= start, "QPDF_json: JSON string length < 0");
632
11.7k
            tos.object.replaceStreamData(provide_data(is, start, end), {}, {});
633
11.7k
            return true;
634
17.4k
        }
635
5.16k
        if (key == "datafile") {
636
3.12k
            saw_datafile = true;
637
3.12k
            std::string filename;
638
3.12k
            if (!value.getString(filename)) {
639
643
                error(
640
643
                    value.getStart(),
641
643
                    "\"stream.datafile\" must be a string containing a file name");
642
643
                tos.object.replaceStreamData("", {}, {});
643
643
                return true;
644
643
            }
645
2.47k
            tos.object.replaceStreamData(QUtil::file_provider(filename), {}, {});
646
2.47k
            return true;
647
3.12k
        }
648
2.04k
        return true; // Ignore unknown keys for forward compatibility.
649
5.16k
    }
650
651
243k
    util::assertion(state == st_object, "QPDF_json: unknown state " + std::to_string(state));
652
243k
    util::assertion(!stack.empty(), "stack empty in st_object");
653
243k
    auto& tos = stack.back();
654
243k
    auto dict = tos.object;
655
243k
    if (dict.isStream()) {
656
0
        dict = dict.getDict();
657
0
    }
658
243k
    util::assertion(
659
243k
        dict.isDictionary(),
660
243k
        "current object is not stream or dictionary in st_object dictionary item");
661
243k
    dict.replaceKey(
662
243k
        is_pdf_name(key) ? QPDFObjectHandle::parse(key.substr(2)).getName() : key,
663
243k
        makeObject(value));
664
243k
    return true;
665
273k
}
666
667
bool
668
QPDF::JSONReactor::arrayItem(JSON const& value)
669
4.85M
{
670
4.85M
    if (stack.empty()) {
671
0
        throw std::logic_error("stack is empty in arrayItem");
672
0
    }
673
4.85M
    next_state = st_ignore;
674
4.85M
    auto state = stack.back().state;
675
4.85M
    if (state == st_qpdf) {
676
30.3k
        if (!this->saw_qpdf_meta) {
677
11.3k
            this->saw_qpdf_meta = true;
678
11.3k
            setNextStateIfDictionary("qpdf[0]", value, st_qpdf_meta);
679
19.0k
        } else if (!this->saw_objects) {
680
10.2k
            this->saw_objects = true;
681
10.2k
            setNextStateIfDictionary("qpdf[1]", value, st_objects);
682
10.2k
        } else {
683
8.81k
            QTC::TC("qpdf", "QPDF_json more than two qpdf elements");
684
8.81k
            error(value.getStart(), "\"qpdf\" must have two elements");
685
8.81k
        }
686
4.82M
    } else if (state == st_object) {
687
4.80M
        stack.back().object.appendItem(makeObject(value));
688
4.80M
    }
689
4.85M
    return true;
690
4.85M
}
691
692
void
693
QPDF::JSONReactor::setObjectDescription(QPDFObjectHandle& oh, JSON const& value)
694
3.93M
{
695
3.93M
    auto j_descr = std::get<QPDFObject::JSON_Descr>(*descr);
696
3.93M
    if (j_descr.object != cur_object) {
697
21.4k
        descr = std::make_shared<QPDFObject::Description>(
698
21.4k
            QPDFObject::JSON_Descr(j_descr.input, cur_object));
699
21.4k
    }
700
701
3.93M
    oh.obj_sp()->setDescription(&pdf, descr, value.getStart());
702
3.93M
}
703
704
QPDFObjectHandle
705
QPDF::JSONReactor::makeObject(JSON const& value)
706
5.09M
{
707
5.09M
    QPDFObjectHandle result;
708
5.09M
    std::string str_v;
709
5.09M
    bool bool_v = false;
710
5.09M
    if (value.isDictionary()) {
711
56.9k
        result = QPDFObjectHandle::newDictionary();
712
56.9k
        next_obj = result;
713
56.9k
        next_state = st_object;
714
5.03M
    } else if (value.isArray()) {
715
25.1k
        result = QPDFObjectHandle::newArray();
716
25.1k
        next_obj = result;
717
25.1k
        next_state = st_object;
718
5.00M
    } else if (value.isNull()) {
719
4.13k
        result = QPDFObjectHandle::newNull();
720
5.00M
    } else if (value.getBool(bool_v)) {
721
6.40k
        result = QPDFObjectHandle::newBool(bool_v);
722
4.99M
    } else if (value.getNumber(str_v)) {
723
3.71M
        if (QUtil::is_long_long(str_v.c_str())) {
724
3.70M
            result = QPDFObjectHandle::newInteger(QUtil::string_to_ll(str_v.c_str()));
725
3.70M
        } else {
726
            // JSON allows scientific notation, but PDF does not.
727
12.2k
            if (str_v.find('e') != std::string::npos || str_v.find('E') != std::string::npos) {
728
6.46k
                try {
729
6.46k
                    auto v = std::stod(str_v);
730
6.46k
                    str_v = QUtil::double_to_string(v);
731
6.46k
                } catch (std::exception&) {
732
                    // Keep it as it was
733
413
                }
734
6.46k
            }
735
12.2k
            result = QPDFObjectHandle::newReal(str_v);
736
12.2k
        }
737
3.71M
    } else if (value.getString(str_v)) {
738
1.28M
        int obj = 0;
739
1.28M
        int gen = 0;
740
1.28M
        std::string str;
741
1.28M
        if (is_indirect_object(str_v, obj, gen)) {
742
1.18M
            result = objects.getObjectForJSON(obj, gen);
743
1.18M
        } else if (is_unicode_string(str_v, str)) {
744
10.3k
            result = QPDFObjectHandle::newUnicodeString(str);
745
88.4k
        } else if (is_binary_string(str_v, str)) {
746
2.24k
            result = QPDFObjectHandle::newString(QUtil::hex_decode(str));
747
86.2k
        } else if (is_name(str_v)) {
748
26.8k
            result = QPDFObjectHandle::newName(str_v);
749
59.3k
        } else if (is_pdf_name(str_v)) {
750
15.2k
            result = QPDFObjectHandle::parse(str_v.substr(2));
751
44.1k
        } else {
752
44.1k
            QTC::TC("qpdf", "QPDF_json unrecognized string value");
753
44.1k
            error(value.getStart(), "unrecognized string value");
754
44.1k
            result = QPDFObjectHandle::newNull();
755
44.1k
        }
756
1.28M
    }
757
5.09M
    if (!result) {
758
0
        throw std::logic_error("JSONReactor::makeObject didn't initialize the object");
759
0
    }
760
761
5.09M
    if (!result.hasObjectDescription()) {
762
3.89M
        setObjectDescription(result, value);
763
3.89M
    }
764
5.09M
    return result;
765
5.09M
}
766
767
void
768
QPDF::createFromJSON(std::string const& json_file)
769
0
{
770
0
    createFromJSON(std::make_shared<FileInputSource>(json_file.c_str()));
771
0
}
772
773
void
774
QPDF::createFromJSON(std::shared_ptr<InputSource> is)
775
15.8k
{
776
15.8k
    auto mw = m->cf.max_warnings();
777
15.8k
    (void)m->cf.max_warnings(0);
778
15.8k
    processMemoryFile(is->getName().c_str(), JSON_PDF, strlen(JSON_PDF));
779
15.8k
    (void)m->cf.max_warnings(mw);
780
15.8k
    importJSON(is, true);
781
15.8k
    (void)m->cf.max_warnings(0);
782
15.8k
}
783
784
void
785
QPDF::updateFromJSON(std::string const& json_file)
786
0
{
787
0
    updateFromJSON(std::make_shared<FileInputSource>(json_file.c_str()));
788
0
}
789
790
void
791
QPDF::updateFromJSON(std::shared_ptr<InputSource> is)
792
0
{
793
0
    importJSON(is, false);
794
0
}
795
796
void
797
QPDF::importJSON(std::shared_ptr<InputSource> is, bool must_be_complete)
798
15.8k
{
799
15.8k
    JSONReactor reactor(*this, is, must_be_complete);
800
15.8k
    try {
801
15.8k
        JSON::parse(*is, &reactor);
802
15.8k
    } catch (std::runtime_error& e) {
803
15.6k
        throw std::runtime_error(is->getName() + ": " + e.what());
804
15.6k
    }
805
141
    if (reactor.anyErrors()) {
806
118
        throw std::runtime_error(is->getName() + ": errors found in JSON");
807
118
    }
808
141
}
809
810
void
811
writeJSONStreamFile(
812
    int version,
813
    JSON::Writer& jw,
814
    qpdf::Stream& stream,
815
    int id,
816
    qpdf_stream_decode_level_e decode_level,
817
    std::string const& file_prefix)
818
0
{
819
0
    auto filename = file_prefix + "-" + std::to_string(id);
820
0
    auto* f = QUtil::safe_fopen(filename.c_str(), "wb");
821
0
    Pl_StdioFile f_pl{"stream data", f};
822
0
    stream.writeStreamJSON(version, jw, qpdf_sj_file, decode_level, &f_pl, filename);
823
0
    f_pl.finish();
824
0
    fclose(f);
825
0
}
826
827
void
828
QPDF::writeJSON(
829
    int version,
830
    Pipeline* p,
831
    qpdf_stream_decode_level_e decode_level,
832
    qpdf_json_stream_data_e json_stream_data,
833
    std::string const& file_prefix,
834
    std::set<std::string> wanted_objects)
835
0
{
836
0
    bool first = true;
837
0
    writeJSON(version, p, true, first, decode_level, json_stream_data, file_prefix, wanted_objects);
838
0
}
839
840
void
841
QPDF::writeJSON(
842
    int version,
843
    Pipeline* p,
844
    bool complete,
845
    bool& first_key,
846
    qpdf_stream_decode_level_e decode_level,
847
    qpdf_json_stream_data_e json_stream_data,
848
    std::string const& file_prefix,
849
    std::set<std::string> wanted_objects)
850
0
{
851
0
    if (version != 2) {
852
0
        throw std::runtime_error("QPDF::writeJSON: only version 2 is supported");
853
0
    }
854
0
    JSON::Writer jw{p, 4};
855
0
    if (complete) {
856
0
        jw << "{";
857
0
    } else if (!first_key) {
858
0
        jw << ",";
859
0
    }
860
0
    first_key = false;
861
862
    /* clang-format off */
863
0
    jw << "\n"
864
0
          "  \"qpdf\": [\n"
865
0
          "    {\n"
866
0
          "      \"jsonversion\": " << std::to_string(version) << ",\n"
867
0
          "      \"pdfversion\": \"" << getPDFVersion() << "\",\n"
868
0
          "      \"pushedinheritedpageresources\": " <<  (everPushedInheritedAttributesToPages() ? "true" : "false") << ",\n"
869
0
          "      \"calledgetallpages\": " <<  (everCalledGetAllPages() ? "true" : "false") << ",\n"
870
0
          "      \"maxobjectid\": " <<  std::to_string(getObjectCount()) << "\n"
871
0
          "    },\n"
872
0
          "    {";
873
    /* clang-format on */
874
875
0
    bool all_objects = wanted_objects.empty();
876
0
    bool first = true;
877
0
    for (auto& obj: getAllObjects()) {
878
0
        auto const og = obj.getObjGen();
879
0
        std::string key = "obj:" + og.unparse(' ') + " R";
880
0
        if (all_objects || wanted_objects.contains(key)) {
881
0
            if (first) {
882
0
                jw << "\n      \"" << key;
883
0
                first = false;
884
0
            } else {
885
0
                jw << "\n      },\n      \"" << key;
886
0
            }
887
0
            if (Stream stream = obj) {
888
0
                jw << "\": {\n        \"stream\": ";
889
0
                if (json_stream_data == qpdf_sj_file) {
890
0
                    writeJSONStreamFile(
891
0
                        version, jw, stream, og.getObj(), decode_level, file_prefix);
892
0
                } else {
893
0
                    stream.writeStreamJSON(
894
0
                        version, jw, json_stream_data, decode_level, nullptr, "");
895
0
                }
896
0
            } else {
897
0
                jw << "\": {\n        \"value\": ";
898
0
                obj.writeJSON(version, jw, true);
899
0
            }
900
0
        }
901
0
    }
902
0
    if (all_objects || wanted_objects.contains("trailer")) {
903
0
        if (!first) {
904
0
            jw << "\n      },";
905
0
        }
906
0
        jw << "\n      \"trailer\": {\n        \"value\": ";
907
0
        getTrailer().writeJSON(version, jw, true);
908
0
        first = false;
909
0
    }
910
0
    if (!first) {
911
0
        jw << "\n      }";
912
0
    }
913
    /* clang-format off */
914
0
    jw << "\n"
915
0
          "    }\n"
916
0
          "  ]";
917
    /* clang-format on */
918
0
    if (complete) {
919
0
        jw << "\n}\n";
920
0
        p->finish();
921
0
    }
922
0
}