Coverage Report

Created: 2025-08-29 06:57

/src/qpdf/include/qpdf/QUtil.hh
Line
Count
Source (jump to first uncovered line)
1
// Copyright (c) 2005-2021 Jay Berkenbilt
2
// Copyright (c) 2022-2025 Jay Berkenbilt and Manfred Holger
3
//
4
// This file is part of qpdf.
5
//
6
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
7
// in compliance with the License. You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing, software distributed under the License
12
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
13
// or implied. See the License for the specific language governing permissions and limitations under
14
// the License.
15
//
16
// Versions of qpdf prior to version 7 were released under the terms of version 2.0 of the Artistic
17
// License. At your option, you may continue to consider qpdf to be licensed under those terms.
18
// Please see the manual for additional information.
19
20
#ifndef QUTIL_HH
21
#define QUTIL_HH
22
23
#include <qpdf/DLL.h>
24
#include <qpdf/Types.h>
25
#include <cstdio>
26
#include <cstring>
27
#include <ctime>
28
#include <functional>
29
#include <list>
30
#include <memory>
31
#include <stdexcept>
32
#include <string>
33
#include <vector>
34
35
class RandomDataProvider;
36
class Pipeline;
37
38
namespace QUtil
39
{
40
    // This is a collection of useful utility functions that don't really go anywhere else.
41
    QPDF_DLL
42
    std::string int_to_string(long long, int length = 0);
43
    QPDF_DLL
44
    std::string uint_to_string(unsigned long long, int length = 0);
45
    QPDF_DLL
46
    std::string int_to_string_base(long long, int base, int length = 0);
47
    QPDF_DLL
48
    std::string uint_to_string_base(unsigned long long, int base, int length = 0);
49
    QPDF_DLL
50
    std::string double_to_string(double, int decimal_places = 0, bool trim_trailing_zeroes = true);
51
52
    // These string to number methods throw std::runtime_error on underflow/overflow.
53
    QPDF_DLL
54
    long long string_to_ll(char const* str);
55
    QPDF_DLL
56
    int string_to_int(char const* str);
57
    QPDF_DLL
58
    unsigned long long string_to_ull(char const* str);
59
    QPDF_DLL
60
    unsigned int string_to_uint(char const* str);
61
62
    // Returns true if this exactly represents a long long. The determination is made by converting
63
    // the string to a long long, then converting the result back to a string, and then comparing
64
    // that result with the original string.
65
    QPDF_DLL
66
    bool is_long_long(char const* str);
67
68
    // Pipeline's write method wants unsigned char*, but we often have some other type of string.
69
    // These methods do combinations of const_cast and reinterpret_cast to give us an unsigned
70
    // char*. They should only be used when it is known that it is safe. None of the pipelines in
71
    // qpdf modify the data passed to them, so within qpdf, it should always be safe.
72
    QPDF_DLL
73
    unsigned char* unsigned_char_pointer(std::string const& str);
74
    QPDF_DLL
75
    unsigned char* unsigned_char_pointer(char const* str);
76
77
    // Throw QPDFSystemError, which is derived from std::runtime_error, with a string formed by
78
    // appending to "description: " the standard string corresponding to the current value of errno.
79
    // You can retrieve the value of errno by calling getErrno() on the QPDFSystemError. Prior to
80
    // qpdf 8.2.0, this method threw system::runtime_error directly, but since QPDFSystemError is
81
    // derived from system::runtime_error, old code that specifically catches std::runtime_error
82
    // will still work.
83
    QPDF_DLL
84
    void throw_system_error(std::string const& description);
85
86
    // The status argument is assumed to be the return value of a standard library call that sets
87
    // errno when it fails.  If status is -1, convert the current value of errno to a
88
    // std::runtime_error that includes the standard error string. Otherwise, return status.
89
    QPDF_DLL
90
    int os_wrapper(std::string const& description, int status);
91
92
    // If the open fails, throws std::runtime_error. Otherwise, the FILE* is returned. The filename
93
    // should be UTF-8 encoded, even on Windows. It will be converted as needed on Windows.
94
    QPDF_DLL
95
    FILE* safe_fopen(char const* filename, char const* mode);
96
97
    // The FILE* argument is assumed to be the return of fopen. If null, throw std::runtime_error.
98
    // Otherwise, return the FILE* argument.
99
    QPDF_DLL
100
    FILE* fopen_wrapper(std::string const&, FILE*);
101
102
    // This is a little class to help with automatic closing files. You can do something like
103
    //
104
    // QUtil::FileCloser fc(QUtil::safe_fopen(filename, "rb"));
105
    //
106
    // and then use fc.f to the file. Be sure to actually declare a variable of type FileCloser.
107
    // Using it as a temporary won't work because it will close the file as soon as it goes out of
108
    // scope.
109
    class FileCloser
110
    {
111
      public:
112
        FileCloser(FILE* f) :
113
1
            f(f)
114
1
        {
115
1
        }
116
117
        ~FileCloser()
118
1
        {
119
1
            if (f) {
120
1
                fclose(f);
121
1
                f = nullptr;
122
1
            }
123
1
        }
124
125
        FILE* f;
126
    };
127
128
    // Attempt to open the file read only and then close again
129
    QPDF_DLL
130
    bool file_can_be_opened(char const* filename);
131
132
    // Wrap around off_t versions of fseek and ftell if available
133
    QPDF_DLL
134
    int seek(FILE* stream, qpdf_offset_t offset, int whence);
135
    QPDF_DLL
136
    qpdf_offset_t tell(FILE* stream);
137
138
    QPDF_DLL
139
    bool same_file(char const* name1, char const* name2);
140
141
    QPDF_DLL
142
    void remove_file(char const* path);
143
144
    // rename_file will overwrite newname if it exists
145
    QPDF_DLL
146
    void rename_file(char const* oldname, char const* newname);
147
148
    // Write the contents of filename as a binary file to the pipeline.
149
    QPDF_DLL
150
    void pipe_file(char const* filename, Pipeline* p);
151
152
    // Return a function that will send the contents of the given file through the given pipeline as
153
    // binary data.
154
    QPDF_DLL
155
    std::function<void(Pipeline*)> file_provider(std::string const& filename);
156
157
    // Return the last path element. On Windows, either / or \ are path separators. Otherwise, only
158
    // / is a path separator. Strip any trailing path separators. Then, if any path separators
159
    // remain, return everything after the last path separator. Otherwise, return the whole string.
160
    // As a special case, if a string consists entirely of path separators, the first character is
161
    // returned.
162
    QPDF_DLL
163
    std::string path_basename(std::string const& filename);
164
165
    // Returns a dynamically allocated copy of a string that the caller has to delete with delete[].
166
    QPDF_DLL
167
    char* copy_string(std::string const&);
168
169
    // Returns a shared_ptr<char> with the correct deleter.
170
    QPDF_DLL
171
    std::shared_ptr<char> make_shared_cstr(std::string const&);
172
173
    // Copy string as a unique_ptr to an array.
174
    QPDF_DLL
175
    std::unique_ptr<char[]> make_unique_cstr(std::string const&);
176
177
    // Create a shared pointer to an array. From c++20, std::make_shared<T[]>(n) does this.
178
    template <typename T>
179
    std::shared_ptr<T>
180
    make_shared_array(size_t n)
181
78.4k
    {
182
78.4k
        return std::shared_ptr<T>(new T[n], std::default_delete<T[]>());
183
78.4k
    }
std::__1::shared_ptr<unsigned char> QUtil::make_shared_array<unsigned char>(unsigned long)
Line
Count
Source
181
78.4k
    {
182
78.4k
        return std::shared_ptr<T>(new T[n], std::default_delete<T[]>());
183
78.4k
    }
Unexecuted instantiation: std::__1::shared_ptr<char> QUtil::make_shared_array<char>(unsigned long)
184
185
    // Returns lower-case hex-encoded version of the string, treating each character in the input
186
    // string as unsigned.  The output string will be twice as long as the input string.
187
    QPDF_DLL
188
    std::string hex_encode(std::string const&);
189
190
    // Returns lower-case hex-encoded version of the char including a leading "#".
191
    QPDF_DLL
192
    std::string hex_encode_char(char);
193
194
    // Returns a string that is the result of decoding the input string. The input string may
195
    // consist of mixed case hexadecimal digits. Any characters that are not hexadecimal digits will
196
    // be silently ignored. If there are an odd number of hexadecimal digits, a trailing 0 will be
197
    // assumed.
198
    QPDF_DLL
199
    std::string hex_decode(std::string const&);
200
201
    // Decode a single hex digit into a char in the range 0 <= char < 16. Return a char >= 16 if
202
    // digit is not a valid hex digit.
203
    QPDF_DLL
204
    char hex_decode_char(char digit);
205
206
    // Set stdin, stdout to binary mode
207
    QPDF_DLL
208
    void binary_stdout();
209
    QPDF_DLL
210
    void binary_stdin();
211
    // Set stdout to line buffered
212
    QPDF_DLL
213
    void setLineBuf(FILE*);
214
215
    // May modify argv0
216
    QPDF_DLL
217
    char* getWhoami(char* argv0);
218
219
    // Get the value of an environment variable in a portable fashion. Returns true iff the variable
220
    // is defined.  If `value' is non-null, initializes it with the value of the variable.
221
    QPDF_DLL
222
    bool get_env(std::string const& var, std::string* value = nullptr);
223
224
    QPDF_DLL
225
    time_t get_current_time();
226
227
    // Portable structure representing a point in time with second granularity and time zone offset.
228
    struct QPDFTime
229
    {
230
        QPDFTime() = default;
231
        QPDFTime(QPDFTime const&) = default;
232
        QPDFTime& operator=(QPDFTime const&) = default;
233
        QPDFTime(int year, int month, int day, int hour, int minute, int second, int tz_delta) :
234
0
            year(year),
235
0
            month(month),
236
0
            day(day),
237
0
            hour(hour),
238
0
            minute(minute),
239
0
            second(second),
240
0
            tz_delta(tz_delta)
241
0
        {
242
0
        }
243
        int year;  // actual year, no 1900 stuff
244
        int month; // 1--12
245
        int day;   // 1--31
246
        int hour;
247
        int minute;
248
        int second;
249
        int tz_delta; // minutes before UTC
250
    };
251
252
    QPDF_DLL
253
    QPDFTime get_current_qpdf_time();
254
255
    // Convert a QPDFTime structure to a PDF timestamp string, which is "D:yyyymmddhhmmss<z>" where
256
    // <z> is either "Z" for UTC or "-hh'mm'" or "+hh'mm'" for timezone offset. <z> may also be
257
    // omitted.
258
    // Examples: "D:20210207161528-05'00'", "D:20210207211528Z", "D:20210207211528".
259
    // See get_current_qpdf_time and the QPDFTime structure above.
260
    QPDF_DLL
261
    std::string qpdf_time_to_pdf_time(QPDFTime const&);
262
263
    // Convert QPDFTime to a second-granularity ISO-8601 timestamp.
264
    QPDF_DLL
265
    std::string qpdf_time_to_iso8601(QPDFTime const&);
266
267
    // Convert a PDF timestamp string to a QPDFTime. If syntactically valid, return true and fill in
268
    // qtm. If not valid, return false, and do not modify qtm. If qtm is null, just check the
269
    // validity of the string.
270
    QPDF_DLL
271
    bool pdf_time_to_qpdf_time(std::string const&, QPDFTime* qtm = nullptr);
272
273
    // Convert PDF timestamp to a second-granularity ISO-8601 timestamp. If syntactically valid,
274
    // return true and initialize iso8601. Otherwise, return false.
275
    bool pdf_time_to_iso8601(std::string const& pdf_time, std::string& iso8601);
276
277
    // Return a string containing the byte representation of the UTF-8 encoding for the unicode
278
    // value passed in.
279
    QPDF_DLL
280
    std::string toUTF8(unsigned long uval);
281
282
    // Return a string containing the byte representation of the UTF-16 big-endian encoding for the
283
    // unicode value passed in. Unrepresentable code points are converted to U+FFFD.
284
    QPDF_DLL
285
    std::string toUTF16(unsigned long uval);
286
287
    // If utf8_val.at(pos) points to the beginning of a valid UTF-8-encoded character, return the
288
    // codepoint of the character and set error to false. Otherwise, return 0xfffd and set error to
289
    // true. In all cases, pos is advanced to the next position that may begin a valid character.
290
    // When the string has been consumed, pos will be set to the string length. It is an error to
291
    // pass a value of pos that is greater than or equal to the length of the string.
292
    QPDF_DLL
293
    unsigned long get_next_utf8_codepoint(std::string const& utf8_val, size_t& pos, bool& error);
294
295
    // Test whether this is a UTF-16 string. This is indicated by first two bytes being 0xFE 0xFF
296
    // (big-endian) or 0xFF 0xFE (little-endian), each of which is the encoding of U+FEFF, the
297
    // Unicode marker. Starting in qpdf 10.6.2, this detects little-endian as well as big-endian.
298
    // Even though the PDF spec doesn't allow little-endian, most readers seem to accept it.
299
    QPDF_DLL
300
    bool is_utf16(std::string const&);
301
302
    // Test whether this is an explicit UTF-8 string as allowed by the PDF 2.0 spec. This is
303
    // indicated by first three bytes being 0xEF 0xBB 0xBF, which is the UTF-8 encoding of U+FEFF.
304
    QPDF_DLL
305
    bool is_explicit_utf8(std::string const&);
306
307
    // Convert a UTF-8 encoded string to UTF-16 big-endian. Unrepresentable code points are
308
    // converted to U+FFFD.
309
    QPDF_DLL
310
    std::string utf8_to_utf16(std::string const& utf8);
311
312
    // Convert a UTF-8 encoded string to the specified single-byte encoding system by replacing all
313
    // unsupported characters with the given unknown_char.
314
    QPDF_DLL
315
    std::string utf8_to_ascii(std::string const& utf8, char unknown_char = '?');
316
    QPDF_DLL
317
    std::string utf8_to_win_ansi(std::string const& utf8, char unknown_char = '?');
318
    QPDF_DLL
319
    std::string utf8_to_mac_roman(std::string const& utf8, char unknown_char = '?');
320
    QPDF_DLL
321
    std::string utf8_to_pdf_doc(std::string const& utf8, char unknown_char = '?');
322
323
    // These versions return true if the conversion was successful and false if any unrepresentable
324
    // characters were found and had to be substituted with the unknown character.
325
    QPDF_DLL
326
    bool utf8_to_ascii(std::string const& utf8, std::string& ascii, char unknown_char = '?');
327
    QPDF_DLL
328
    bool utf8_to_win_ansi(std::string const& utf8, std::string& win, char unknown_char = '?');
329
    QPDF_DLL
330
    bool utf8_to_mac_roman(std::string const& utf8, std::string& mac, char unknown_char = '?');
331
    QPDF_DLL
332
    bool utf8_to_pdf_doc(std::string const& utf8, std::string& pdfdoc, char unknown_char = '?');
333
334
    // Convert a UTF-16 encoded string to UTF-8. Unrepresentable code
335
    // points are converted to U+FFFD.
336
    QPDF_DLL
337
    std::string utf16_to_utf8(std::string const& utf16);
338
339
    // Convert from the specified single-byte encoding system to UTF-8. There is no ascii_to_utf8
340
    // because all ASCII strings are already valid UTF-8.
341
    QPDF_DLL
342
    std::string win_ansi_to_utf8(std::string const& win);
343
    QPDF_DLL
344
    std::string mac_roman_to_utf8(std::string const& mac);
345
    QPDF_DLL
346
    std::string pdf_doc_to_utf8(std::string const& pdfdoc);
347
348
    // Analyze a string for encoding. We can't tell the difference between any single-byte
349
    // encodings, and we can't tell for sure whether a string that happens to be valid UTF-8 isn't a
350
    // different encoding, but we can at least tell a few things to help us guess. If there are no
351
    // characters with the high bit set, has_8bit_chars is false, and the other values are also
352
    // false, even though ASCII strings are valid UTF-8. is_valid_utf8 means that the string is
353
    // non-trivially valid UTF-8. Although the PDF spec requires UTF-16 to be UTF-16BE, qpdf (and
354
    // just about everything else) accepts UTF-16LE (as of 10.6.2).
355
    QPDF_DLL
356
    void analyze_encoding(
357
        std::string const& str, bool& has_8bit_chars, bool& is_valid_utf8, bool& is_utf16);
358
359
    // Try to compensate for previously incorrectly encoded strings. We want to compensate for the
360
    // following errors:
361
    //
362
    // * The string was supposed to be UTF-8 but was one of the single-byte encodings
363
    // * The string was supposed to be PDF Doc but was either UTF-8 or one of the other single-byte
364
    //   encodings
365
    //
366
    // The returned vector always contains the original string first, and then it contains what the
367
    // correct string would be in the event that the original string was the result of any of the
368
    // above errors.
369
    //
370
    // This method is useful for attempting to recover a password that may have been previously
371
    // incorrectly encoded. For example, the password was supposed to be UTF-8 but the previous
372
    // application used a password encoded in WinAnsi, or if the previous password was supposed to
373
    // be PDFDoc but was actually given as UTF-8 or WinAnsi, this method would find the correct
374
    // password.
375
    QPDF_DLL
376
    std::vector<std::string> possible_repaired_encodings(std::string);
377
378
    // Return a cryptographically secure random number.
379
    QPDF_DLL
380
    long random();
381
382
    // Initialize a buffer with cryptographically secure random bytes.
383
    QPDF_DLL
384
    void initializeWithRandomBytes(unsigned char* data, size_t len);
385
386
    // Supply a random data provider. Starting in qpdf 10.0.0, qpdf uses the crypto provider as its
387
    // source of random numbers. If you are using the native crypto provider, then qpdf will either
388
    // use the operating system's secure random number source or, only if enabled at build time, an
389
    // insecure random source from stdlib. The caller is responsible for managing the memory for the
390
    // RandomDataProvider. This method modifies a static variable. If you are providing your own
391
    // random data provider, you should call this at the beginning of your program before creating
392
    // any QPDF objects. Passing a null to this method will reset the library back to its default
393
    // random data provider.
394
    QPDF_DLL
395
    void setRandomDataProvider(RandomDataProvider*);
396
397
    // This returns the random data provider that would be used the next time qpdf needs random
398
    // data.  It will never return null. If no random data provider has been provided and the
399
    // library was not compiled with any random data provider available, an exception will be
400
    // thrown.
401
    QPDF_DLL
402
    RandomDataProvider* getRandomDataProvider();
403
404
    // Filename is UTF-8 encoded, even on Windows, as described in the comments for safe_fopen.
405
    QPDF_DLL
406
    std::list<std::string> read_lines_from_file(char const* filename, bool preserve_eol = false);
407
    QPDF_DLL
408
    std::list<std::string> read_lines_from_file(std::istream&, bool preserve_eol = false);
409
    QPDF_DLL
410
    std::list<std::string> read_lines_from_file(FILE*, bool preserve_eol = false);
411
    QPDF_DLL
412
    void read_lines_from_file(
413
        std::function<bool(char&)> next_char,
414
        std::list<std::string>& lines,
415
        bool preserve_eol = false);
416
417
    QPDF_DLL
418
    void read_file_into_memory(char const* filename, std::shared_ptr<char>& file_buf, size_t& size);
419
420
    QPDF_DLL
421
    std::string read_file_into_string(char const* filename);
422
    QPDF_DLL
423
    std::string read_file_into_string(FILE* f, std::string_view filename = "");
424
425
    // This used to be called strcasecmp, but that is a macro on some platforms, so we have to give
426
    // it a name that is not likely to be a macro anywhere.
427
    QPDF_DLL
428
    int str_compare_nocase(char const*, char const*);
429
430
    // These routines help the tokenizer recognize certain character classes without using ctype,
431
    // which we avoid because of locale considerations.
432
    QPDF_DLL
433
    bool is_hex_digit(char);
434
435
    QPDF_DLL
436
    bool is_space(char);
437
438
    QPDF_DLL
439
    bool is_digit(char);
440
441
    QPDF_DLL
442
    bool is_number(char const*);
443
444
    // This method parses the numeric range syntax used by the qpdf command-line tool. May throw
445
    // std::runtime_error. A numeric range is as comma-separated list of groups. A group may be a
446
    // number specification or a range of number specifications separated by a dash. A number
447
    // specification may be one of the following (where <n> is a number):
448
    // * <n> -- the numeric value of n
449
    // * z -- the value of the `max` parameter
450
    // * r<n> -- represents max + 1 - <n> (<n> from the end)
451
    //
452
    // If the group is two number specifications separated by a dash, it represents the range of
453
    // numbers from the first to the second, inclusive. If the first is greater than the second, the
454
    // numbers are descending.
455
    //
456
    // From qpdf 11.7.1: if a group starts with `x`, its members are excluded from the previous
457
    // group that didn't start with `x1.
458
    //
459
    // Example: with max of 15, the range "4-10,x7-9,12-8,xr5" is 4, 5, 6, 10, 12, 10, 9, 8. This is
460
    // 4 through 10 inclusive without 7 through 9 inclusive followed by 12 to 8 inclusive
461
    // (descending) without 11 (the fifth value counting backwards from 15). For more information
462
    // and additional examples, see the "Page Ranges" section in the manual.
463
    QPDF_DLL
464
    std::vector<int> parse_numrange(char const* range, int max);
465
466
#ifndef QPDF_NO_WCHAR_T
467
    // If you are building qpdf on a stripped down system that doesn't have wchar_t, such as may be
468
    // the case in some embedded environments, you may define QPDF_NO_WCHAR_T in your build. This
469
    // symbol is never defined automatically. Search for wchar_t in qpdf's top-level README.md file
470
    // for details.
471
472
    // Take an argv array consisting of wchar_t, as when wmain is invoked, convert all UTF-16
473
    // encoded strings to UTF-8, and call another main.
474
    QPDF_DLL
475
    int call_main_from_wmain(int argc, wchar_t* argv[], std::function<int(int, char*[])> realmain);
476
    QPDF_DLL
477
    int call_main_from_wmain(
478
        int argc,
479
        wchar_t const* const argv[],
480
        std::function<int(int, char const* const[])> realmain);
481
#endif // QPDF_NO_WCHAR_T
482
483
    // Try to return the maximum amount of memory allocated by the current process and its threads.
484
    // Return 0 if unable to determine. This is Linux-specific and not implemented to be completely
485
    // reliable. It is used during development for performance testing to detect changes that may
486
    // significantly change memory usage. It is not recommended for use for other purposes.
487
    QPDF_DLL
488
    size_t get_max_memory_usage();
489
}; // namespace QUtil
490
491
#endif // QUTIL_HH