Coverage Report

Created: 2025-11-11 07:02

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/qpdf/libqpdf/QPDFAcroFormDocumentHelper.cc
Line
Count
Source
1
#include <qpdf/QPDFAcroFormDocumentHelper.hh>
2
3
#include <qpdf/Pl_Buffer.hh>
4
#include <qpdf/QPDFObjectHandle_private.hh>
5
#include <qpdf/QPDFPageDocumentHelper.hh>
6
#include <qpdf/QPDF_private.hh>
7
#include <qpdf/QTC.hh>
8
#include <qpdf/QUtil.hh>
9
#include <qpdf/ResourceFinder.hh>
10
11
#include <deque>
12
#include <utility>
13
14
using namespace qpdf;
15
using namespace std::literals;
16
17
class QPDFAcroFormDocumentHelper::Members
18
{
19
  public:
20
0
    Members() = default;
21
    Members(Members const&) = delete;
22
0
    ~Members() = default;
23
24
    struct FieldData
25
    {
26
        std::vector<QPDFAnnotationObjectHelper> annotations;
27
        std::string name;
28
    };
29
30
    bool cache_valid{false};
31
    std::map<QPDFObjGen, FieldData> field_to;
32
    std::map<QPDFObjGen, QPDFFormFieldObjectHelper> annotation_to_field;
33
    std::map<std::string, std::set<QPDFObjGen>> name_to_fields;
34
};
35
36
QPDFAcroFormDocumentHelper::QPDFAcroFormDocumentHelper(QPDF& qpdf) :
37
0
    QPDFDocumentHelper(qpdf),
38
0
    m(std::make_shared<Members>())
