Coverage Report

Created: 2026-12-01 06:46

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/qpdf/libqpdf/QUtil.cc
Line
Count
Source
1
// Include qpdf-config.h first so off_t is guaranteed to have the right size.
2
#include <qpdf/qpdf-config.h>
3
4
#include <qpdf/QUtil.hh>
5
#include <qpdf/Util.hh>
6
7
#include <qpdf/CryptoRandomDataProvider.hh>
8
#include <qpdf/Pipeline.hh>
9
#include <qpdf/QIntC.hh>
10
#include <qpdf/QPDFSystemError.hh>
11
#include <qpdf/QTC.hh>
12
#include <qpdf/Util.hh>
13
14
#include <algorithm>
15
#include <cerrno>
16
#include <charconv>
17
#include <chrono>
18
#include <cstdlib>
19
#include <cstring>
20
#include <fcntl.h>
21
#include <fstream>
22
#include <iomanip>
23
#include <map>
24
#include <memory>
25
#include <regex>
26
#include <set>
27
#include <sstream>
28
#include <stdexcept>
29
#ifndef QPDF_NO_WCHAR_T
30
# include <cwchar>
31
#endif
32
#ifdef _WIN32
33
# define WIN32_LEAN_AND_MEAN
34
# include <direct.h>
35
# include <io.h>
36
# include <windows.h>
37
#else
38
# include <sys/stat.h>
39
# include <unistd.h>
40
#endif
41
#ifdef HAVE_MALLOC_INFO
42
# include <malloc.h>
43
#endif
44
45
using namespace qpdf;
46
using namespace std::literals;
47
48
// First element is 24
49
static unsigned short pdf_doc_low_to_unicode[] = {
50
    0x02d8, // 0x18    BREVE
51
    0x02c7, // 0x19    CARON
52
    0x02c6, // 0x1a    MODIFIER LETTER CIRCUMFLEX ACCENT
53
    0x02d9, // 0x1b    DOT ABOVE
54
    0x02dd, // 0x1c    DOUBLE ACUTE ACCENT
55
    0x02db, // 0x1d    OGONEK
56
    0x02da, // 0x1e    RING ABOVE
57
    0x02dc, // 0x1f    SMALL TILDE
58
};
59
// First element is 127
60
static unsigned short pdf_doc_to_unicode[] = {
61
    0xfffd, // 0x7f    UNDEFINED
62
    0x2022, // 0x80    BULLET
63
    0x2020, // 0x81    DAGGER
64
    0x2021, // 0x82    DOUBLE DAGGER
65
    0x2026, // 0x83    HORIZONTAL ELLIPSIS
66
    0x2014, // 0x84    EM DASH
67
    0x2013, // 0x85    EN DASH
68
    0x0192, // 0x86    SMALL LETTER F WITH HOOK
69
    0x2044, // 0x87    FRACTION SLASH (solidus)
70
    0x2039, // 0x88    SINGLE LEFT-POINTING ANGLE QUOTATION MARK
71
    0x203a, // 0x89    SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
72
    0x2212, // 0x8a    MINUS SIGN
73
    0x2030, // 0x8b    PER MILLE SIGN
74
    0x201e, // 0x8c    DOUBLE LOW-9 QUOTATION MARK (quotedblbase)
75
    0x201c, // 0x8d    LEFT DOUBLE QUOTATION MARK (double quote left)
76
    0x201d, // 0x8e    RIGHT DOUBLE QUOTATION MARK (quotedblright)
77
    0x2018, // 0x8f    LEFT SINGLE QUOTATION MARK (quoteleft)
78
    0x2019, // 0x90    RIGHT SINGLE QUOTATION MARK (quoteright)
79
    0x201a, // 0x91    SINGLE LOW-9 QUOTATION MARK (quotesinglbase)
80
    0x2122, // 0x92    TRADE MARK SIGN
81
    0xfb01, // 0x93    LATIN SMALL LIGATURE FI
82
    0xfb02, // 0x94    LATIN SMALL LIGATURE FL
83
    0x0141, // 0x95    LATIN CAPITAL LETTER L WITH STROKE
84
    0x0152, // 0x96    LATIN CAPITAL LIGATURE OE
85
    0x0160, // 0x97    LATIN CAPITAL LETTER S WITH CARON
86
    0x0178, // 0x98    LATIN CAPITAL LETTER Y WITH DIAERESIS
87
    0x017d, // 0x99    LATIN CAPITAL LETTER Z WITH CARON
88
    0x0131, // 0x9a    LATIN SMALL LETTER DOTLESS I
89
    0x0142, // 0x9b    LATIN SMALL LETTER L WITH STROKE
90
    0x0153, // 0x9c    LATIN SMALL LIGATURE OE
91
    0x0161, // 0x9d    LATIN SMALL LETTER S WITH CARON
92
    0x017e, // 0x9e    LATIN SMALL LETTER Z WITH CARON
93
    0xfffd, // 0x9f    UNDEFINED
94
    0x20ac, // 0xa0    EURO SIGN
95
};
96
static unsigned short win_ansi_to_unicode[] = {
97
    0x20ac, // 0x80
98
    0xfffd, // 0x81
99
    0x201a, // 0x82
100
    0x0192, // 0x83
101
    0x201e, // 0x84
102
    0x2026, // 0x85
103
    0x2020, // 0x86
104
    0x2021, // 0x87
105
    0x02c6, // 0x88
106
    0x2030, // 0x89
107
    0x0160, // 0x8a
108
    0x2039, // 0x8b
109
    0x0152, // 0x8c
110
    0xfffd, // 0x8d
111
    0x017d, // 0x8e
112
    0xfffd, // 0x8f
113
    0xfffd, // 0x90
114
    0x2018, // 0x91
115
    0x2019, // 0x92
116
    0x201c, // 0x93
117
    0x201d, // 0x94
118
    0x2022, // 0x95
119
    0x2013, // 0x96
120
    0x2014, // 0x97
121
    0x0303, // 0x98
122
    0x2122, // 0x99
123
    0x0161, // 0x9a
124
    0x203a, // 0x9b
125
    0x0153, // 0x9c
126
    0xfffd, // 0x9d
127
    0x017e, // 0x9e
128
    0x0178, // 0x9f
129
    0x00a0, // 0xa0
130
};
131
static unsigned short mac_roman_to_unicode[] = {
132
    0x00c4, // 0x80
133
    0x00c5, // 0x81
134
    0x00c7, // 0x82
135
    0x00c9, // 0x83
136
    0x00d1, // 0x84
137
    0x00d6, // 0x85
138
    0x00dc, // 0x86
139
    0x00e1, // 0x87
140
    0x00e0, // 0x88
141
    0x00e2, // 0x89
142
    0x00e4, // 0x8a
143
    0x00e3, // 0x8b
144
    0x00e5, // 0x8c
145
    0x00e7, // 0x8d
146
    0x00e9, // 0x8e
147
    0x00e8, // 0x8f
148
    0x00ea, // 0x90
149
    0x00eb, // 0x91
150
    0x00ed, // 0x92
151
    0x00ec, // 0x93
152
    0x00ee, // 0x94
153
    0x00ef, // 0x95
154
    0x00f1, // 0x96
155
    0x00f3, // 0x97
156
    0x00f2, // 0x98
157
    0x00f4, // 0x99
158
    0x00f6, // 0x9a
159
    0x00f5, // 0x9b
160
    0x00fa, // 0x9c
161
    0x00f9, // 0x9d
162
    0x00fb, // 0x9e
163
    0x00fc, // 0x9f
164
    0x2020, // 0xa0
165
    0x00b0, // 0xa1
166
    0x00a2, // 0xa2
167
    0x00a3, // 0xa3
168
    0x00a7, // 0xa4
169
    0x2022, // 0xa5
170
    0x00b6, // 0xa6
171
    0x00df, // 0xa7
172
    0x00ae, // 0xa8
173
    0x00a9, // 0xa9
174
    0x2122, // 0xaa
175
    0x0301, // 0xab
176
    0x0308, // 0xac
177
    0xfffd, // 0xad
178
    0x00c6, // 0xae
179
    0x00d8, // 0xaf
180
    0xfffd, // 0xb0
181
    0x00b1, // 0xb1
182
    0xfffd, // 0xb2
183
    0xfffd, // 0xb3
184
    0x00a5, // 0xb4
185
    0x03bc, // 0xb5
186
    0xfffd, // 0xb6
187
    0xfffd, // 0xb7
188
    0xfffd, // 0xb8
189
    0xfffd, // 0xb9
190
    0xfffd, // 0xba
191
    0x1d43, // 0xbb
192
    0x1d52, // 0xbc
193
    0xfffd, // 0xbd
194
    0x00e6, // 0xbe
195
    0x00f8, // 0xbf
196
    0x00bf, // 0xc0
197
    0x00a1, // 0xc1
198
    0x00ac, // 0xc2
199
    0xfffd, // 0xc3
200
    0x0192, // 0xc4
201
    0xfffd, // 0xc5
202
    0xfffd, // 0xc6
203
    0x00ab, // 0xc7
204
    0x00bb, // 0xc8
205
    0x2026, // 0xc9
206
    0xfffd, // 0xca
207
    0x00c0, // 0xcb
208
    0x00c3, // 0xcc
209
    0x00d5, // 0xcd
210
    0x0152, // 0xce
211
    0x0153, // 0xcf
212
    0x2013, // 0xd0
213
    0x2014, // 0xd1
214
    0x201c, // 0xd2
215
    0x201d, // 0xd3
216
    0x2018, // 0xd4
217
    0x2019, // 0xd5
218
    0x00f7, // 0xd6
219
    0xfffd, // 0xd7
220
    0x00ff, // 0xd8
221
    0x0178, // 0xd9
222
    0x2044, // 0xda
223
    0x00a4, // 0xdb
224
    0x2039, // 0xdc
225
    0x203a, // 0xdd
226
    0xfb01, // 0xde
227
    0xfb02, // 0xdf
228
    0x2021, // 0xe0
229
    0x00b7, // 0xe1
230
    0x201a, // 0xe2
231
    0x201e, // 0xe3
232
    0x2030, // 0xe4
233
    0x00c2, // 0xe5
234
    0x00ca, // 0xe6
235
    0x00c1, // 0xe7
236
    0x00cb, // 0xe8
237
    0x00c8, // 0xe9
238
    0x00cd, // 0xea
239
    0x00ce, // 0xeb
240
    0x00cf, // 0xec
241
    0x00cc, // 0xed
242
    0x00d3, // 0xee
243
    0x00d4, // 0xef
244
    0xfffd, // 0xf0
245
    0x00d2, // 0xf1
246
    0x00da, // 0xf2
247
    0x00db, // 0xf3
248
    0x00d9, // 0xf4
249
    0x0131, // 0xf5
250
    0x02c6, // 0xf6
251
    0x0303, // 0xf7
252
    0x0304, // 0xf8
253
    0x0306, // 0xf9
254
    0x0307, // 0xfa
255
    0x030a, // 0xfb
256
    0x0327, // 0xfc
257
    0x030b, // 0xfd
258
    0x0328, // 0xfe
259
    0x02c7, // 0xff
260
};
261
262
static std::map<unsigned long, unsigned char> unicode_to_win_ansi = {
263
    {0x20ac, 0x80}, {0x201a, 0x82}, {0x192, 0x83},  {0x201e, 0x84}, {0x2026, 0x85}, {0x2020, 0x86},
264
    {0x2021, 0x87}, {0x2c6, 0x88},  {0x2030, 0x89}, {0x160, 0x8a},  {0x2039, 0x8b}, {0x152, 0x8c},
265
    {0x17d, 0x8e},  {0x2018, 0x91}, {0x2019, 0x92}, {0x201c, 0x93}, {0x201d, 0x94}, {0x2022, 0x95},
266
    {0x2013, 0x96}, {0x2014, 0x97}, {0x303, 0x98},  {0x2122, 0x99}, {0x161, 0x9a},  {0x203a, 0x9b},
267
    {0x153, 0x9c},  {0x17e, 0x9e},  {0x178, 0x9f},  {0xa0, 0xa0},
268
};
269
static std::map<unsigned long, unsigned char> unicode_to_mac_roman = {
270
    {0xc4, 0x80},   {0xc5, 0x81},   {0xc7, 0x82},   {0xc9, 0x83},   {0xd1, 0x84},   {0xd6, 0x85},
271
    {0xdc, 0x86},   {0xe1, 0x87},   {0xe0, 0x88},   {0xe2, 0x89},   {0xe4, 0x8a},   {0xe3, 0x8b},
272
    {0xe5, 0x8c},   {0xe7, 0x8d},   {0xe9, 0x8e},   {0xe8, 0x8f},   {0xea, 0x90},   {0xeb, 0x91},
273
    {0xed, 0x92},   {0xec, 0x93},   {0xee, 0x94},   {0xef, 0x95},   {0xf1, 0x96},   {0xf3, 0x97},
274
    {0xf2, 0x98},   {0xf4, 0x99},   {0xf6, 0x9a},   {0xf5, 0x9b},   {0xfa, 0x9c},   {0xf9, 0x9d},
275
    {0xfb, 0x9e},   {0xfc, 0x9f},   {0x2020, 0xa0}, {0xb0, 0xa1},   {0xa2, 0xa2},   {0xa3, 0xa3},
276
    {0xa7, 0xa4},   {0x2022, 0xa5}, {0xb6, 0xa6},   {0xdf, 0xa7},   {0xae, 0xa8},   {0xa9, 0xa9},
277
    {0x2122, 0xaa}, {0x301, 0xab},  {0x308, 0xac},  {0xc6, 0xae},   {0xd8, 0xaf},   {0xb1, 0xb1},
278
    {0xa5, 0xb4},   {0x3bc, 0xb5},  {0x1d43, 0xbb}, {0x1d52, 0xbc}, {0xe6, 0xbe},   {0xf8, 0xbf},
279
    {0xbf, 0xc0},   {0xa1, 0xc1},   {0xac, 0xc2},   {0x192, 0xc4},  {0xab, 0xc7},   {0xbb, 0xc8},
280
    {0x2026, 0xc9}, {0xc0, 0xcb},   {0xc3, 0xcc},   {0xd5, 0xcd},   {0x152, 0xce},  {0x153, 0xcf},
281
    {0x2013, 0xd0}, {0x2014, 0xd1}, {0x201c, 0xd2}, {0x201d, 0xd3}, {0x2018, 0xd4}, {0x2019, 0xd5},
282
    {0xf7, 0xd6},   {0xff, 0xd8},   {0x178, 0xd9},  {0x2044, 0xda}, {0xa4, 0xdb},   {0x2039, 0xdc},
283
    {0x203a, 0xdd}, {0xfb01, 0xde}, {0xfb02, 0xdf}, {0x2021, 0xe0}, {0xb7, 0xe1},   {0x201a, 0xe2},
284
    {0x201e, 0xe3}, {0x2030, 0xe4}, {0xc2, 0xe5},   {0xca, 0xe6},   {0xc1, 0xe7},   {0xcb, 0xe8},
285
    {0xc8, 0xe9},   {0xcd, 0xea},   {0xce, 0xeb},   {0xcf, 0xec},   {0xcc, 0xed},   {0xd3, 0xee},
286
    {0xd4, 0xef},   {0xd2, 0xf1},   {0xda, 0xf2},   {0xdb, 0xf3},   {0xd9, 0xf4},   {0x131, 0xf5},
287
    {0x2c6, 0xf6},  {0x303, 0xf7},  {0x304, 0xf8},  {0x306, 0xf9},  {0x307, 0xfa},  {0x30a, 0xfb},
288
    {0x327, 0xfc},  {0x30b, 0xfd},  {0x328, 0xfe},  {0x2c7, 0xff},
289
};
290
static std::map<unsigned long, unsigned char> unicode_to_pdf_doc = {
291
    {0x02d8, 0x18}, {0x02c7, 0x19}, {0x02c6, 0x1a}, {0x02d9, 0x1b}, {0x02dd, 0x1c}, {0x02db, 0x1d},
292
    {0x02da, 0x1e}, {0x02dc, 0x1f}, {0x2022, 0x80}, {0x2020, 0x81}, {0x2021, 0x82}, {0x2026, 0x83},
293
    {0x2014, 0x84}, {0x2013, 0x85}, {0x0192, 0x86}, {0x2044, 0x87}, {0x2039, 0x88}, {0x203a, 0x89},
294
    {0x2212, 0x8a}, {0x2030, 0x8b}, {0x201e, 0x8c}, {0x201c, 0x8d}, {0x201d, 0x8e}, {0x2018, 0x8f},
295
    {0x2019, 0x90}, {0x201a, 0x91}, {0x2122, 0x92}, {0xfb01, 0x93}, {0xfb02, 0x94}, {0x0141, 0x95},
296
    {0x0152, 0x96}, {0x0160, 0x97}, {0x0178, 0x98}, {0x017d, 0x99}, {0x0131, 0x9a}, {0x0142, 0x9b},
297
    {0x0153, 0x9c}, {0x0161, 0x9d}, {0x017e, 0x9e}, {0xfffd, 0x9f}, {0x20ac, 0xa0},
298
};
299
300
template <typename T>
301
static std::string
302
int_to_string_base_internal(T num, int base, int length)
303
161k
{
304
    // Backward compatibility -- int_to_string, which calls this function, used to use sprintf with
305
    // %0*d, so we interpret length such that a negative value appends spaces and a positive value
306
    // prepends zeroes.
307
161k
    if (!((base == 8) || (base == 10) || (base == 16))) {
308
0
        throw std::logic_error("int_to_string_base called with unsupported base");
309
0
    }
310
161k
    std::string cvt;
311
161k
    if (base == 10) {
312
        // Use the more efficient std::to_string when possible
313
27.4k
        cvt = std::to_string(num);
314
134k
    } else {
315
134k
        std::ostringstream buf;
316
134k
        buf.imbue(std::locale::classic());
317
134k
        buf << std::setbase(base) << std::nouppercase << num;
318
134k
        cvt = buf.str();
319
134k
    }
320
161k
    std::string result;
321
161k
    int str_length = QIntC::to_int(cvt.length());
322
161k
    if ((length > 0) && (str_length < length)) {
323
33.8k
        result.append(QIntC::to_size(length - str_length), '0');
324
33.8k
    }
325
161k
    result += cvt;
326
161k
    if ((length < 0) && (str_length < -length)) {
327
0
        result.append(QIntC::to_size(-length - str_length), ' ');
328
0
    }
329
161k
    return result;
330
161k
}
QUtil.cc:std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > int_to_string_base_internal<long long>(long long, int, int)
Line
Count
Source
303
161k
{
304
    // Backward compatibility -- int_to_string, which calls this function, used to use sprintf with
305
    // %0*d, so we interpret length such that a negative value appends spaces and a positive value
306
    // prepends zeroes.
307
161k
    if (!((base == 8) || (base == 10) || (base == 16))) {
308
0
        throw std::logic_error("int_to_string_base called with unsupported base");
309
0
    }
310
161k
    std::string cvt;
311
161k
    if (base == 10) {
312
        // Use the more efficient std::to_string when possible
313
27.4k
        cvt = std::to_string(num);
314
134k
    } else {
315
134k
        std::ostringstream buf;
316
134k
        buf.imbue(std::locale::classic());
317
134k
        buf << std::setbase(base) << std::nouppercase << num;
318
134k
        cvt = buf.str();
319
134k
    }
320
161k
    std::string result;
321
161k
    int str_length = QIntC::to_int(cvt.length());
322
161k
    if ((length > 0) && (str_length < length)) {
323
33.8k
        result.append(QIntC::to_size(length - str_length), '0');
324
33.8k
    }
325
161k
    result += cvt;
326
161k
    if ((length < 0) && (str_length < -length)) {
327
0
        result.append(QIntC::to_size(-length - str_length), ' ');
328
0
    }
329
161k
    return result;
330
161k
}
Unexecuted instantiation: QUtil.cc:std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > int_to_string_base_internal<unsigned long long>(unsigned long long, int, int)
331
332
std::string
333
QUtil::int_to_string(long long num, int length)
334
27.4k
{
335
27.4k
    return int_to_string_base(num, 10, length);
336
27.4k
}
337
338
std::string
339
QUtil::uint_to_string(unsigned long long num, int length)
340
0
{
341
0
    return uint_to_string_base(num, 10, length);
342
0
}
343
344
std::string
345
QUtil::int_to_string_base(long long num, int base, int length)
346
161k
{
347
161k
    return int_to_string_base_internal(num, base, length);
348
161k
}
349
350
std::string
351
QUtil::uint_to_string_base(unsigned long long num, int base, int length)
352
0
{
353
0
    return int_to_string_base_internal(num, base, length);
354
0
}
355
356
std::string
357
QUtil::double_to_string(double num, int decimal_places, bool trim_trailing_zeroes)
358
37.3k
{
359
    // Backward compatibility -- this code used to use sprintf and treated decimal_places <= 0 to
360
    // mean to use the default, which was six decimal places. Starting in 10.2, we trim trailing
361
    // zeroes by default.
362
37.3k
    if (decimal_places <= 0) {
363
37.3k
        decimal_places = 6;
364
37.3k
    }
365
37.3k
    std::ostringstream buf;
366
37.3k
    buf.imbue(std::locale::classic());
367
37.3k
    buf << std::setprecision(decimal_places) << std::fixed << num;
368
37.3k
    std::string result = buf.str();
369
37.3k
    if (trim_trailing_zeroes) {
370
261k
        while ((result.length() > 1) && (result.back() == '0')) {
371
223k
            result.pop_back();
372
223k
        }
373
37.3k
        if ((result.length() > 1) && (result.back() == '.')) {
374
37.3k
            result.pop_back();
375
37.3k
        }
376
37.3k
    }
377
37.3k
    return result;
378
37.3k
}
379
380
std::optional<double>
381
util::string_to_double(std::string const& str)
382
0
{
383
0
    std::istringstream buf(str);
384
0
    buf.imbue(std::locale::classic());
385
0
    double result;
386
0
    if (buf >> result) {
387
0
        return result;
388
0
    }
389
0
    return std::nullopt;
390
0
}
391
392
long long
393
QUtil::string_to_ll(char const* str)
394
3.43M
{
395
3.43M
    errno = 0;
396
#ifdef _MSC_VER
397
    long long result = _strtoi64(str, 0, 10);
398
#else
399
3.43M
    long long result = strtoll(str, nullptr, 10);
400
3.43M
#endif
401
3.43M
    if (errno == ERANGE) {
402
756
        throw std::range_error(
403
756
            std::string("overflow/underflow converting ") + str + " to 64-bit integer");
404
756
    }
405
3.43M
    return result;
406
3.43M
}
407
408
int
409
QUtil::string_to_int(char const* str)
410
941k
{
411
    // QIntC::to_int does range checking
412
941k
    return QIntC::to_int(string_to_ll(str));
413
941k
}
414
415
unsigned long long
416
QUtil::string_to_ull(char const* str)
417
0
{
418
0
    char const* p = str;
419
0
    while (*p && util::is_space(*p)) {
420
0
        ++p;
421
0
    }
422
0
    if (*p == '-') {
423
0
        throw std::runtime_error(
424
0
            std::string("underflow converting ") + str + " to 64-bit unsigned integer");
425
0
    }
426
427
0
    errno = 0;
428
#ifdef _MSC_VER
429
    unsigned long long result = _strtoui64(str, 0, 10);
430
#else
431
0
    unsigned long long result = strtoull(str, nullptr, 10);
432
0
#endif
433
0
    if (errno == ERANGE) {
434
0
        throw std::runtime_error(
435
0
            std::string("overflow converting ") + str + " to 64-bit unsigned integer");
436
0
    }
437
0
    return result;
438
0
}
439
440
unsigned int
441
QUtil::string_to_uint(char const* str)
442
0
{
443
    // QIntC::to_uint does range checking
444
0
    return QIntC::to_uint(string_to_ull(str));
445
0
}
446
447
bool
448
QUtil::is_long_long(char const* str)
449
0
{
450
0
    try {
451
0
        auto i1 = string_to_ll(str);
452
0
        std::string s1 = int_to_string(i1);
453
0
        return str == s1;
454
0
    } catch (std::exception&) {
455
        // overflow or other error
456
0
    }
457
0
    return false;
458
0
}
459
460
unsigned char*
461
QUtil::unsigned_char_pointer(std::string const& str)
462
151k
{
463
151k
    return reinterpret_cast<unsigned char*>(const_cast<char*>(str.c_str()));
464
151k
}
465
466
unsigned char*
467
QUtil::unsigned_char_pointer(char const* str)
468
6.10k
{
469
6.10k
    return reinterpret_cast<unsigned char*>(const_cast<char*>(str));
470
6.10k
}
471
472
void
473
QUtil::throw_system_error(std::string const& description)
474
0
{
475
0
    throw QPDFSystemError(description, errno);
476
0
}
477
478
int
479
QUtil::os_wrapper(std::string const& description, int status)
480
0
{
481
0
    if (status == -1) {
482
0
        throw_system_error(description);
483
0
    }
484
0
    return status;
485
0
}
486
487
#ifdef _WIN32
488
static std::shared_ptr<wchar_t>
489
win_convert_filename(char const* filename)
490
{
491
    // Convert the utf-8 encoded filename argument to wchar_t*. First,
492
    // convert to utf16, then to wchar_t*. Note that u16 will start
493
    // with the UTF16 marker, which we skip.
494
    std::string u16 = QUtil::utf8_to_utf16(filename);
495
    size_t len = u16.length();
496
    size_t wlen = (len / 2) - 1;
497
    auto wfilenamep = QUtil::make_shared_array<wchar_t>(wlen + 1);
498
    wchar_t* wfilename = wfilenamep.get();
499
    wfilename[wlen] = 0;
500
    for (unsigned int i = 2; i < len; i += 2) {
501
        wfilename[(i / 2) - 1] = static_cast<wchar_t>(
502
            (static_cast<unsigned char>(u16.at(i)) << 8) +
503
            static_cast<unsigned char>(u16.at(i + 1)));
504
    }
505
    return wfilenamep;
506
}
507
#endif
508
509
FILE*
510
QUtil::safe_fopen(char const* filename, char const* mode)
511
0
{
512
0
    FILE* f = nullptr;
513
#ifdef _WIN32
514
    std::shared_ptr<wchar_t> wfilenamep = win_convert_filename(filename);
515
    wchar_t* wfilename = wfilenamep.get();
516
    auto wmodep = QUtil::make_shared_array<wchar_t>(strlen(mode) + 1);
517
    wchar_t* wmode = wmodep.get();
518
    wmode[strlen(mode)] = 0;
519
    for (size_t i = 0; i < strlen(mode); ++i) {
520
        wmode[i] = static_cast<wchar_t>(mode[i]);
521
    }
522
523
# ifdef _MSC_VER
524
    errno_t err = _wfopen_s(&f, wfilename, wmode);
525
    if (err != 0) {
526
        errno = err;
527
    }
528
# else
529
    f = _wfopen(wfilename, wmode);
530
# endif
531
    if (f == 0) {
532
        throw_system_error(std::string("open ") + filename);
533
    }
534
#else
535
0
    f = fopen_wrapper(std::string("open ") + filename, fopen(filename, mode));
536
0
#endif
537
0
    return f;
538
0
}
539
540
FILE*
541
QUtil::fopen_wrapper(std::string const& description, FILE* f)
542
0
{
543
0
    if (f == nullptr) {
544
0
        throw_system_error(description);
545
0
    }
546
0
    return f;
547
0
}
548
549
bool
550
QUtil::file_can_be_opened(char const* filename)
551
0
{
552
0
    try {
553
0
        fclose(safe_fopen(filename, "rb"));
554
0
        return true;
555
0
    } catch (std::runtime_error&) {
556
        // can't open the file
557
0
    }
558
0
    return false;
559
0
}
560
561
int
562
QUtil::seek(FILE* stream, qpdf_offset_t offset, int whence)
563
0
{
564
0
#if HAVE_FSEEKO
565
0
    return fseeko(stream, QIntC::IntConverter<qpdf_offset_t, off_t>::convert(offset), whence);
566
#elif HAVE_FSEEKO64
567
    return fseeko64(stream, offset, whence);
568
#else
569
# if defined _MSC_VER || defined __BORLANDC__
570
    return _fseeki64(stream, offset, whence);
571
# else
572
    return fseek(stream, QIntC::to_long(offset), whence);
573
# endif
574
#endif
575
0
}
576
577
qpdf_offset_t
578
QUtil::tell(FILE* stream)
579
0
{
580
0
#if HAVE_FSEEKO
581
0
    return QIntC::to_offset(ftello(stream));
582
#elif HAVE_FSEEKO64
583
    return QIntC::to_offset(ftello64(stream));
584
#else
585
# if defined _MSC_VER || defined __BORLANDC__
586
    return _ftelli64(stream);
587
# else
588
    return QIntC::to_offset(ftell(stream));
589
# endif
590
#endif
591
0
}
592
593
bool
594
QUtil::same_file(char const* name1, char const* name2)
595
0
{
596
0
    if ((name1 == nullptr) || (strlen(name1) == 0) || (name2 == nullptr) || (strlen(name2) == 0)) {
597
0
        return false;
598
0
    }
599
#ifdef _WIN32
600
    bool same = false;
601
# ifndef AVOID_WINDOWS_HANDLE
602
    HANDLE fh1 = CreateFile(
603
        name1, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
604
    HANDLE fh2 = CreateFile(
605
        name2, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
606
    BY_HANDLE_FILE_INFORMATION fi1;
607
    BY_HANDLE_FILE_INFORMATION fi2;
608
    if ((fh1 != INVALID_HANDLE_VALUE) && (fh2 != INVALID_HANDLE_VALUE) &&
609
        GetFileInformationByHandle(fh1, &fi1) && GetFileInformationByHandle(fh2, &fi2) &&
610
        (fi1.dwVolumeSerialNumber == fi2.dwVolumeSerialNumber) &&
611
        (fi1.nFileIndexLow == fi2.nFileIndexLow) && (fi1.nFileIndexHigh == fi2.nFileIndexHigh)) {
612
        same = true;
613
    }
614
    if (fh1 != INVALID_HANDLE_VALUE) {
615
        CloseHandle(fh1);
616
    }
617
    if (fh2 != INVALID_HANDLE_VALUE) {
618
        CloseHandle(fh2);
619
    }
620
# endif
621
    return same;
622
#else
623
0
    struct stat st1;
624
0
    struct stat st2;
625
0
    if ((stat(name1, &st1) == 0) && (stat(name2, &st2) == 0) && (st1.st_ino == st2.st_ino) &&
626
0
        (st1.st_dev == st2.st_dev)) {
627
0
        return true;
628
0
    }
629
0
#endif
630
0
    return false;
631
0
}
632
633
void
634
QUtil::remove_file(char const* path)
635
0
{
636
#ifdef _WIN32
637
    std::shared_ptr<wchar_t> wpath = win_convert_filename(path);
638
    os_wrapper(std::string("remove ") + path, _wunlink(wpath.get()));
639
#else
640
0
    os_wrapper(std::string("remove ") + path, unlink(path));
641
0
#endif
642
0
}
643
644
void
645
QUtil::rename_file(char const* oldname, char const* newname)
646
0
{
647
#ifdef _WIN32
648
    try {
649
        remove_file(newname);
650
    } catch (QPDFSystemError&) {
651
        // ignore
652
    }
653
    std::shared_ptr<wchar_t> wold = win_convert_filename(oldname);
654
    std::shared_ptr<wchar_t> wnew = win_convert_filename(newname);
655
    os_wrapper(std::string("rename ") + oldname + " " + newname, _wrename(wold.get(), wnew.get()));
656
#else
657
0
    os_wrapper(std::string("rename ") + oldname + " " + newname, rename(oldname, newname));
658
0
#endif
659
0
}
660
661
void
662
QUtil::pipe_file(char const* filename, Pipeline* p)
663
0
{
664
    // Exercised in test suite by testing file_provider.
665
0
    FILE* f = safe_fopen(filename, "rb");
666
0
    FileCloser fc(f);
667
0
    size_t len = 0;
668
0
    int constexpr size = 8192;
669
0
    unsigned char buf[size];
670
0
    while ((len = fread(buf, 1, size, f)) > 0) {
671
0
        p->write(buf, len);
672
0
    }
673
0
    p->finish();
674
0
    if (ferror(f)) {
675
0
        throw std::runtime_error(std::string("failure reading file ") + filename);
676
0
    }
677
0
}
678
679
std::function<void(Pipeline*)>
680
QUtil::file_provider(std::string const& filename)
681
0
{
682
0
    return [filename](Pipeline* p) { pipe_file(filename.c_str(), p); };
683
0
}
684
685
std::string
686
QUtil::path_basename(std::string const& filename)
687
0
{
688
#ifdef _WIN32
689
    char const* pathsep = "/\\";
690
#else
691
0
    char const* pathsep = "/";
692
0
#endif
693
0
    std::string last = filename;
694
0
    auto len = last.length();
695
0
    while (len > 1) {
696
0
        auto pos = last.find_last_of(pathsep);
697
0
        if (pos == len - 1) {
698
0
            last.pop_back();
699
0
            --len;
700
0
        } else if (pos == std::string::npos) {
701
0
            break;
702
0
        } else {
703
0
            last = last.substr(pos + 1);
704
0
            break;
705
0
        }
706
0
    }
707
0
    return last;
708
0
}
709
710
char*
711
QUtil::copy_string(std::string const& str)
712
0
{
713
0
    char* result = new char[str.length() + 1];
714
    // Use memcpy in case string contains nulls
715
0
    result[str.length()] = '\0';
716
0
    memcpy(result, str.c_str(), str.length());
717
0
    return result;
718
0
}
719
720
std::shared_ptr<char>
721
QUtil::make_shared_cstr(std::string const& str)
722
0
{
723
0
    auto result = QUtil::make_shared_array<char>(str.length() + 1);
724
    // Use memcpy in case string contains nulls
725
0
    result.get()[str.length()] = '\0';
726
0
    memcpy(result.get(), str.c_str(), str.length());
727
0
    return result;
728
0
}
729
730
std::unique_ptr<char[]>
731
QUtil::make_unique_cstr(std::string const& str)
732
6.10k
{
733
6.10k
    auto result = std::make_unique<char[]>(str.length() + 1);
734
    // Use memcpy in case string contains nulls
735
6.10k
    result.get()[str.length()] = '\0';
736
6.10k
    memcpy(result.get(), str.c_str(), str.length());
737
6.10k
    return result;
738
6.10k
}
739
740
std::string
741
QUtil::hex_encode(std::string const& input)
742
7.93k
{
743
7.93k
    static auto constexpr hexchars = "0123456789abcdef";
744
7.93k
    std::string result;
745
7.93k
    result.reserve(2 * input.length());
746
126k
    for (const char c: input) {
747
126k
        result += hexchars[static_cast<unsigned char>(c) >> 4];
748
126k
        result += hexchars[c & 0x0f];
749
126k
    }
750
7.93k
    return result;
751
7.93k
}
752
753
std::string
754
QUtil::hex_decode(std::string const& input)
755
0
{
756
0
    std::string result;
757
    // We know result.size() <= 0.5 * input.size() + 1. However, reserving string space for this
758
    // upper bound has a negative impact.
759
0
    bool first = true;
760
0
    char decoded;
761
0
    for (auto ch: input) {
762
0
        ch = util::hex_decode_char(ch);
763
0
        if (ch < '\20') {
764
0
            if (first) {
765
0
                decoded = static_cast<char>(ch << 4);
766
0
                first = false;
767
0
            } else {
768
0
                result.push_back(decoded | ch);
769
0
                first = true;
770
0
            }
771
0
        }
772
0
    }
773
0
    if (!first) {
774
0
        result.push_back(decoded);
775
0
    }
776
0
    return result;
777
0
}
778
779
void
780
QUtil::binary_stdout()
781
0
{
782
#if defined(_WIN32) && defined(__BORLANDC__)
783
    setmode(_fileno(stdout), _O_BINARY);
784
#elif defined(_WIN32)
785
    _setmode(_fileno(stdout), _O_BINARY);
786
#endif
787
0
}
788
789
void
790
QUtil::binary_stdin()
791
0
{
792
#if defined(_WIN32) && defined(__BORLANDC__)
793
    setmode(_fileno(stdin), _O_BINARY);
794
#elif defined(_WIN32)
795
    _setmode(_fileno(stdin), _O_BINARY);
796
#endif
797
0
}
798
799
void
800
QUtil::setLineBuf(FILE* f)
801
0
{
802
0
#ifndef _WIN32
803
0
    setvbuf(f, reinterpret_cast<char*>(0), _IOLBF, 0);
804
0
#endif
805
0
}
806
807
char*
808
QUtil::getWhoami(char* argv0)
809
0
{
810
0
    char* whoami = nullptr;
811
0
    if (((whoami = strrchr(argv0, '/')) == nullptr) &&
812
0
        ((whoami = strrchr(argv0, '\\')) == nullptr)) {
813
0
        whoami = argv0;
814
0
    } else {
815
0
        ++whoami;
816
0
    }
817
818
0
    if ((strlen(whoami) > 4) && (strcmp(whoami + strlen(whoami) - 4, ".exe") == 0)) {
819
0
        whoami[strlen(whoami) - 4] = '\0';
820
0
    }
821
822
0
    return whoami;
823
0
}
824
825
bool
826
QUtil::get_env(std::string const& var, std::string* value)
827
9.30k
{
828
    // This was basically ripped out of wxWindows.
829
#ifdef _WIN32
830
# ifdef NO_GET_ENVIRONMENT
831
    return false;
832
# else
833
    // first get the size of the buffer
834
    DWORD len = ::GetEnvironmentVariable(var.c_str(), NULL, 0);
835
    if (len == 0) {
836
        // this means that there is no such variable
837
        return false;
838
    }
839
840
    if (value) {
841
        auto t = QUtil::make_shared_array<char>(len + 1);
842
        ::GetEnvironmentVariable(var.c_str(), t.get(), len);
843
        *value = t.get();
844
    }
845
846
    return true;
847
# endif
848
#else
849
9.30k
    char* p = getenv(var.c_str());
850
9.30k
    if (p == nullptr) {
851
9.30k
        return false;
852
9.30k
    }
853
0
    if (value) {
854
0
        *value = p;
855
0
    }
856
857
0
    return true;
858
9.30k
#endif
859
9.30k
}
860
861
time_t
862
QUtil::get_current_time()
863
0
{
864
0
    if (auto sde = util::source_date_epoch()) {
865
0
        return *sde;
866
0
    }
867
0
    return std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
868
0
}
869
870
std::optional<time_t>
871
util::source_date_epoch()
872
9.29k
{
873
9.29k
    std::string value;
874
    // The spec is silent about an empty value, and implementations vary. Treat empty as unset.
875
9.29k
    if (!QUtil::get_env("SOURCE_DATE_EPOCH", &value) || value.empty()) {
876
9.29k
        return std::nullopt;
877
9.29k
    }
878
0
    time_t result = 0;
879
0
    auto end = value.data() + value.size();
880
0
    if (std::all_of(value.begin(), value.end(), util::is_digit)) {
881
0
        auto [ptr, ec] = std::from_chars(value.data(), end, result);
882
0
        if (ec == std::errc() && ptr == end) {
883
0
            return result;
884
0
        }
885
0
    }
886
0
    throw std::runtime_error("invalid value for SOURCE_DATE_EPOCH: " + value);
887
0
}
888
889
QUtil::QPDFTime
890
QUtil::get_current_qpdf_time()
891
0
{
892
0
    if (auto sde = util::source_date_epoch()) {
893
0
        using namespace std::chrono;
894
0
        auto t = sys_seconds(seconds(*sde));
895
0
        auto d = floor<days>(t);
896
0
        year_month_day ymd(d);
897
0
        hh_mm_ss hms(t - d);
898
0
        return {
899
0
            static_cast<int>(ymd.year()),
900
0
            static_cast<int>(static_cast<unsigned>(ymd.month())),
901
0
            static_cast<int>(static_cast<unsigned>(ymd.day())),
902
0
            static_cast<int>(hms.hours().count()),
903
0
            static_cast<int>(hms.minutes().count()),
904
0
            static_cast<int>(hms.seconds().count()),
905
0
            0};
906
0
    }
907
#ifdef _WIN32
908
    SYSTEMTIME ltime;
909
    GetLocalTime(&ltime);
910
    TIME_ZONE_INFORMATION tzinfo;
911
    GetTimeZoneInformation(&tzinfo);
912
    return QPDFTime(
913
        static_cast<int>(ltime.wYear),
914
        static_cast<int>(ltime.wMonth),
915
        static_cast<int>(ltime.wDay),
916
        static_cast<int>(ltime.wHour),
917
        static_cast<int>(ltime.wMinute),
918
        static_cast<int>(ltime.wSecond),
919
        // tzinfo.Bias is minutes before UTC
920
        static_cast<int>(tzinfo.Bias));
921
#else
922
0
    struct tm ltime;
923
0
    time_t now = time(nullptr);
924
0
    tzset();
925
0
# ifdef HAVE_LOCALTIME_R
926
0
    localtime_r(&now, &ltime);
927
# else
928
    ltime = *localtime(&now);
929
# endif
930
# if HAVE_TM_GMTOFF
931
    // tm_gmtoff is seconds after UTC
932
    int tzoff = -static_cast<int>(ltime.tm_gmtoff / 60);
933
# elif HAVE_EXTERN_LONG_TIMEZONE
934
    // timezone is seconds before UTC, not adjusted for daylight saving time
935
0
    int tzoff = static_cast<int>(timezone / 60);
936
# else
937
    // Don't know how to get timezone on this platform
938
    int tzoff = 0;
939
# endif
940
0
    return {
941
0
        static_cast<int>(ltime.tm_year + 1900),
942
0
        static_cast<int>(ltime.tm_mon + 1),
943
0
        static_cast<int>(ltime.tm_mday),
944
0
        static_cast<int>(ltime.tm_hour),
945
0
        static_cast<int>(ltime.tm_min),
946
0
        static_cast<int>(ltime.tm_sec),
947
0
        tzoff};
948
0
#endif
949
0
}
950
951
std::string
952
QUtil::qpdf_time_to_pdf_time(QPDFTime const& qtm)
953
0
{
954
0
    std::string tz_offset;
955
0
    int t = qtm.tz_delta;
956
0
    if (t == 0) {
957
0
        tz_offset = "Z";
958
0
    } else {
959
0
        if (t < 0) {
960
0
            t = -t;
961
0
            tz_offset += "+";
962
0
        } else {
963
0
            tz_offset += "-";
964
0
        }
965
0
        tz_offset += QUtil::int_to_string(t / 60, 2) + "'" + QUtil::int_to_string(t % 60, 2) + "'";
966
0
    }
967
0
    return (
968
0
        "D:" + QUtil::int_to_string(qtm.year, 4) + QUtil::int_to_string(qtm.month, 2) +
969
0
        QUtil::int_to_string(qtm.day, 2) + QUtil::int_to_string(qtm.hour, 2) +
970
0
        QUtil::int_to_string(qtm.minute, 2) + QUtil::int_to_string(qtm.second, 2) + tz_offset);
971
0
}
972
973
std::string
974
QUtil::qpdf_time_to_iso8601(QPDFTime const& qtm)
975
0
{
976
0
    std::string tz_offset;
977
0
    int t = qtm.tz_delta;
978
0
    if (t == 0) {
979
0
        tz_offset = "Z";
980
0
    } else {
981
0
        if (t < 0) {
982
0
            t = -t;
983
0
            tz_offset += "+";
984
0
        } else {
985
0
            tz_offset += "-";
986
0
        }
987
0
        tz_offset += QUtil::int_to_string(t / 60, 2) + ":" + QUtil::int_to_string(t % 60, 2);
988
0
    }
989
0
    return (
990
0
        QUtil::int_to_string(qtm.year, 4) + "-" + QUtil::int_to_string(qtm.month, 2) + "-" +
991
0
        QUtil::int_to_string(qtm.day, 2) + "T" + QUtil::int_to_string(qtm.hour, 2) + ":" +
992
0
        QUtil::int_to_string(qtm.minute, 2) + ":" + QUtil::int_to_string(qtm.second, 2) +
993
0
        tz_offset);
994
0
}
995
996
bool
997
QUtil::pdf_time_to_qpdf_time(std::string const& str, QPDFTime* qtm)
998
0
{
999
0
    static std::regex pdf_date(
1000
0
        "^D:([0-9]{4})([0-9]{2})([0-9]{2})"
1001
0
        "([0-9]{2})([0-9]{2})([0-9]{2})"
1002
0
        "(?:(Z?)|([\\+\\-])([0-9]{2})'([0-9]{2})')$");
1003
0
    std::smatch m;
1004
0
    if (!std::regex_match(str, m, pdf_date)) {
1005
0
        return false;
1006
0
    }
1007
0
    int tz_delta = 0;
1008
0
    auto to_i = [](std::string const& s) { return QUtil::string_to_int(s.c_str()); };
1009
1010
0
    if (m[8] != "") {
1011
0
        tz_delta = ((to_i(m[9]) * 60) + to_i(m[10]));
1012
0
        if (m[8] == "+") {
1013
0
            tz_delta = -tz_delta;
1014
0
        }
1015
0
    }
1016
0
    if (qtm) {
1017
0
        *qtm = QPDFTime(
1018
0
            to_i(m[1]), to_i(m[2]), to_i(m[3]), to_i(m[4]), to_i(m[5]), to_i(m[6]), tz_delta);
1019
0
    }
1020
0
    return true;
1021
0
}
1022
1023
bool
1024
QUtil::pdf_time_to_iso8601(std::string const& pdf_time, std::string& iso8601)
1025
0
{
1026
0
    QPDFTime qtm;
1027
0
    if (pdf_time_to_qpdf_time(pdf_time, &qtm)) {
1028
0
        iso8601 = qpdf_time_to_iso8601(qtm);
1029
0
        return true;
1030
0
    }
1031
0
    return false;
1032
0
}
1033
1034
std::string
1035
QUtil::toUTF8(unsigned long uval)
1036
0
{
1037
0
    std::string result;
1038
1039
    // A UTF-8 encoding of a Unicode value is a single byte for Unicode values <= 127.  For larger
1040
    // values, the first byte of the UTF-8 encoding has '1' as each of its n highest bits and '0'
1041
    // for its (n+1)th highest bit where n is the total number of bytes required.  Subsequent bytes
1042
    // start with '10' and have the remaining 6 bits free for encoding.  For example, an 11-bit
1043
    // Unicode value can be stored in two bytes where the first is 110zzzzz, the second is 10zzzzzz,
1044
    // and the z's represent the remaining bits.
1045
1046
0
    if (uval > 0x7fffffff) {
1047
0
        throw std::runtime_error("bounds error in QUtil::toUTF8");
1048
0
    } else if (uval < 128) {
1049
0
        result += static_cast<char>(uval);
1050
0
    } else {
1051
0
        unsigned char bytes[7];
1052
0
        bytes[6] = '\0';
1053
0
        unsigned char* cur_byte = &bytes[5];
1054
1055
        // maximum value that will fit in the current number of bytes
1056
0
        unsigned char maxval = 0x3f; // six bits
1057
1058
0
        while (uval > QIntC::to_ulong(maxval)) {
1059
            // Assign low six bits plus 10000000 to lowest unused byte position, then shift
1060
0
            *cur_byte = static_cast<unsigned char>(0x80 + (uval & 0x3f));
1061
0
            uval >>= 6;
1062
            // Maximum that will fit in high byte now shrinks by one bit
1063
0
            maxval = static_cast<unsigned char>(maxval >> 1);
1064
            // Slide to the left one byte
1065
0
            if (cur_byte <= bytes) {
1066
0
                throw std::logic_error("QUtil::toUTF8: overflow error");
1067
0
            }
1068
0
            --cur_byte;
1069
0
        }
1070
        // If maxval is k bits long, the high (7 - k) bits of the resulting byte must be high.
1071
0
        *cur_byte = static_cast<unsigned char>(QIntC::to_ulong(0xff - (1 + (maxval << 1))) + uval);
1072
1073
0
        result += reinterpret_cast<char*>(cur_byte);
1074
0
    }
1075
1076
0
    return result;
1077
0
}
1078
1079
std::string
1080
QUtil::toUTF16(unsigned long uval)
1081
0
{
1082
0
    std::string result;
1083
0
    if ((uval >= 0xd800) && (uval <= 0xdfff)) {
1084
0
        result = "\xff\xfd";
1085
0
    } else if (uval <= 0xffff) {
1086
0
        char out[2];
1087
0
        out[0] = static_cast<char>((uval & 0xff00) >> 8);
1088
0
        out[1] = static_cast<char>(uval & 0xff);
1089
0
        result = std::string(out, 2);
1090
0
    } else if (uval <= 0x10ffff) {
1091
0
        char out[4];
1092
0
        uval -= 0x10000;
1093
0
        unsigned short high = static_cast<unsigned short>(((uval & 0xffc00) >> 10) + 0xd800);
1094
0
        unsigned short low = static_cast<unsigned short>((uval & 0x3ff) + 0xdc00);
1095
0
        out[0] = static_cast<char>((high & 0xff00) >> 8);
1096
0
        out[1] = static_cast<char>(high & 0xff);
1097
0
        out[2] = static_cast<char>((low & 0xff00) >> 8);
1098
0
        out[3] = static_cast<char>(low & 0xff);
1099
0
        result = std::string(out, 4);
1100
0
    } else {
1101
0
        result = "\xff\xfd";
1102
0
    }
1103
1104
0
    return result;
1105
0
}
1106
1107
// Random data support
1108
1109
namespace
1110
{
1111
    class RandomDataProviderProvider
1112
    {
1113
      public:
1114
        RandomDataProviderProvider();
1115
        void setProvider(RandomDataProvider*);
1116
        RandomDataProvider* getProvider();
1117
1118
      private:
1119
        RandomDataProvider* default_provider;
1120
        RandomDataProvider* current_provider{nullptr};
1121
    };
1122
} // namespace
1123
1124
RandomDataProviderProvider::RandomDataProviderProvider() :
1125
1
    default_provider(CryptoRandomDataProvider::getInstance())
1126
1
{
1127
1
    this->current_provider = default_provider;
1128
1
}
1129
1130
RandomDataProvider*
1131
RandomDataProviderProvider::getProvider()
1132
360
{
1133
360
    return this->current_provider;
1134
360
}
1135
1136
void
1137
RandomDataProviderProvider::setProvider(RandomDataProvider* p)
1138
0
{
1139
0
    this->current_provider = p ? p : this->default_provider;
1140
0
}
1141
1142
static RandomDataProviderProvider*
1143
getRandomDataProviderProvider()
1144
360
{
1145
    // Thread-safe static initializer
1146
360
    static RandomDataProviderProvider rdpp;
1147
360
    return &rdpp;
1148
360
}
1149
1150
void
1151
QUtil::setRandomDataProvider(RandomDataProvider* p)
1152
0
{
1153
0
    getRandomDataProviderProvider()->setProvider(p);
1154
0
}
1155
1156
RandomDataProvider*
1157
QUtil::getRandomDataProvider()
1158
360
{
1159
360
    return getRandomDataProviderProvider()->getProvider();
1160
360
}
1161
1162
void
1163
QUtil::initializeWithRandomBytes(unsigned char* data, size_t len)
1164
360
{
1165
360
    getRandomDataProvider()->provideRandomData(data, len);
1166
360
}
1167
1168
std::string
1169
util::random_string(size_t len)
1170
0
{
1171
0
    std::string result(len, '\0');
1172
0
    QUtil::initializeWithRandomBytes(reinterpret_cast<unsigned char*>(result.data()), len);
1173
0
    return result;
1174
0
}
1175
1176
long
1177
QUtil::random()
1178
0
{
1179
0
    long result = 0L;
1180
0
    initializeWithRandomBytes(reinterpret_cast<unsigned char*>(&result), sizeof(result));
1181
0
    return result;
1182
0
}
1183
1184
void
1185
QUtil::read_file_into_memory(char const* filename, std::shared_ptr<char>& file_buf, size_t& size)
1186
0
{
1187
0
    FILE* f = safe_fopen(filename, "rb");
1188
0
    FileCloser fc(f);
1189
0
    fseek(f, 0, SEEK_END);
1190
0
    size = QIntC::to_size(QUtil::tell(f));
1191
0
    fseek(f, 0, SEEK_SET);
1192
0
    file_buf = QUtil::make_shared_array<char>(size);
1193
0
    char* buf_p = file_buf.get();
1194
0
    size_t bytes_read = 0;
1195
0
    size_t len = 0;
1196
0
    while ((len = fread(buf_p + bytes_read, 1, size - bytes_read, f)) > 0) {
1197
0
        bytes_read += len;
1198
0
    }
1199
0
    if (bytes_read != size) {
1200
0
        if (ferror(f)) {
1201
0
            throw std::runtime_error(
1202
0
                std::string("failure reading file ") + filename + " into memory: read " +
1203
0
                uint_to_string(bytes_read) + "; wanted " + uint_to_string(size));
1204
0
        } else {
1205
0
            throw std::runtime_error(
1206
0
                std::string("premature eof reading file ") + filename + " into memory: read " +
1207
0
                uint_to_string(bytes_read) + "; wanted " + uint_to_string(size));
1208
0
        }
1209
0
    }
1210
0
}
1211
1212
std::string
1213
QUtil::read_file_into_string(char const* filename)
1214
0
{
1215
0
    FILE* f = safe_fopen(filename, "rb");
1216
0
    FileCloser fc(f);
1217
0
    return read_file_into_string(f, filename);
1218
0
}
1219
1220
std::string
1221
QUtil::read_file_into_string(FILE* f, std::string_view filename)
1222
0
{
1223
0
    fseek(f, 0, SEEK_END);
1224
0
    auto o_size = QUtil::tell(f);
1225
0
    if (o_size >= 0) {
1226
        // Seekable file
1227
0
        auto size = QIntC::to_size(o_size);
1228
0
        fseek(f, 0, SEEK_SET);
1229
0
        std::string result(size, '\0');
1230
0
        if (auto n_read = fread(result.data(), 1, size, f); n_read != size) {
1231
0
            if (ferror(f)) {
1232
0
                throw std::runtime_error(
1233
0
                    std::string("failure reading file ") + std::string(filename) +
1234
0
                    " into memory: read " + uint_to_string(n_read) + "; wanted " +
1235
0
                    uint_to_string(size));
1236
0
            } else {
1237
0
                throw std::runtime_error(
1238
0
                    std::string("premature eof reading file ") + std::string(filename) +
1239
0
                    " into memory: read " + uint_to_string(n_read) + "; wanted " +
1240
0
                    uint_to_string(size));
1241
0
            }
1242
0
        }
1243
0
        return result;
1244
0
    } else {
1245
        // Pipe or other non-seekable file
1246
0
        size_t buf_size = 8192;
1247
0
        auto n_read = buf_size;
1248
0
        std::string buffer(buf_size, '\0');
1249
0
        std::string result;
1250
0
        while (n_read == buf_size) {
1251
0
            n_read = fread(buffer.data(), 1, buf_size, f);
1252
0
            buffer.erase(n_read);
1253
0
            result.append(buffer);
1254
0
        }
1255
0
        if (ferror(f)) {
1256
0
            throw std::runtime_error(
1257
0
                std::string("failure reading file ") + std::string(filename) + " into memory");
1258
0
        }
1259
0
        return result;
1260
0
    }
1261
0
}
1262
1263
static bool
1264
read_char_from_FILE(char& ch, FILE* f)
1265
0
{
1266
0
    auto len = fread(&ch, 1, 1, f);
1267
0
    if (len == 0) {
1268
0
        if (ferror(f)) {
1269
0
            throw std::runtime_error("failure reading character from file");
1270
0
        }
1271
0
        return false;
1272
0
    }
1273
0
    return true;
1274
0
}
1275
1276
std::list<std::string>
1277
QUtil::read_lines_from_file(char const* filename, bool preserve_eol)
1278
0
{
1279
0
    std::list<std::string> lines;
1280
0
    FILE* f = safe_fopen(filename, "rb");
1281
0
    FileCloser fc(f);
1282
0
    auto next_char = [&f](char& ch) { return read_char_from_FILE(ch, f); };
1283
0
    read_lines_from_file(next_char, lines, preserve_eol);
1284
0
    return lines;
1285
0
}
1286
1287
std::list<std::string>
1288
QUtil::read_lines_from_file(std::istream& in, bool preserve_eol)
1289
0
{
1290
0
    std::list<std::string> lines;
1291
0
    auto next_char = [&in](char& ch) { return (in.get(ch)) ? true : false; };
1292
0
    read_lines_from_file(next_char, lines, preserve_eol);
1293
0
    return lines;
1294
0
}
1295
1296
std::list<std::string>
1297
QUtil::read_lines_from_file(FILE* f, bool preserve_eol)
1298
0
{
1299
0
    std::list<std::string> lines;
1300
0
    auto next_char = [&f](char& ch) { return read_char_from_FILE(ch, f); };
1301
0
    read_lines_from_file(next_char, lines, preserve_eol);
1302
0
    return lines;
1303
0
}
1304
1305
void
1306
QUtil::read_lines_from_file(
1307
    std::function<bool(char&)> next_char, std::list<std::string>& lines, bool preserve_eol)
1308
0
{
1309
0
    std::string* buf = nullptr;
1310
0
    char c;
1311
0
    while (next_char(c)) {
1312
0
        if (buf == nullptr) {
1313
0
            lines.emplace_back("");
1314
0
            buf = &(lines.back());
1315
0
            buf->reserve(80);
1316
0
        }
1317
1318
0
        if (buf->capacity() == buf->size()) {
1319
0
            buf->reserve(buf->capacity() * 2);
1320
0
        }
1321
0
        if (c == '\n') {
1322
0
            if (preserve_eol) {
1323
0
                buf->append(1, c);
1324
0
            } else {
1325
                // Remove any carriage return that preceded the newline and discard the newline
1326
0
                if ((!buf->empty()) && ((*(buf->rbegin())) == '\r')) {
1327
0
                    buf->erase(buf->length() - 1);
1328
0
                }
1329
0
            }
1330
0
            buf = nullptr;
1331
0
        } else {
1332
0
            buf->append(1, c);
1333
0
        }
1334
0
    }
1335
0
}
1336
1337
int
1338
QUtil::str_compare_nocase(char const* s1, char const* s2)
1339
0
{
1340
#if defined(_WIN32) && defined(__BORLANDC__)
1341
    return stricmp(s1, s2);
1342
#elif defined(_WIN32)
1343
    return _stricmp(s1, s2);
1344
#else
1345
0
    return strcasecmp(s1, s2);
1346
0
#endif
1347
0
}
1348
1349
std::vector<int>
1350
QUtil::parse_numrange(char const* range, int max)
1351
0
{
1352
    // Performance note: this implementation aims to be straightforward, not efficient. Numeric
1353
    // range parsing is used only during argument processing. It is not used during processing of
1354
    // PDF files.
1355
1356
0
    static std::regex group_re(R"((x)?(z|r?\d+)(?:-(z|r?\d+))?)");
1357
0
    auto parse_num = [&max](std::string const& s) -> int {
1358
0
        if (s == "z") {
1359
0
            return max;
1360
0
        }
1361
0
        int num;
1362
0
        if (s.at(0) == 'r') {
1363
0
            num = max + 1 - string_to_int(s.substr(1).c_str());
1364
0
        } else {
1365
0
            num = string_to_int(s.c_str());
1366
0
        }
1367
        // max == 0 means we don't know the max and are just testing for valid syntax.
1368
0
        if ((max > 0) && ((num < 1) || (num > max))) {
1369
0
            throw std::runtime_error("number " + std::to_string(num) + " out of range");
1370
0
        }
1371
0
        return num;
1372
0
    };
1373
1374
0
    auto populate = [](std::vector<int>& group, int first_num, bool is_span, int last_num) {
1375
0
        group.clear();
1376
0
        group.emplace_back(first_num);
1377
0
        if (is_span) {
1378
0
            if (first_num > last_num) {
1379
0
                for (auto i = first_num - 1; i >= last_num; --i) {
1380
0
                    group.push_back(i);
1381
0
                }
1382
0
            } else {
1383
0
                for (auto i = first_num + 1; i <= last_num; ++i) {
1384
0
                    group.push_back(i);
1385
0
                }
1386
0
            }
1387
0
        }
1388
0
    };
1389
1390
0
    char const* p;
1391
0
    try {
1392
0
        char const* range_end = range + strlen(range);
1393
0
        std::vector<int> result;
1394
0
        std::vector<int> last_group;
1395
        // See if range ends with :even or :odd.
1396
0
        size_t start_idx = 0;
1397
0
        size_t skip = 1;
1398
0
        p = std::find(range, range_end, ':');
1399
0
        if (*p == ':') {
1400
0
            if (strcmp(p, ":odd") == 0) {
1401
0
                skip = 2;
1402
0
            } else if (strcmp(p, ":even") == 0) {
1403
0
                skip = 2;
1404
0
                start_idx = 1;
1405
0
            } else {
1406
0
                throw std::runtime_error("expected :even or :odd");
1407
0
            }
1408
0
            range_end = p;
1409
0
        }
1410
1411
        // Divide the range into groups
1412
0
        p = range;
1413
0
        char const* group_end;
1414
0
        bool first = true;
1415
0
        while (p != range_end) {
1416
0
            group_end = std::find(p, range_end, ',');
1417
0
            std::cmatch m;
1418
0
            if (!std::regex_match(p, group_end, m, group_re)) {
1419
0
                throw std::runtime_error("invalid range syntax");
1420
0
            }
1421
0
            auto is_exclude = m[1].matched;
1422
0
            if (first && is_exclude) {
1423
0
                throw std::runtime_error("first range group may not be an exclusion");
1424
0
            }
1425
0
            first = false;
1426
0
            auto first_num = parse_num(m[2].str());
1427
0
            auto is_span = m[3].matched;
1428
0
            int last_num{0};
1429
0
            if (is_span) {
1430
0
                last_num = parse_num(m[3].str());
1431
0
            }
1432
0
            if (is_exclude) {
1433
0
                std::vector<int> work;
1434
0
                populate(work, first_num, is_span, last_num);
1435
0
                std::set<int> exclusions;
1436
0
                exclusions.insert(work.begin(), work.end());
1437
0
                work = last_group;
1438
0
                last_group.clear();
1439
0
                for (auto n: work) {
1440
0
                    if (!exclusions.contains(n)) {
1441
0
                        last_group.emplace_back(n);
1442
0
                    }
1443
0
                }
1444
0
            } else {
1445
0
                result.insert(result.end(), last_group.begin(), last_group.end());
1446
0
                populate(last_group, first_num, is_span, last_num);
1447
0
            }
1448
0
            p = group_end;
1449
0
            if (*p == ',') {
1450
0
                ++p;
1451
0
                if (p == range_end) {
1452
0
                    throw std::runtime_error("trailing comma");
1453
0
                }
1454
0
            }
1455
0
        }
1456
0
        result.insert(result.end(), last_group.begin(), last_group.end());
1457
0
        if (skip == 1) {
1458
0
            return result;
1459
0
        }
1460
0
        std::vector<int> filtered;
1461
0
        for (auto i = start_idx; i < result.size(); i += skip) {
1462
0
            filtered.emplace_back(result.at(i));
1463
0
        }
1464
0
        return filtered;
1465
0
    } catch (std::runtime_error const& e) {
1466
0
        std::string message;
1467
0
        if (p) {
1468
0
            message = "error at * in numeric range " +
1469
0
                std::string(range, QIntC::to_size(p - range)) + "*" + p + ": " + e.what();
1470
0
        } else {
1471
0
            message = "error in numeric range " + std::string(range) + ": " + e.what();
1472
0
        }
1473
0
        throw std::runtime_error(message);
1474
0
    }
1475
0
}
1476
1477
enum encoding_e { e_utf16, e_ascii, e_winansi, e_macroman, e_pdfdoc };
1478
1479
static unsigned char
1480
encode_winansi(unsigned long codepoint)
1481
0
{
1482
0
    auto i = unicode_to_win_ansi.find(codepoint);
1483
0
    if (i != unicode_to_win_ansi.end()) {
1484
0
        return i->second;
1485
0
    }
1486
0
    return '\0';
1487
0
}
1488
1489
static unsigned char
1490
encode_macroman(unsigned long codepoint)
1491
0
{
1492
0
    auto i = unicode_to_mac_roman.find(codepoint);
1493
0
    if (i != unicode_to_mac_roman.end()) {
1494
0
        return i->second;
1495
0
    }
1496
0
    return '\0';
1497
0
}
1498
1499
static unsigned char
1500
encode_pdfdoc(unsigned long codepoint)
1501
0
{
1502
0
    auto i = unicode_to_pdf_doc.find(codepoint);
1503
0
    if (i != unicode_to_pdf_doc.end()) {
1504
0
        return i->second;
1505
0
    }
1506
0
    return '\0';
1507
0
}
1508
1509
unsigned long
1510
QUtil::get_next_utf8_codepoint(std::string const& utf8_val, size_t& pos, bool& error)
1511
0
{
1512
0
    auto o_pos = pos;
1513
0
    size_t len = utf8_val.length();
1514
0
    unsigned char ch = static_cast<unsigned char>(utf8_val.at(pos++));
1515
0
    error = false;
1516
0
    if (ch < 128) {
1517
0
        return static_cast<unsigned long>(ch);
1518
0
    }
1519
1520
0
    size_t bytes_needed = 0;
1521
0
    unsigned bit_check = 0x40;
1522
0
    unsigned char to_clear = 0x80;
1523
0
    while (ch & bit_check) {
1524
0
        ++bytes_needed;
1525
0
        to_clear = static_cast<unsigned char>(to_clear | bit_check);
1526
0
        bit_check >>= 1;
1527
0
    }
1528
0
    if (((bytes_needed > 5) || (bytes_needed < 1)) || ((pos + bytes_needed) > len)) {
1529
0
        error = true;
1530
0
        return 0xfffd;
1531
0
    }
1532
1533
0
    auto codepoint = static_cast<unsigned long>(ch & ~to_clear);
1534
0
    while (bytes_needed > 0) {
1535
0
        --bytes_needed;
1536
0
        ch = static_cast<unsigned char>(utf8_val.at(pos++));
1537
0
        if ((ch & 0xc0) != 0x80) {
1538
0
            --pos;
1539
0
            error = true;
1540
0
            return 0xfffd;
1541
0
        }
1542
0
        codepoint <<= 6;
1543
0
        codepoint += (ch & 0x3f);
1544
0
    }
1545
0
    unsigned long lower_bound = 0;
1546
0
    switch (pos - o_pos) {
1547
0
    case 2:
1548
0
        lower_bound = 1 << 7;
1549
0
        break;
1550
0
    case 3:
1551
0
        lower_bound = 1 << 11;
1552
0
        break;
1553
0
    case 4:
1554
0
        lower_bound = 1 << 16;
1555
0
        break;
1556
0
    case 5:
1557
0
        lower_bound = 1 << 21;
1558
0
        break;
1559
0
    case 6:
1560
0
        lower_bound = 1 << 26;
1561
0
        break;
1562
0
    default:
1563
0
        lower_bound = 0;
1564
0
    }
1565
1566
0
    if (lower_bound > 0 && codepoint < lower_bound) {
1567
        // Too many bytes were used, but return whatever character was encoded.
1568
0
        error = true;
1569
0
    }
1570
0
    return codepoint;
1571
0
}
1572
1573
static bool
1574
transcode_utf8(std::string const& utf8_val, std::string& result, encoding_e encoding, char unknown)
1575
0
{
1576
0
    bool okay = true;
1577
0
    result.clear();
1578
0
    size_t len = utf8_val.length();
1579
0
    switch (encoding) {
1580
0
    case e_utf16:
1581
0
        result += "\xfe\xff";
1582
0
        break;
1583
0
    case e_pdfdoc:
1584
        // We need to avoid having the result start with something that will be interpreted as
1585
        // UTF-16 or UTF-8, meaning we can't end up with a string that starts with "fe ff",
1586
        // (UTF-16-BE) "ff fe" (UTF-16-LE, not officially part of the PDF spec, but recognized by
1587
        // most readers including qpdf), or "ef bb bf" (UTF-8). It's more efficient to check the
1588
        // input string to see if it will map to one of those sequences than to check the output
1589
        // string since all cases start with the same starting character.
1590
0
        if ((len >= 4) && (utf8_val[0] == '\xc3')) {
1591
0
            static std::string fe_ff("\xbe\xc3\xbf");
1592
0
            static std::string ff_fe("\xbf\xc3\xbe");
1593
0
            static std::string ef_bb_bf("\xaf\xc2\xbb\xc2\xbf");
1594
            // C++-20 has starts_with, but when this was written, qpdf had a minimum supported
1595
            // version of C++-17.
1596
0
            if ((utf8_val.compare(1, 3, fe_ff) == 0) || (utf8_val.compare(1, 3, ff_fe) == 0) ||
1597
0
                (utf8_val.compare(1, 5, ef_bb_bf) == 0)) {
1598
0
                result += unknown;
1599
0
                okay = false;
1600
0
            }
1601
0
        }
1602
0
        break;
1603
0
    default:
1604
0
        break;
1605
0
    }
1606
0
    size_t pos = 0;
1607
0
    while (pos < len) {
1608
0
        bool error = false;
1609
0
        unsigned long codepoint = QUtil::get_next_utf8_codepoint(utf8_val, pos, error);
1610
0
        if (error) {
1611
0
            okay = false;
1612
0
            if (encoding == e_utf16) {
1613
0
                result += "\xff\xfd";
1614
0
            } else {
1615
0
                result.append(1, unknown);
1616
0
            }
1617
0
        } else if (codepoint < 128) {
1618
0
            char ch = static_cast<char>(codepoint);
1619
0
            if (encoding == e_utf16) {
1620
0
                result += QUtil::toUTF16(QIntC::to_ulong(ch));
1621
0
            } else if ((encoding == e_pdfdoc) && (((ch >= 0x18) && (ch <= 0x1f)) || (ch == 127))) {
1622
                // PDFDocEncoding maps some low characters to Unicode, so if we encounter those
1623
                // invalid UTF-8 code points, map them to unknown so reversing the mapping doesn't
1624
                // change them into other characters.
1625
0
                okay = false;
1626
0
                result.append(1, unknown);
1627
0
            } else {
1628
0
                result.append(1, ch);
1629
0
            }
1630
0
        } else if (encoding == e_utf16) {
1631
0
            result += QUtil::toUTF16(codepoint);
1632
0
        } else if ((codepoint == 0xad) && (encoding == e_pdfdoc)) {
1633
            // PDFDocEncoding omits 0x00ad (soft hyphen).
1634
0
            okay = false;
1635
0
            result.append(1, unknown);
1636
0
        } else if (
1637
0
            (codepoint > 160) && (codepoint < 256) &&
1638
0
            ((encoding == e_winansi) || (encoding == e_pdfdoc))) {
1639
0
            result.append(1, static_cast<char>(codepoint & 0xff));
1640
0
        } else {
1641
0
            unsigned char ch = '\0';
1642
0
            if (encoding == e_winansi) {
1643
0
                ch = encode_winansi(codepoint);
1644
0
            } else if (encoding == e_macroman) {
1645
0
                ch = encode_macroman(codepoint);
1646
0
            } else if (encoding == e_pdfdoc) {
1647
0
                ch = encode_pdfdoc(codepoint);
1648
0
            }
1649
0
            if (ch == '\0') {
1650
0
                okay = false;
1651
0
                ch = static_cast<unsigned char>(unknown);
1652
0
            }
1653
0
            result.append(1, static_cast<char>(ch));
1654
0
        }
1655
0
    }
1656
0
    return okay;
1657
0
}
1658
1659
static std::string
1660
transcode_utf8(std::string const& utf8_val, encoding_e encoding, char unknown)
1661
0
{
1662
0
    std::string result;
1663
0
    transcode_utf8(utf8_val, result, encoding, unknown);
1664
0
    return result;
1665
0
}
1666
1667
std::string
1668
QUtil::utf8_to_utf16(std::string const& utf8)
1669
0
{
1670
0
    return transcode_utf8(utf8, e_utf16, 0);
1671
0
}
1672
1673
std::string
1674
QUtil::utf8_to_ascii(std::string const& utf8, char unknown_char)
1675
0
{
1676
0
    return transcode_utf8(utf8, e_ascii, unknown_char);
1677
0
}
1678
1679
std::string
1680
QUtil::utf8_to_win_ansi(std::string const& utf8, char unknown_char)
1681
0
{
1682
0
    return transcode_utf8(utf8, e_winansi, unknown_char);
1683
0
}
1684
1685
std::string
1686
QUtil::utf8_to_mac_roman(std::string const& utf8, char unknown_char)
1687
0
{
1688
0
    return transcode_utf8(utf8, e_macroman, unknown_char);
1689
0
}
1690
1691
std::string
1692
QUtil::utf8_to_pdf_doc(std::string const& utf8, char unknown_char)
1693
0
{
1694
0
    return transcode_utf8(utf8, e_pdfdoc, unknown_char);
1695
0
}
1696
1697
bool
1698
QUtil::utf8_to_ascii(std::string const& utf8, std::string& ascii, char unknown_char)
1699
0
{
1700
0
    return transcode_utf8(utf8, ascii, e_ascii, unknown_char);
1701
0
}
1702
1703
bool
1704
QUtil::utf8_to_win_ansi(std::string const& utf8, std::string& win, char unknown_char)
1705
0
{
1706
0
    return transcode_utf8(utf8, win, e_winansi, unknown_char);
1707
0
}
1708
1709
bool
1710
QUtil::utf8_to_mac_roman(std::string const& utf8, std::string& mac, char unknown_char)
1711
0
{
1712
0
    return transcode_utf8(utf8, mac, e_macroman, unknown_char);
1713
0
}
1714
1715
bool
1716
QUtil::utf8_to_pdf_doc(std::string const& utf8, std::string& pdfdoc, char unknown_char)
1717
0
{
1718
0
    return transcode_utf8(utf8, pdfdoc, e_pdfdoc, unknown_char);
1719
0
}
1720
1721
bool
1722
QUtil::is_utf16(std::string const& val)
1723
0
{
1724
0
    return util::is_utf16(val);
1725
0
}
1726
1727
bool
1728
QUtil::is_explicit_utf8(std::string const& val)
1729
0
{
1730
0
    return util::is_explicit_utf8(val);
1731
0
}
1732
1733
std::string
1734
QUtil::utf16_to_utf8(std::string const& val)
1735
0
{
1736
0
    std::string result;
1737
    // This code uses unsigned long and unsigned short to hold codepoint values. It requires
1738
    // unsigned long to be at least 32 bits and unsigned short to be at least 16 bits, but it will
1739
    // work fine if they are larger.
1740
0
    unsigned long codepoint = 0L;
1741
0
    size_t len = val.length();
1742
0
    size_t start = 0;
1743
0
    bool is_le = false;
1744
0
    if (is_utf16(val)) {
1745
0
        if (static_cast<unsigned char>(val.at(0)) == 0xff) {
1746
0
            is_le = true;
1747
0
        }
1748
0
        start += 2;
1749
0
    }
1750
    // If the string has an odd number of bytes, the last byte is ignored.
1751
0
    for (size_t i = start; i + 1 < len; i += 2) {
1752
        // Convert from UTF16-BE.  If we get a malformed codepoint, this code will generate
1753
        // incorrect output without giving a warning.  Specifically, a high codepoint not followed
1754
        // by a low codepoint will be discarded, and a low codepoint not preceded by a high
1755
        // codepoint will just get its low 10 bits output.
1756
0
        auto msb = is_le ? i + 1 : i;
1757
0
        auto lsb = is_le ? i : i + 1;
1758
0
        unsigned short bits = QIntC::to_ushort(
1759
0
            (static_cast<unsigned char>(val.at(msb)) << 8) +
1760
0
            static_cast<unsigned char>(val.at(lsb)));
1761
0
        if ((bits & 0xFC00) == 0xD800) {
1762
0
            codepoint = 0x10000U + ((bits & 0x3FFU) << 10U);
1763
0
            continue;
1764
0
        } else if ((bits & 0xFC00) == 0xDC00) {
1765
0
            if (codepoint != 0) {
1766
0
                QTC::TC("qpdf", "QUtil non-trivial UTF-16");
1767
0
            }
1768
0
            codepoint += bits & 0x3FF;
1769
0
        } else {
1770
0
            codepoint = bits;
1771
0
        }
1772
1773
0
        result += QUtil::toUTF8(codepoint);
1774
0
        codepoint = 0;
1775
0
    }
1776
0
    return result;
1777
0
}
1778
1779
std::string
1780
QUtil::win_ansi_to_utf8(std::string const& val)
1781
0
{
1782
0
    std::string result;
1783
0
    size_t len = val.length();
1784
0
    for (unsigned int i = 0; i < len; ++i) {
1785
0
        unsigned char ch = static_cast<unsigned char>(val.at(i));
1786
0
        unsigned short ch_short = ch;
1787
0
        if ((ch >= 128) && (ch <= 160)) {
1788
0
            ch_short = win_ansi_to_unicode[ch - 128];
1789
0
        }
1790
0
        result += QUtil::toUTF8(ch_short);
1791
0
    }
1792
0
    return result;
1793
0
}
1794
1795
std::string
1796
QUtil::mac_roman_to_utf8(std::string const& val)
1797
0
{
1798
0
    std::string result;
1799
0
    size_t len = val.length();
1800
0
    for (unsigned int i = 0; i < len; ++i) {
1801
0
        unsigned char ch = static_cast<unsigned char>(val.at(i));
1802
0
        unsigned short ch_short = ch;
1803
0
        if (ch >= 128) {
1804
0
            ch_short = mac_roman_to_unicode[ch - 128];
1805
0
        }
1806
0
        result += QUtil::toUTF8(ch_short);
1807
0
    }
1808
0
    return result;
1809
0
}
1810
1811
std::string
1812
QUtil::pdf_doc_to_utf8(std::string const& val)
1813
0
{
1814
0
    std::string result;
1815
0
    size_t len = val.length();
1816
0
    for (unsigned int i = 0; i < len; ++i) {
1817
0
        unsigned char ch = static_cast<unsigned char>(val.at(i));
1818
0
        unsigned short ch_short = ch;
1819
0
        if ((ch >= 127) && (ch <= 160)) {
1820
0
            ch_short = pdf_doc_to_unicode[ch - 127];
1821
0
        } else if ((ch >= 24) && (ch <= 31)) {
1822
0
            ch_short = pdf_doc_low_to_unicode[ch - 24];
1823
0
        } else if (ch == 173) {
1824
0
            ch_short = 0xfffd;
1825
0
        }
1826
0
        result += QUtil::toUTF8(ch_short);
1827
0
    }
1828
0
    return result;
1829
0
}
1830
1831
void
1832
QUtil::analyze_encoding(
1833
    std::string const& val, bool& has_8bit_chars, bool& is_valid_utf8, bool& is_utf16)
1834
0
{
1835
0
    has_8bit_chars = is_utf16 = is_valid_utf8 = false;
1836
0
    if (QUtil::is_utf16(val)) {
1837
0
        has_8bit_chars = true;
1838
0
        is_utf16 = true;
1839
0
        return;
1840
0
    }
1841
0
    size_t len = val.length();
1842
0
    size_t pos = 0;
1843
0
    bool any_errors = false;
1844
0
    while (pos < len) {
1845
0
        bool error = false;
1846
0
        auto o_pos = pos;
1847
0
        get_next_utf8_codepoint(val, pos, error);
1848
0
        if (error) {
1849
0
            any_errors = true;
1850
0
        }
1851
0
        if (pos - o_pos > 1 || val[o_pos] & 0x80) {
1852
0
            has_8bit_chars = true;
1853
0
        }
1854
0
    }
1855
0
    if (has_8bit_chars && (!any_errors)) {
1856
0
        is_valid_utf8 = true;
1857
0
    }
1858
0
}
1859
1860
std::vector<std::string>
1861
QUtil::possible_repaired_encodings(std::string supplied)
1862
0
{
1863
0
    std::vector<std::string> result;
1864
    // Always include the original string
1865
0
    result.push_back(supplied);
1866
0
    bool has_8bit_chars = false;
1867
0
    bool is_valid_utf8 = false;
1868
0
    bool is_utf16 = false;
1869
0
    analyze_encoding(supplied, has_8bit_chars, is_valid_utf8, is_utf16);
1870
0
    if (!has_8bit_chars) {
1871
0
        return result;
1872
0
    }
1873
0
    if (is_utf16) {
1874
        // Convert to UTF-8 and pretend we got a UTF-8 string.
1875
0
        is_utf16 = false;
1876
0
        is_valid_utf8 = true;
1877
0
        supplied = utf16_to_utf8(supplied);
1878
0
    }
1879
0
    std::string output;
1880
0
    if (is_valid_utf8) {
1881
        // Maybe we were given UTF-8 but wanted one of the single-byte encodings.
1882
0
        if (utf8_to_pdf_doc(supplied, output)) {
1883
0
            result.push_back(output);
1884
0
        }
1885
0
        if (utf8_to_win_ansi(supplied, output)) {
1886
0
            result.push_back(output);
1887
0
        }
1888
0
        if (utf8_to_mac_roman(supplied, output)) {
1889
0
            result.push_back(output);
1890
0
        }
1891
0
    } else {
1892
        // Maybe we were given one of the single-byte encodings but wanted UTF-8.
1893
0
        std::string from_pdf_doc(pdf_doc_to_utf8(supplied));
1894
0
        result.push_back(from_pdf_doc);
1895
0
        std::string from_win_ansi(win_ansi_to_utf8(supplied));
1896
0
        result.push_back(from_win_ansi);
1897
0
        std::string from_mac_roman(mac_roman_to_utf8(supplied));
1898
0
        result.push_back(from_mac_roman);
1899
1900
        // Maybe we were given one of the other single-byte encodings but wanted one of the other
1901
        // ones.
1902
0
        if (utf8_to_win_ansi(from_pdf_doc, output)) {
1903
0
            result.push_back(output);
1904
0
        }
1905
0
        if (utf8_to_mac_roman(from_pdf_doc, output)) {
1906
0
            result.push_back(output);
1907
0
        }
1908
0
        if (utf8_to_pdf_doc(from_win_ansi, output)) {
1909
0
            result.push_back(output);
1910
0
        }
1911
0
        if (utf8_to_mac_roman(from_win_ansi, output)) {
1912
0
            result.push_back(output);
1913
0
        }
1914
0
        if (utf8_to_pdf_doc(from_mac_roman, output)) {
1915
0
            result.push_back(output);
1916
0
        }
1917
0
        if (utf8_to_win_ansi(from_mac_roman, output)) {
1918
0
            result.push_back(output);
1919
0
        }
1920
0
    }
1921
    // De-duplicate
1922
0
    std::vector<std::string> t;
1923
0
    std::set<std::string> seen;
1924
0
    for (auto const& iter: result) {
1925
0
        if (!seen.contains(iter)) {
1926
0
            seen.insert(iter);
1927
0
            t.push_back(iter);
1928
0
        }
1929
0
    }
1930
0
    return t;
1931
0
}
1932
1933
#ifndef QPDF_NO_WCHAR_T
1934
static int
1935
call_main_from_wmain(
1936
    bool, int argc, wchar_t const* const argv[], std::function<int(int, char*[])> realmain)
1937
0
{
1938
    // argv contains UTF-16-encoded strings with a 16-bit wchar_t. Convert this to UTF-8-encoded
1939
    // strings for compatibility with other systems. That way the rest of qpdf.cc can just act like
1940
    // arguments are UTF-8.
1941
1942
0
    std::vector<std::string> utf8_argv;
1943
0
    utf8_argv.reserve(QIntC::to_size(argc));
1944
0
    for (int i = 0; i < argc; ++i) {
1945
0
        std::string utf16;
1946
0
        for (size_t j = 0; j < std::wcslen(argv[i]); ++j) {
1947
0
            unsigned short codepoint = static_cast<unsigned short>(argv[i][j]);
1948
0
            utf16.append(1, static_cast<char>(QIntC::to_uchar(codepoint >> 8)));
1949
0
            utf16.append(1, static_cast<char>(QIntC::to_uchar(codepoint & 0xff)));
1950
0
        }
1951
0
        utf8_argv.emplace_back(QUtil::utf16_to_utf8(utf16));
1952
0
    }
1953
0
    std::vector<char*> new_argv;
1954
0
    new_argv.reserve(utf8_argv.size() + 1U);
1955
0
    for (auto const& arg: utf8_argv) {
1956
0
        new_argv.emplace_back(const_cast<char*>(arg.data()));
1957
0
    }
1958
0
    argc = QIntC::to_int(utf8_argv.size());
1959
0
    new_argv.emplace_back(nullptr);
1960
0
    return realmain(argc, new_argv.data());
1961
0
}
1962
1963
int
1964
QUtil::call_main_from_wmain(int argc, wchar_t* argv[], std::function<int(int, char*[])> realmain)
1965
0
{
1966
0
    return ::call_main_from_wmain(true, argc, argv, realmain);
1967
0
}
1968
1969
int
1970
QUtil::call_main_from_wmain(
1971
    int argc, wchar_t const* const argv[], std::function<int(int, char const* const[])> realmain)
1972
0
{
1973
0
    return ::call_main_from_wmain(true, argc, argv, [realmain](int new_argc, char* new_argv[]) {
1974
0
        return realmain(new_argc, new_argv);
1975
0
    });
1976
0
}
1977
1978
#endif // QPDF_NO_WCHAR_T
1979
1980
size_t
1981
QUtil::get_max_memory_usage()
1982
0
{
1983
0
#if defined(HAVE_MALLOC_INFO) && defined(HAVE_OPEN_MEMSTREAM)
1984
0
    static std::regex tag_re("<(/?\\w+)([^>]*?)>");
1985
0
    static std::regex attr_re("(\\w+)=\"(.*?)\"");
1986
1987
0
    char* buf;
1988
0
    size_t size;
1989
0
    FILE* f = open_memstream(&buf, &size);
1990
0
    if (f == nullptr) {
1991
0
        return 0;
1992
0
    }
1993
0
    malloc_info(0, f);
1994
0
    fclose(f);
1995
0
    if (QUtil::get_env("QPDF_DEBUG_MEM_USAGE")) {
1996
0
        fprintf(stderr, "%s", buf);
1997
0
    }
1998
1999
    // Warning: this code uses regular expression to extract data from an XML string. This is
2000
    // generally a bad idea, but we're going to do it anyway because QUtil.hh warns against using
2001
    // this function for other than development/testing, and if this function fails to generate
2002
    // reasonable output during performance testing, it will be noticed.
2003
2004
    // This is my best guess at how to interpret malloc_info. Anyway it seems to provide useful
2005
    // information for detecting code changes that drastically change memory usage.
2006
0
    size_t result = 0;
2007
0
    try {
2008
0
        std::cregex_iterator m_begin(buf, buf + size, tag_re);
2009
0
        std::cregex_iterator cr_end;
2010
0
        std::sregex_iterator sr_end;
2011
2012
0
        int in_heap = 0;
2013
0
        for (auto m = m_begin; m != cr_end; ++m) {
2014
0
            std::string tag(m->str(1));
2015
0
            if (tag == "heap") {
2016
0
                ++in_heap;
2017
0
            } else if (tag == "/heap") {
2018
0
                --in_heap;
2019
0
            } else if (in_heap == 0) {
2020
0
                std::string rest = m->str(2);
2021
0
                std::map<std::string, std::string> attrs;
2022
0
                std::sregex_iterator a_begin(rest.begin(), rest.end(), attr_re);
2023
0
                for (auto m2 = a_begin; m2 != sr_end; ++m2) {
2024
0
                    attrs[m2->str(1)] = m2->str(2);
2025
0
                }
2026
0
                if (tag == "total") {
2027
0
                    if (attrs.contains("size")) {
2028
0
                        result += QIntC::to_size(QUtil::string_to_ull(attrs["size"].c_str()));
2029
0
                    }
2030
0
                } else if (tag == "system" && attrs["type"] == "max") {
2031
0
                    result += QIntC::to_size(QUtil::string_to_ull(attrs["size"].c_str()));
2032
0
                }
2033
0
            }
2034
0
        }
2035
0
    } catch (...) {
2036
        // ignore -- just return 0
2037
0
    }
2038
0
    free(buf);
2039
0
    return result;
2040
#else
2041
    return 0;
2042
#endif
2043
0
}
2044
2045
char
2046
QUtil::hex_decode_char(char digit)
2047
0
{
2048
0
    return util::hex_decode_char(digit);
2049
0
}
2050
2051
std::string
2052
QUtil::hex_encode_char(char c)
2053
0
{
2054
0
    return util::hex_encode_char(c);
2055
0
}
2056
2057
bool
2058
QUtil::is_number(char const* p)
2059
0
{
2060
    // No longer used by qpdf.
2061
2062
    // ^[\+\-]?(\.\d*|\d+(\.\d*)?)$
2063
0
    if (!*p) {
2064
0
        return false;
2065
0
    }
2066
0
    if ((*p == '-') || (*p == '+')) {
2067
0
        ++p;
2068
0
    }
2069
0
    bool found_dot = false;
2070
0
    bool found_digit = false;
2071
0
    for (; *p; ++p) {
2072
0
        if (*p == '.') {
2073
0
            if (found_dot) {
2074
                // only one dot
2075
0
                return false;
2076
0
            }
2077
0
            found_dot = true;
2078
0
        } else if (util::is_digit(*p)) {
2079
0
            found_digit = true;
2080
0
        } else {
2081
0
            return false;
2082
0
        }
2083
0
    }
2084
0
    return found_digit;
2085
0
}
2086
2087
bool
2088
QUtil::is_space(char c)
2089
0
{
2090
0
    return util::is_space(c);
2091
0
}
2092
2093
bool
2094
QUtil::is_digit(char c)
2095
0
{
2096
0
    return util::is_digit(c);
2097
0
}
2098
2099
bool
2100
QUtil::is_hex_digit(char c)
2101
0
{
2102
0
    return util::is_hex_digit(c);
2103
0
}
2104
2105
void
2106
QUtil::handle_result_code(qpdf_result_e result, std::string_view context)
2107
0
{
2108
0
    if (result == qpdf_r_ok) {
2109
0
        return;
2110
0
    }
2111
0
    qpdf::util::assertion(
2112
0
        result == qpdf_r_bad_parameter,
2113
0
        "unexpected result code received from function in "s.append(context));
2114
0
    throw std::logic_error("invalid parameter supplied to function in "s.append(context));
2115
0
}