39
0
{
40
    // We have to analyze up front. Otherwise, when we are adding annotations and fields, we are in
41
    // a temporarily unstable configuration where some widget annotations are not reachable.
42
0
    analyze();
43
0
}
44
45
QPDFAcroFormDocumentHelper&
46
QPDFAcroFormDocumentHelper::get(QPDF& qpdf)
47
0
{
48
0
    return qpdf.doc().acroform();
49
0
}
50
51
void
52
QPDFAcroFormDocumentHelper::validate(bool repair)
53
0
{
54
0
    invalidateCache();
55
0
    analyze();
56
0
}
57
58
void
59
QPDFAcroFormDocumentHelper::invalidateCache()
60
0
{
61
0
    m->cache_valid = false;
62
0
    m->field_to.clear();
63
0
    m->annotation_to_field.clear();
64
0
}
65
66
bool
67
QPDFAcroFormDocumentHelper::hasAcroForm()
68
0
{
69
0
    return qpdf.getRoot().hasKey("/AcroForm");
70
0
}
71
72
QPDFObjectHandle
73
QPDFAcroFormDocumentHelper::getOrCreateAcroForm()
74
0
{
75
0
    auto acroform = qpdf.getRoot().getKey("/AcroForm");
76
0
    if (!acroform.isDictionary()) {
77
0
        acroform = qpdf.getRoot().replaceKeyAndGetNew(
78
0
            "/AcroForm", qpdf.makeIndirectObject(QPDFObjectHandle::newDictionary()));
79
0
    }
80
0
    return acroform;
81
0
}
82
83
void
84
QPDFAcroFormDocumentHelper::addFormField(QPDFFormFieldObjectHelper ff)
85
0
{
86
0
    auto acroform = getOrCreateAcroForm();
87
0
    auto fields = acroform.getKey("/Fields");
88
0
    if (!fields.isArray()) {
89
0
        fields = acroform.replaceKeyAndGetNew("/Fields", QPDFObjectHandle::newArray());
90
0
    }
91
0
    fields.appendItem(ff.getObjectHandle());
92
0
    traverseField(ff.getObjectHandle(), {}, 0);
93
0
}
94
95
void
96
QPDFAcroFormDocumentHelper::addAndRenameFormFields(std::vector<QPDFObjectHandle> fields)
97
0
{
98
0
    analyze();
99
0
    std::map<std::string, std::string> renames;
100
0
    QPDFObjGen::set seen;
101
0
    for (std::list<QPDFObjectHandle> queue{fields.begin(), fields.end()}; !queue.empty();
102
0
         queue.pop_front()) {
103
0
        auto& obj = queue.front();
104
0
        if (seen.add(obj)) {
105
0
            auto kids = obj.getKey("/Kids");
106
0
            if (kids.isArray()) {
107
0
                for (auto const& kid: kids.aitems()) {
108
0
                    queue.push_back(kid);
109
0
                }
110
0
            }
111
112
0
            if (obj.hasKey("/T")) {
113
                // Find something we can append to the partial name that makes the fully qualified
114
                // name unique. When we find something, reuse the same suffix for all fields in this
115
                // group with the same name. We can only change the name of fields that have /T, and
116
                // this field's /T is always at the end of the fully qualified name, appending to /T
117
                // has the effect of appending the same thing to the fully qualified name.
118
0
                std::string old_name = QPDFFormFieldObjectHelper(obj).getFullyQualifiedName();
119
0
                if (!renames.contains(old_name)) {
120
0
                    std::string new_name = old_name;
121
0
                    int suffix = 0;
122
0
                    std::string append;
123
0
                    while (!getFieldsWithQualifiedName(new_name).empty()) {
124
0
                        ++suffix;
125
0
                        append = "+" + std::to_string(suffix);
126
0
                        new_name = old_name + append;
127
0
                    }
128
0
                    renames[old_name] = append;
129
0
                }
130
0
                std::string append = renames[old_name];
131
0
                if (!append.empty()) {
132
0
                    obj.replaceKey(
133
0
                        "/T",
134
0
                        QPDFObjectHandle::newUnicodeString(
135
0
                            obj.getKey("/T").getUTF8Value() + append));
136
0
                }
137
0
            }
138
0
        }
139
0
    }
140
141
0
    for (auto const& i: fields) {
142
0
        addFormField(i);
143
0
    }
144
0
}
145
146
void
147
QPDFAcroFormDocumentHelper::removeFormFields(std::set<QPDFObjGen> const& to_remove)
148
0
{
149
0
    auto acroform = qpdf.getRoot().getKey("/AcroForm");
150
0
    if (!acroform.isDictionary()) {
151
0
        return;
152
0
    }
153
0
    auto fields = acroform.getKey("/Fields");
154
0
    if (!fields.isArray()) {
155
0
        return;
156
0
    }
157
158
0
    for (auto const& og: to_remove) {
159
0
        auto it = m->field_to.find(og);
160
0
        if (it != m->field_to.end()) {
161
0
            for (auto aoh: it->second.annotations) {
162
0
                m->annotation_to_field.erase(aoh.getObjectHandle().getObjGen());
163
0
            }
164
0
            auto const& name = it->second.name;
165
0
            if (!name.empty()) {
166
0
                m->name_to_fields[name].erase(og);
167
0
                if (m->name_to_fields[name].empty()) {
168
0
                    m->name_to_fields.erase(name);
169
0
                }
170
0
            }
171
0
            m->field_to.erase(og);
172
0
        }
173
0
    }
174
175
0
    int i = 0;
176
0
    while (std::cmp_less(i, fields.size())) {
177
0
        auto field = fields.getArrayItem(i);
178
0
        if (to_remove.contains(field.getObjGen())) {
179
0
            fields.eraseItem(i);
180
0
        } else {
181
0
            ++i;
182
0
        }
183
0
    }
184
0
}
185
186
void
187
QPDFAcroFormDocumentHelper::setFormFieldName(QPDFFormFieldObjectHelper ff, std::string const& name)
188
0
{
189
0
    ff.setFieldAttribute("/T", name);
190
0
    traverseField(ff, ff["/Parent"], 0);
191
0
}
192
193
std::vector<QPDFFormFieldObjectHelper>
194
QPDFAcroFormDocumentHelper::getFormFields()
195
0
{
196
0
    analyze();
197
0
    std::vector<QPDFFormFieldObjectHelper> result;
198
0
    for (auto const& [og, data]: m->field_to) {
199
0
        if (!data.annotations.empty()) {
200
0
            result.emplace_back(qpdf.getObject(og));
201
0
        }
202
0
    }
203
0
    return result;
204
0
}
205
206
std::set<QPDFObjGen>
207
QPDFAcroFormDocumentHelper::getFieldsWithQualifiedName(std::string const& name)
208
0
{
209
0
    analyze();
210
    // Keep from creating an empty entry
211
0
    auto iter = m->name_to_fields.find(name);
212
0
    if (iter != m->name_to_fields.end()) {
213
0
        return iter->second;
214
0
    }
215
0
    return {};
216
0
}
217
218
std::vector<QPDFAnnotationObjectHelper>
219
QPDFAcroFormDocumentHelper::getAnnotationsForField(QPDFFormFieldObjectHelper h)
220
0
{
221
0
    analyze();
222
0
    std::vector<QPDFAnnotationObjectHelper> result;
223
0
    QPDFObjGen og(h.getObjectHandle().getObjGen());
224
0
    if (m->field_to.contains(og)) {
225
0
        result = m->field_to[og].annotations;
226
0
    }
227
0
    return result;
228
0
}
229
230
std::vector<QPDFAnnotationObjectHelper>
231
QPDFAcroFormDocumentHelper::getWidgetAnnotationsForPage(QPDFPageObjectHelper h)
232
0
{
233
0
    return h.getAnnotations("/Widget");
234
0
}
235
236
std::vector<QPDFFormFieldObjectHelper>
237
QPDFAcroFormDocumentHelper::getFormFieldsForPage(QPDFPageObjectHelper ph)
238
0
{
239
0
    analyze();
240
0
    QPDFObjGen::set todo;
241
0
    std::vector<QPDFFormFieldObjectHelper> result;
242
0
    for (auto& annot: getWidgetAnnotationsForPage(ph)) {
243
0
        auto field = getFieldForAnnotation(annot).getTopLevelField();
244
0
        if (todo.add(field) && field.getObjectHandle().isDictionary()) {
245
0
            result.push_back(field);
246
0
        }
247
0
    }
248
0
    return result;
249
0
}
250
251
QPDFFormFieldObjectHelper
252
QPDFAcroFormDocumentHelper::getFieldForAnnotation(QPDFAnnotationObjectHelper h)
253
0
{
254
0
    QPDFObjectHandle oh = h.getObjectHandle();
255
0
    if (!oh.isDictionaryOfType("", "/Widget")) {
256
0
        return Null::temp();
257
0
    }
258
0
    analyze();
259
0
    QPDFObjGen og(oh.getObjGen());
260
0
    if (m->annotation_to_field.contains(og)) {
261
0
        return m->annotation_to_field[og];
262
0
    }
263
0
    return Null::temp();
264
0
}
265
266
void
267
QPDFAcroFormDocumentHelper::analyze()
268
0
{
269
0
    if (m->cache_valid) {
270
0
        return;
271
0
    }
272
0
    m->cache_valid = true;
273
0
    QPDFObjectHandle acroform = qpdf.getRoot().getKey("/AcroForm");
274
0
    if (!(acroform.isDictionary() && acroform.hasKey("/Fields"))) {
275
0
        return;
276
0
    }
277
0
    QPDFObjectHandle fields = acroform.getKey("/Fields");
278
0
    if (Array fa = fields) {
279
        // Traverse /AcroForm to find annotations and map them bidirectionally to fields.
280
0
        for (auto const& field: fa) {
281
0
            traverseField(field, {}, 0);
282
0
        }
283
0
    } else {
284
0
        acroform.warn("/Fields key of /AcroForm dictionary is not an array; ignoring");
285
0
        fields = Array::empty();
286
0
    }
287
288
    // All Widget annotations should have been encountered by traversing /AcroForm, but in case any
289
    // weren't, find them by walking through pages, and treat any widget annotation that is not
290
    // associated with a field as its own field. This just ensures that requesting the field for any
291
    // annotation we find through a page's /Annots list will have some associated field. Note that
292
    // a file that contains this kind of error will probably not
293
    // actually work with most viewers.
294
295
0
    for (auto const& ph: QPDFPageDocumentHelper(qpdf).getAllPages()) {
296
0
        for (auto const& iter: getWidgetAnnotationsForPage(ph)) {
297
0
            QPDFObjectHandle annot(iter.getObjectHandle());
298
0
            QPDFObjGen og(annot.getObjGen());
299
0
            if (!m->annotation_to_field.contains(og)) {
300
                // This is not supposed to happen, but it's easy enough for us to handle this case.
301
                // Treat the annotation as its own field. This could allow qpdf to sensibly handle a
302
                // case such as a PDF creator adding a self-contained annotation (merged with the
303
                // field dictionary) to the page's /Annots array and forgetting to also put it in
304
                // /AcroForm.
305
0
                annot.warn(
306
0
                    "this widget annotation is not reachable from /AcroForm in the document "
307
0
                    "catalog");
308
0
                m->annotation_to_field[og] = QPDFFormFieldObjectHelper(annot);
309
0
                m->field_to[og].annotations.emplace_back(annot);
310
0
            }
311
0
        }
312
0
    }
313
0
}
314
315
void
316
QPDFAcroFormDocumentHelper::traverseField(
317
    QPDFObjectHandle field, QPDFObjectHandle const& parent, int depth)
318
0
{
319
0
    if (depth > 100) {
320
        // Arbitrarily cut off recursion at a fixed depth to avoid specially crafted files that
321
        // could cause stack overflow.
322
0
        return;
323
0
    }
324
0
    if (!field.indirect()) {
325
0
        field.warn(
326
0
            "encountered a direct object as a field or annotation while traversing /AcroForm; "
327
0
            "ignoring field or annotation");
328
0
        return;
329
0
    }
330
0
    if (field == parent) {
331
0
        field.warn("loop detected while traversing /AcroForm");
332
0
        return;
333
0
    }
334
0
    if (!field.isDictionary()) {
335
0
        field.warn(
336
0
            "encountered a non-dictionary as a field or annotation while traversing /AcroForm; "
337
0
            "ignoring field or annotation");
338
0
        return;
339
0
    }
340
0
    QPDFObjGen og(field.getObjGen());
341
0
    if (m->field_to.contains(og) || m->annotation_to_field.contains(og)) {
342
0
        field.warn("loop detected while traversing /AcroForm");
343
0
        return;
344
0
    }
345
346
    // A dictionary encountered while traversing the /AcroForm field may be a form field, an
347
    // annotation, or the merger of the two. A field that has no fields below it is a terminal. If a
348
    // terminal field looks like an annotation, it is an annotation because annotation dictionary
349
    // fields can be merged with terminal field dictionaries. Otherwise, the annotation fields might
350
    // be there to be inherited by annotations below it.
351
352
0
    Array Kids = field["/Kids"];
353
0
    const bool is_field = depth == 0 || Kids || field.hasKey("/Parent");
354
0
    const bool is_annotation =
355
0
        !Kids && (field.hasKey("/Subtype") || field.hasKey("/Rect") || field.hasKey("/AP"));
356
357
0
    QTC::TC("qpdf", "QPDFAcroFormDocumentHelper field found", (depth == 0) ? 0 : 1);
358
0
    QTC::TC("qpdf", "QPDFAcroFormDocumentHelper annotation found", (is_field ? 0 : 1));
359
360
0
    if (is_annotation) {
361
0
        QPDFObjectHandle our_field = (is_field ? field : parent);
362
0
        m->field_to[our_field.getObjGen()].annotations.emplace_back(field);
363
0
        m->annotation_to_field[og] = QPDFFormFieldObjectHelper(our_field);
364
0
    }
365
366
0
    if (is_field && depth != 0 && field["/Parent"] != parent) {
367
0
        for (auto const& kid: Array(field["/Parent"]["/Kids"])) {
368
0
            if (kid == parent) {
369
0
                field.warn("loop detected while traversing /AcroForm");
370
0
                return;
371
0
            }
372
0
        }
373
0
        field.warn("encountered invalid /Parent entry while traversing /AcroForm; correcting");
374
0
        field.replaceKey("/Parent", parent);
375
0
    }
376
377
0
    if (is_field && field.hasKey("/T")) {
378
0
        QPDFFormFieldObjectHelper foh(field);
379
0
        std::string name = foh.getFullyQualifiedName();
380
0
        auto old = m->field_to.find(og);
381
0
        if (old != m->field_to.end() && !old->second.name.empty()) {
382
            // We might be updating after a name change, so remove any old information
383
0
            m->name_to_fields[old->second.name].erase(og);
384
0
        }
385
0
        m->field_to[og].name = name;
386
0
        m->name_to_fields[name].insert(og);
387
0
    }
388
389
0
    for (auto const& kid: Kids) {
390
0
        traverseField(kid, field, 1 + depth);
391
0
    }
392
0
}
393
394
bool
395
QPDFAcroFormDocumentHelper::getNeedAppearances()
396
0
{
397
0
    bool result = false;
398
0
    QPDFObjectHandle acroform = qpdf.getRoot().getKey("/AcroForm");
399
0
    if (acroform.isDictionary() && acroform.getKey("/NeedAppearances").isBool()) {
400
0
        result = acroform.getKey("/NeedAppearances").getBoolValue();
401
0
    }
402
0
    return result;
403
0
}
404
405
void
406
QPDFAcroFormDocumentHelper::setNeedAppearances(bool val)
407
0
{
408
0
    QPDFObjectHandle acroform = qpdf.getRoot().getKey("/AcroForm");
409
0
    if (!acroform.isDictionary()) {
410
0
        qpdf.getRoot().warn(
411
0
            "ignoring call to QPDFAcroFormDocumentHelper::setNeedAppearances"
412
0
            " on a file that lacks an /AcroForm dictionary");
413
0
        return;
414
0
    }
415
0
    if (val) {
416
0
        acroform.replaceKey("/NeedAppearances", QPDFObjectHandle::newBool(true));
417
0
    } else {
418
0
        acroform.removeKey("/NeedAppearances");
419
0
    }
420
0
}
421
422
void
423
QPDFAcroFormDocumentHelper::generateAppearancesIfNeeded()
424
0
{
425
0
    if (!getNeedAppearances()) {
426
0
        return;
427
0
    }
428
429
0
    for (auto const& page: QPDFPageDocumentHelper(qpdf).getAllPages()) {
430
0
        for (auto& aoh: getWidgetAnnotationsForPage(page)) {
431
0
            QPDFFormFieldObjectHelper ffh = getFieldForAnnotation(aoh);
432
0
            if (ffh.getFieldType() == "/Btn") {
433
                // Rather than generating appearances for button fields, rely on what's already
434
                // there. Just make sure /AS is consistent with /V, which we can do by resetting the
435
                // value of the field back to itself. This code is referenced in a comment in
436
                // QPDFFormFieldObjectHelper::generateAppearance.
437
0
                if (ffh.isRadioButton() || ffh.isCheckbox()) {
438
0
                    ffh.setV(ffh.getValue());
439
0
                }
440
0
            } else {
441
0
                ffh.generateAppearance(aoh);
442
0
            }
443
0
        }
444
0
    }
445
0
    setNeedAppearances(false);
446
0
}
447
448
void
449
QPDFAcroFormDocumentHelper::disableDigitalSignatures()
450
0
{
451
0
    qpdf.removeSecurityRestrictions();
452
0
    std::set<QPDFObjGen> to_remove;
453
0
    auto fields = getFormFields();
454
0
    for (auto& f: fields) {
455
0
        auto ft = f.getFieldType();
456
0
        if (ft == "/Sig") {
457
0
            auto oh = f.getObjectHandle();
458
0
            to_remove.insert(oh.getObjGen());
459
            // Make this no longer a form field. If it's also an annotation, the annotation will
460
            // survive. If it's only a field and is no longer referenced, it will disappear.
461
0
            oh.removeKey("/FT");
462
            // Remove fields that are specific to signature fields.
463
0
            oh.removeKey("/V");
464
0
            oh.removeKey("/SV");
465
0
            oh.removeKey("/Lock");
466
0
        }
467
0
    }
468
0
    removeFormFields(to_remove);
469
0
}
470
471
void
472
QPDFAcroFormDocumentHelper::adjustInheritedFields(
473
    QPDFObjectHandle obj,
474
    bool override_da,
475
    std::string const& from_default_da,
476
    bool override_q,
477
    int from_default_q)
478
0
{
479
0
    if (!(override_da || override_q)) {
480
0
        return;
481
0
    }
482
    // Override /Q or /DA if needed. If this object has a field type, directly or inherited, it is a
483
    // field and not just an annotation. In that case, we need to override if we are getting a value
484
    // from the document that is different from the value we would have gotten from the old
485
    // document. We must take care not to override an explicit value. It's possible that /FT may be
486
    // inherited by lower fields that may explicitly set /DA or /Q or that this is a field whose
487
    // type does not require /DA or /Q and we may be put a value on the field that is unused. This
488
    // is harmless, so it's not worth trying to work around.
489
490
0
    auto has_explicit = [](QPDFFormFieldObjectHelper& field, std::string const& key) {
491
0
        if (field.getObjectHandle().hasKey(key)) {
492
0
            return true;
493
0
        }
494
0
        return !field.getInheritableFieldValue(key).null();
495
0
    };
496
497
0
    if (override_da || override_q) {
498
0
        QPDFFormFieldObjectHelper cur_field(obj);
499
0
        if (override_da && (!has_explicit(cur_field, "/DA"))) {
500
0
            std::string da = cur_field.getDefaultAppearance();
501
0
            if (da != from_default_da) {
502
0
                obj.replaceKey("/DA", QPDFObjectHandle::newUnicodeString(from_default_da));
503
0
            }
504
0
        }
505
0
        if (override_q && (!has_explicit(cur_field, "/Q"))) {
506
0
            int q = cur_field.getQuadding();
507
0
            if (q != from_default_q) {
508
0
                obj.replaceKey("/Q", QPDFObjectHandle::newInteger(from_default_q));
509
0
            }
510
0
        }
511
0
    }
512
0
}
513
514
namespace
515
{
516
    class ResourceReplacer: public QPDFObjectHandle::TokenFilter
517
    {
518
      public:
519
        ResourceReplacer(
520
            std::map<std::string, std::map<std::string, std::string>> const& dr_map,
521
            std::map<std::string, std::map<std::string, std::vector<size_t>>> const& rnames);
522
0
        ~ResourceReplacer() override = default;
523
        void handleToken(QPDFTokenizer::Token const&) override;
524
525
      private:
526
        size_t offset{0};
527
        std::map<std::string, std::map<size_t, std::string>> to_replace;
528
    };
529
} // namespace
530
531
ResourceReplacer::ResourceReplacer(
532
    std::map<std::string, std::map<std::string, std::string>> const& dr_map,
533
    std::map<std::string, std::map<std::string, std::vector<size_t>>> const& rnames)
534
0
{
535
    // We have:
536
    // * dr_map[resource_type][key] == new_key
537
    // * rnames[resource_type][key] == set of offsets
538
    //
539
    // We want:
540
    // * to_replace[key][offset] = new_key
541
542
0
    for (auto const& [rtype, key_offsets]: rnames) {
543
0
        auto dr_map_rtype = dr_map.find(rtype);
544
0
        if (dr_map_rtype == dr_map.end()) {
545
0
            continue;
546
0
        }
547
0
        for (auto const& [old_key, offsets]: key_offsets) {
548
0
            auto dr_map_rtype_old = dr_map_rtype->second.find(old_key);
549
0
            if (dr_map_rtype_old == dr_map_rtype->second.end()) {
550
0
                continue;
551
0
            }
552
0
            for (auto const& offs: offsets) {
553
0
                to_replace[old_key][offs] = dr_map_rtype_old->second;
554
0
            }
555
0
        }
556
0
    }
557
0
}
558
559
void
560
ResourceReplacer::handleToken(QPDFTokenizer::Token const& token)
561
0
{
562
0
    if (token.getType() == QPDFTokenizer::tt_name) {
563
0
        auto it1 = to_replace.find(token.getValue());
564
0
        if (it1 != to_replace.end()) {
565
0
            auto it2 = it1->second.find(offset);
566
0
            if (it2 != it1->second.end()) {
567
0
                QTC::TC("qpdf", "QPDFAcroFormDocumentHelper replaced DA token");
568
0
                write(it2->second);
569
0
                offset += token.getRawValue().length();
570
0
                return;
571
0
            }
572
0
        }
573
0
    }
574
0
    offset += token.getRawValue().length();
575
0
    writeToken(token);
576
0
}
577
578
void
579
QPDFAcroFormDocumentHelper::adjustDefaultAppearances(
580
    QPDFObjectHandle obj, std::map<std::string, std::map<std::string, std::string>> const& dr_map)
581
0
{
582
    // This method is called on a field that has been copied from another file but whose /DA still
583
    // refers to resources in the original file's /DR.
584
585
    // When appearance streams are generated for variable text fields (see ISO 32000 PDF spec
586
    // section 12.7.3.3), the field's /DA is used to generate content of the appearance stream. /DA
587
    // contains references to resources that may be resolved in the document's /DR dictionary, which
588
    // appears in the document's /AcroForm dictionary. For fields that we copied from other
589
    // documents, we need to ensure that resources are mapped correctly in the case of conflicting
590
    // names. For example, if a.pdf's /DR has /F1 pointing to one font and b.pdf's /DR also has /F1
591
    // but it points elsewhere, we need to make sure appearance streams of fields copied from b.pdf
592
    // into a.pdf use whatever font /F1 meant in b.pdf, not whatever it means in a.pdf. This method
593
    // takes care of that. It is only called on fields copied from foreign files.
594
595
    // A few notes:
596
    //
597
    // * If the from document's /DR and the current document's /DR have conflicting keys, we have
598
    //   already resolved the conflicts before calling this method. The dr_map parameter contains
599
    //   the mapping from old keys to new keys.
600
    //
601
    // * /DA may be inherited from the document's /AcroForm dictionary. By the time this method has
602
    //   been called, we have already copied any document-level values into the fields to avoid
603
    //   having them inherit from the new document. This was done in adjustInheritedFields.
604
605
0
    auto DA = obj.getKey("/DA");
606
0
    if (!DA.isString()) {
607
0
        return;
608
0
    }
609
610
    // Find names in /DA. /DA is a string that contains content stream-like code, so we create a
611
    // stream out of the string and then filter it. We don't attach the stream to anything, so it
612
    // will get discarded.
613
0
    ResourceFinder rf;
614
0
    auto da_stream = QPDFObjectHandle::newStream(&qpdf, DA.getUTF8Value());
615
0
    try {
616
0
        auto nwarnings = qpdf.numWarnings();
617
0
        da_stream.parseAsContents(&rf);
618
0
        if (qpdf.numWarnings() > nwarnings) {
619
0
            QTC::TC("qpdf", "QPDFAcroFormDocumentHelper /DA parse error");
620
0
        }
621
0
    } catch (std::exception& e) {
622
        // No way to reproduce in test suite right now since error conditions are converted to
623
        // warnings.
624
0
        obj.warn("Unable to parse /DA: "s + e.what() + "; this form field may not update properly");
625
0
        return;
626
0
    }
627
628
    // Regenerate /DA by filtering its tokens.
629
0
    ResourceReplacer rr(dr_map, rf.getNamesByResourceType());
630
0
    Pl_Buffer buf_pl("filtered DA");
631
0
    da_stream.filterAsContents(&rr, &buf_pl);
632
0
    std::string new_da = buf_pl.getString();
633
0
    obj.replaceKey("/DA", QPDFObjectHandle::newString(new_da));
634
0
}
635
636
void
637
QPDFAcroFormDocumentHelper::adjustAppearanceStream(
638
    QPDFObjectHandle stream, std::map<std::string, std::map<std::string, std::string>> dr_map)
639
0
{
640
    // We don't have to modify appearance streams or their resource dictionaries for them to display
641
    // properly, but we need to do so to make them save to regenerate. Suppose an appearance stream
642
    // as a font /F1 that is different from /F1 in /DR, and that when we copy the field, /F1 is
643
    // remapped to /F1_1. When the field is regenerated, /F1_1 won't appear in the stream's resource
644
    // dictionary, so the regenerated appearance stream will revert to the /F1_1 in /DR. If we
645
    // adjust existing appearance streams, we are protected from this problem.
646
647
0
    auto dict = stream.getDict();
648
0
    auto resources = dict.getKey("/Resources");
649
650
    // Make sure this stream has its own private resource dictionary.
651
0
    bool was_indirect = resources.isIndirect();
652
0
    resources = resources.shallowCopy();
653
0
    if (was_indirect) {
654
0
        resources = qpdf.makeIndirectObject(resources);
655
0
    }
656
0
    dict.replaceKey("/Resources", resources);
657
    // Create a dictionary with top-level keys so we can use mergeResources to force them to be
658
    // unshared. We will also use this to resolve conflicts that may already be in the resource
659
    // dictionary.
660
0
    auto merge_with = QPDFObjectHandle::newDictionary();
661
0
    for (auto const& top_key: dr_map) {
662
0
        merge_with.replaceKey(top_key.first, QPDFObjectHandle::newDictionary());
663
0
    }
664
0
    resources.mergeResources(merge_with);
665
    // Rename any keys in the resource dictionary that we remapped.
666
0
    for (auto const& i1: dr_map) {
667
0
        std::string const& top_key = i1.first;
668
0
        auto subdict = resources.getKey(top_key);
669
0
        if (!subdict.isDictionary()) {
670
0
            continue;
671
0
        }
672
0
        for (auto const& i2: i1.second) {
673
0
            std::string const& old_key = i2.first;
674
0
            std::string const& new_key = i2.second;
675
0
            auto existing_new = subdict.getKey(new_key);
676
0
            if (!existing_new.null()) {
677
                // The resource dictionary already has a key in it matching what we remapped an old
678
                // key to, so we'll have to move it out of the way. Stick it in merge_with, which we
679
                // will re-merge with the dictionary when we're done. We know merge_with already has
680
                // dictionaries for all the top keys.
681
0
                merge_with.getKey(top_key).replaceKey(new_key, existing_new);
682
0
            }
683
0
            auto existing_old = subdict.getKey(old_key);
684
0
            if (!existing_old.null()) {
685
0
                subdict.replaceKey(new_key, existing_old);
686
0
                subdict.removeKey(old_key);
687
0
            }
688
0
        }
689
0
    }
690
    // Deal with any any conflicts by re-merging with merge_with and updating our local copy of
691
    // dr_map, which we will use to modify the stream contents.
692
0
    resources.mergeResources(merge_with, &dr_map);
693
    // Remove empty subdictionaries
694
0
    for (auto iter: resources.ditems()) {
695
0
        if (iter.second.isDictionary() && iter.second.getKeys().empty()) {
696
0
            resources.removeKey(iter.first);
697
0
        }
698
0
    }
699
700
    // Now attach a token filter to replace the actual resources.
701
0
    ResourceFinder rf;
702
0
    try {
703
0
        auto nwarnings = qpdf.numWarnings();
704
0
        stream.parseAsContents(&rf);
705
0
        QTC::TC(
706
0
            "qpdf",
707
0
            "QPDFAcroFormDocumentHelper AP parse error",
708
0
            qpdf.numWarnings() > nwarnings ? 0 : 1);
709
0
        auto rr = new ResourceReplacer(dr_map, rf.getNamesByResourceType());
710
0
        auto tf = std::shared_ptr<QPDFObjectHandle::TokenFilter>(rr);
711
0
        stream.addTokenFilter(tf);
712
0
    } catch (std::exception& e) {
713
        // No way to reproduce in test suite right now since error conditions are converted to
714
        // warnings.
715
0
        stream.warn("Unable to parse appearance stream: "s + e.what());
716
0
    }
717
0
}
718
719
void
720
QPDFAcroFormDocumentHelper::transformAnnotations(
721
    QPDFObjectHandle a_old_annots,
722
    std::vector<QPDFObjectHandle>& new_annots,
723
    std::vector<QPDFObjectHandle>& new_fields,
724
    std::set<QPDFObjGen>& old_fields,
725
    QPDFMatrix const& cm,
726
    QPDF* from_qpdf,
727
    QPDFAcroFormDocumentHelper* from_afdh)
728
0
{
729
0
    Array old_annots = std::move(a_old_annots);
730
0
    if (!from_qpdf) {
731
        // Assume these are from the same QPDF.
732
0
        from_qpdf = &qpdf;
733
0
        from_afdh = this;
734
0
    } else if (from_qpdf != &qpdf && !from_afdh) {
735
0
        from_afdh = &QPDFAcroFormDocumentHelper::get(*from_qpdf);
736
0
    }
737
0
    const bool foreign = from_qpdf != &qpdf;
738
739
    // It's possible that we will transform annotations that don't include any form fields. This
740
    // code takes care not to muck around with /AcroForm unless we have to.
741
742
0
    Dictionary acroform = qpdf.getRoot()["/AcroForm"];
743
0
    Dictionary from_acroform = from_qpdf->getRoot()["/AcroForm"];
744
745
    // /DA and /Q may be inherited from the document-level /AcroForm dictionary. If we are copying a
746
    // foreign stream and the stream is getting one of these values from its document's /AcroForm,
747
    // we will need to copy the value explicitly so that it doesn't start getting its default from
748
    // the destination document.
749
0
    std::string from_default_da;
750
0
    int from_default_q = 0;
751
    // If we copy any form fields, we will need to merge the source document's /DR into this
752
    // document's /DR.
753
0
    Dictionary from_dr;
754
0
    std::string default_da;
755
0
    int default_q = 0;
756
0
    if (foreign) {
757
0
        if (acroform) {
758
0
            if (acroform["/DA"].isString()) {
759
0
                default_da = acroform["/DA"].getUTF8Value();
760
0
            }
761
0
            if (Integer Q = acroform["/Q"]) {
762
0
                default_q = Q;
763
0
            }
764
0
        }
765
0
        if (from_acroform) {
766
0
            from_dr = from_acroform["/DR"];
767
0
            if (from_dr) {
768
0
                if (!from_dr.indirect()) {
769
0
                    from_dr = from_qpdf->makeIndirectObject(from_dr);
770
0
                }
771
0
                from_dr = qpdf.copyForeignObject(from_dr);
772
0
            }
773
0
            if (from_acroform["/DA"].isString()) {
774
0
                from_default_da = from_acroform["/DA"].getUTF8Value();
775
0
            }
776
0
            if (Integer Q = from_acroform["/Q"]) {
777
0
                from_default_q = Q;
778
0
            }
779
0
        }
780
0
    }
781
0
    const bool override_da = from_acroform ? from_default_da != default_da : false;
782
0
    const bool override_q = from_acroform ? from_default_q != default_q : false;
783
784
    // If we have to merge /DR, we will need a mapping of conflicting keys for rewriting /DA. Set
785
    // this up for lazy initialization in case we encounter any form fields.
786
0
    std::map<std::string, std::map<std::string, std::string>> dr_map;
787
0
    Dictionary dr;
788
789
0
    auto init_dr_map = [&]() {
790
0
        if (!dr) {
791
            // Ensure that we have a /DR that is an indirect
792
            // dictionary object.
793
0
            if (!acroform) {
794
0
                acroform = getOrCreateAcroForm();
795
0
            }
796
0
            dr = acroform["/DR"];
797
0
            if (!dr) {
798
0
                dr = Dictionary::empty();
799
0
            }
800
0
            QPDFObjectHandle(dr).makeResourcesIndirect(qpdf);
801
0
            if (!dr.indirect()) {
802
0
                acroform.replaceKey("/DR", qpdf.makeIndirectObject(dr));
803
0
                dr = acroform["/DR"];
804
0
            }
805
            // Merge the other document's /DR, creating a conflict map. mergeResources checks to
806
            // make sure both objects are dictionaries. By this point, if this is foreign, from_dr
807
            // has been copied, so we use the target qpdf as the owning qpdf.
808
0
            QPDFObjectHandle(from_dr).makeResourcesIndirect(qpdf);
809
0
            QPDFObjectHandle(dr).mergeResources(from_dr, &dr_map);
810
811
0
            if (from_afdh->getNeedAppearances()) {
812
0
                setNeedAppearances(true);
813
0
            }
814
0
        }
815
0
    };
816
817
    // This helper prevents us from copying the same object multiple times.
818
0
    std::map<QPDFObjGen, QPDFObjectHandle> orig_to_copy;
819
0
    auto maybe_copy_object = [&](QPDFObjectHandle& to_copy) {
820
0
        auto og = to_copy.getObjGen();
821
0
        if (orig_to_copy.contains(og)) {
822
0
            to_copy = orig_to_copy[og];
823
0
            return false;
824
0
        } else {
825
0
            to_copy = qpdf.makeIndirectObject(to_copy.shallowCopy());
826
0
            orig_to_copy[og] = to_copy;
827
0
            return true;
828
0
        }
829
0
    };
830
831
    // Traverse the field, copying kids, and preserving integrity.
832
0
    auto traverse_field = [&](QPDFObjectHandle& top_field) -> void {
833
0
        std::deque<Dictionary> queue({top_field});
834
0
        QPDFObjGen::set seen;
835
0
        for (auto it = queue.begin(); it != queue.end(); ++it) {
836
0
            auto& obj = *it;
837
0
            if (seen.add(obj)) {
838
0
                Dictionary parent = obj["/Parent"];
839
0
                if (parent.indirect()) {
840
0
                    auto parent_og = parent.id_gen();
841
0
                    if (orig_to_copy.contains(parent_og)) {
842
0
                        obj.replaceKey("/Parent", orig_to_copy[parent_og]);
843
0
                    } else {
844
0
                        parent.warn(
845
0
                            "while traversing field " + obj.id_gen().unparse(',') +
846
0
                            ", found parent (" + parent_og.unparse(',') +
847
0
                            ") that had not been seen, indicating likely invalid field structure");
848
0
                    }
849
0
                }
850
0
                size_t i = 0;
851
0
                Array Kids = obj["/Kids"];
852
0
                for (auto& kid: Kids) {
853
0
                    if (maybe_copy_object(kid)) {
854
0
                        Kids.set(i, kid);
855
0
                        queue.emplace_back(kid);
856
0
                    }
857
0
                    ++i;
858
0
                }
859
0
                adjustInheritedFields(
860
0
                    obj, override_da, from_default_da, override_q, from_default_q);
861
0
                if (foreign) {
862
                    // Lazily initialize our /DR and the conflict map.
863
0
                    init_dr_map();
864
                    // The spec doesn't say anything about /DR on the field, but lots of writers
865
                    // put one there, and it is frequently the same as the document-level /DR.
866
                    // To avoid having the field's /DR point to information that we are not
867
                    // maintaining, just reset it to that if it exists. Empirical evidence
868
                    // suggests that many readers, including Acrobat, Adobe Acrobat Reader,
869
                    // chrome, firefox, the mac Preview application, and several of the free
870
                    // readers on Linux all ignore /DR at the field level.
871
0
                    if (obj.contains("/DR")) {
872
0
                        obj.replaceKey("/DR", dr);
873
0
                    }
874
0
                    if (obj["/DA"].isString() && !dr_map.empty()) {
875
0
                        adjustDefaultAppearances(obj, dr_map);
876
0
                    }
877
0
                }
878
0
            }
879
0
        }
880
0
    };
881
882
0
    auto transform_annotation =
883
0
        [&](QPDFObjectHandle& annot) -> std::tuple<QPDFObjectHandle, bool, bool> {
884
        // Make copies of annotations and fields down to the appearance streams, preserving all
885
        // internal referential integrity. When the incoming annotations are from a different file,
886
        // we first copy them locally. Then, whether local or foreign, we copy them again so that if
887
        // we bring the same annotation in multiple times (e.g. overlaying a foreign page onto
888
        // multiple local pages or a local page onto multiple other local pages), we don't create
889
        // annotations that are referenced in more than one place. If we did that, the effect of
890
        // applying transformations would be cumulative, which is definitely not what we want.
891
        // Besides, annotations and fields are not intended to be referenced in multiple places.
892
893
        // Determine if this annotation is attached to a form field. If so, the annotation may be
894
        // the same object as the form field, or the form field may have the annotation as a kid. In
895
        // either case, we have to walk up the field structure to find the top-level field. Within
896
        // one iteration through a set of annotations, we don't want to copy the same item more than
897
        // once. For example, suppose we have field A with kids B, C, and D, each of which has
898
        // annotations BA, CA, and DA. When we get to BA, we will find that BA is a kid of B which
899
        // is under A. When we do a copyForeignObject of A, it will also copy everything else
900
        // because of the indirect references. When we clone BA, we will want to clone A and then
901
        // update A's clone's kid to point B's clone and B's clone's parent to point to A's clone.
902
        // The same thing holds for annotations. Next, when we get to CA, we will again discover
903
        // that A is the top, but we don't want to re-copy A. We want CA's clone to be linked to the
904
        // same clone as BA's. Failure to do this will break up things like radio button groups,
905
        // which all have to kids of the same parent.
906
907
0
        auto ffield = from_afdh->getFieldForAnnotation(annot);
908
0
        auto ffield_oh = ffield.getObjectHandle();
909
0
        if (ffield.null()) {
910
0
            return {{}, false, false};
911
0
        }
912
0
        if (ffield_oh.isStream()) {
913
0
            ffield.warn("ignoring form field that's a stream");
914
0
            return {{}, false, false};
915
0
        }
916
0
        if (!ffield_oh.isIndirect()) {
917
0
            ffield.warn("ignoring form field not indirect");
918
0
            return {{}, false, false};
919
0
        }
920
        // A field and its associated annotation can be the same object. This matters because we
921
        // don't want to clone the annotation and field separately in this case.
922
        // Find the top-level field. It may be the field itself.
923
0
        bool have_parent = false;
924
0
        QPDFObjectHandle top_field = ffield.getTopLevelField(&have_parent).getObjectHandle();
925
0
        if (foreign) {
926
            // copyForeignObject returns the same value if called multiple times with the same
927
            // field. Create/retrieve the local copy of the original field. This pulls over
928
            // everything the field references including annotations and appearance streams, but
929
            // it's harmless to call copyForeignObject on them too. They will already be copied,
930
            // so we'll get the right object back.
931
932
            // top_field and ffield_oh are known to be indirect.
933
0
            top_field = qpdf.copyForeignObject(top_field);
934
0
            ffield_oh = qpdf.copyForeignObject(ffield_oh);
935
0
        } else {
936
            // We don't need to add top_field to old_fields if it's foreign because the new copy
937
            // of the foreign field won't be referenced anywhere. It's just the starting point
938
            // for us to make an additional local copy of.
939
0
            old_fields.insert(top_field.getObjGen());
940
0
        }
941
942
0
        if (maybe_copy_object(top_field)) {
943
0
            traverse_field(top_field);
944
0
        }
945
946
        // Now switch to copies. We already switched for top_field
947
0
        maybe_copy_object(ffield_oh);
948
0
        return {top_field, true, have_parent};
949
0
    };
950
951
    // Now do the actual copies.
952
953
0
    QPDFObjGen::set added_new_fields;
954
0
    for (auto annot: old_annots) {
955
0
        if (annot.isStream()) {
956
0
            annot.warn("ignoring annotation that's a stream");
957
0
            continue;
958
0
        }
959
0
        auto [top_field, have_field, have_parent] = transform_annotation(annot);
960
961
0
        QTC::TC(
962
0
            "qpdf",
963
0
            "QPDFAcroFormDocumentHelper copy annotation",
964
0
            (have_field ? 1 : 0) | (foreign ? 2 : 0));
965
0
        if (have_field) {
966
0
            QTC::TC(
967
0
                "qpdf",
968
0
                "QPDFAcroFormDocumentHelper field with parent",
969
0
                (have_parent ? 1 : 0) | (foreign ? 2 : 0));
970
0
        }
971
0
        if (foreign) {
972
0
            if (!annot.isIndirect()) {
973
0
                annot = from_qpdf->makeIndirectObject(annot);
974
0
            }
975
0
            annot = qpdf.copyForeignObject(annot);
976
0
        }
977
0
        maybe_copy_object(annot);
978
979
        // Now we have copies, so we can safely mutate.
980
0
        if (have_field && added_new_fields.add(top_field)) {
981
0
            new_fields.emplace_back(top_field);
982
0
        }
983
0
        new_annots.emplace_back(annot);
984
985
        // Identify and copy any appearance streams
986
987
0
        auto ah = QPDFAnnotationObjectHelper(annot);
988
0
        Dictionary apdict = ah.getAppearanceDictionary();
989
0
        std::vector<QPDFObjectHandle> streams;
990
0
        auto replace_stream = [](auto& dict, auto& key, auto& old) {
991
0
            dict.replaceKey(key, old.copyStream());
992
0
            return dict[key];
993
0
        };
Unexecuted instantiation: QPDFAcroFormDocumentHelper.cc:auto QPDFAcroFormDocumentHelper::transformAnnotations(QPDFObjectHandle, std::__1::vector<QPDFObjectHandle, std::__1::allocator<QPDFObjectHandle> >&, std::__1::vector<QPDFObjectHandle, std::__1::allocator<QPDFObjectHandle> >&, std::__1::set<QPDFObjGen, std::__1::less<QPDFObjGen>, std::__1::allocator<QPDFObjGen> >&, QPDFMatrix const&, QPDF*, QPDFAcroFormDocumentHelper*)::$_0::operator()<qpdf::Dictionary, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, QPDFObjectHandle>(qpdf::Dictionary&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, QPDFObjectHandle&) const
Unexecuted instantiation: QPDFAcroFormDocumentHelper.cc:auto QPDFAcroFormDocumentHelper::transformAnnotations(QPDFObjectHandle, std::__1::vector<QPDFObjectHandle, std::__1::allocator<QPDFObjectHandle> >&, std::__1::vector<QPDFObjectHandle, std::__1::allocator<QPDFObjectHandle> >&, std::__1::set<QPDFObjGen, std::__1::less<QPDFObjGen>, std::__1::allocator<QPDFObjGen> >&, QPDFMatrix const&, QPDF*, QPDFAcroFormDocumentHelper*)::$_0::operator()<QPDFObjectHandle, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, QPDFObjectHandle>(QPDFObjectHandle&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, QPDFObjectHandle&) const
994
995
0
        for (auto& [key1, value1]: apdict) {
996
0
            if (value1.isStream()) {
997
0
                streams.emplace_back(replace_stream(apdict, key1, value1));
998
0
            } else {
999
0
                for (auto& [key2, value2]: Dictionary(value1)) {
1000
0
                    if (value2.isStream()) {
1001
0
                        streams.emplace_back(replace_stream(value1, key2, value2));
1002
0
                    }
1003
0
                }
1004
0
            }
1005
0
        }
1006
1007
        // Now we can safely mutate the annotation and its appearance streams.
1008
0
        for (auto& stream: streams) {
1009
0
            Dictionary dict = stream.getDict();
1010
1011
0
            QPDFMatrix apcm;
1012
0
            Array omatrix = dict["/Matrix"];
1013
0
            if (omatrix) {
1014
0
                apcm = QPDFMatrix(QPDFObjectHandle(omatrix).getArrayAsMatrix());
1015
0
            }
1016
0
            apcm.concat(cm);
1017
0
            if (omatrix || apcm != QPDFMatrix()) {
1018
0
                dict.replaceKey("/Matrix", QPDFObjectHandle::newFromMatrix(apcm));
1019
0
            }
1020
0
            Dictionary resources = dict["/Resources"];
1021
0
            if (!dr_map.empty() && resources) {
1022
0
                adjustAppearanceStream(stream, dr_map);
1023
0
            }
1024
0
        }
1025
0
        auto rect = cm.transformRectangle(annot["/Rect"].getArrayAsRectangle());
1026
0
        annot.replaceKey("/Rect", QPDFObjectHandle::newFromRectangle(rect));
1027
0
    }
1028
0
}
1029
1030
void
1031
QPDFAcroFormDocumentHelper::fixCopiedAnnotations(
1032
    QPDFObjectHandle to_page,
1033
    QPDFObjectHandle from_page,
1034
    QPDFAcroFormDocumentHelper& from_afdh,
1035
    std::set<QPDFObjGen>* added_fields)
1036
0
{
1037
0
    auto old_annots = from_page.getKey("/Annots");
1038
0
    if (old_annots.empty() || !old_annots.isArray()) {
1039
0
        return;
1040
0
    }
1041
1042
0
    std::vector<QPDFObjectHandle> new_annots;
1043
0
    std::vector<QPDFObjectHandle> new_fields;
1044
0
    std::set<QPDFObjGen> old_fields;
1045
0
    transformAnnotations(
1046
0
        old_annots,
1047
0
        new_annots,
1048
0
        new_fields,
1049
0
        old_fields,
1050
0
        QPDFMatrix(),
1051
0
        &(from_afdh.getQPDF()),
1052
0
        &from_afdh);
1053
1054
0
    to_page.replaceKey("/Annots", QPDFObjectHandle::newArray(new_annots));
1055
0
    addAndRenameFormFields(new_fields);
1056
0
    if (added_fields) {
1057
0
        for (auto const& f: new_fields) {
1058
0
            added_fields->insert(f.getObjGen());
1059
0
        }
1060
0
    }
1061
0
}