Commit 52e41f256f62827aa3cfd9cb547be5574811539a

Authored by m-holger
Committed by GitHub
2 parents 8f29397d d43382c4

Merge pull request #1602 from m-holger/cli

Introduce parameter validation for compression-level and jpeg-quality
libqpdf/QPDFJob_config.cc
1 1 #include <qpdf/QPDFJob_private.hh>
2 2  
3   -#include <regex>
4   -
5 3 #include <qpdf/QPDFLogger.hh>
  4 +#include <qpdf/QPDFUsage.hh>
6 5 #include <qpdf/QTC.hh>
7 6 #include <qpdf/QUtil.hh>
8 7  
  8 +#include <concepts>
  9 +#include <regex>
  10 +
  11 +static void
  12 +int_usage(std::string_view option, std::integral auto min, std::integral auto max)
  13 +{
  14 + throw QPDFUsage(
  15 + "invalid "s.append(option) + ": must be a number between " + std::to_string(min) + " and " +
  16 + std::to_string(max));
  17 +}
  18 +
  19 +static int
  20 +to_int(std::string_view option, std::string const& value, int min, int max)
  21 +{
  22 + int result = 0;
  23 + try {
  24 + result = std::stoi(value);
  25 + if (result < min || result > max) {
  26 + int_usage(option, min, max);
  27 + }
  28 + } catch (std::exception&) {
  29 + int_usage(option, min, max);
  30 + }
  31 + return result;
  32 +}
  33 +
9 34 void
10 35 QPDFJob::Config::checkConfiguration()
11 36 {
... ... @@ -131,14 +156,14 @@ QPDFJob::Config::compressStreams(std::string const&amp; parameter)
131 156 QPDFJob::Config*
132 157 QPDFJob::Config::compressionLevel(std::string const& parameter)
133 158 {
134   - o.m->compression_level = QUtil::string_to_int(parameter.c_str());
  159 + o.m->compression_level = to_int("compression-level", parameter, 1, 9);
135 160 return this;
136 161 }
137 162  
138 163 QPDFJob::Config*
139 164 QPDFJob::Config::jpegQuality(std::string const& parameter)
140 165 {
141   - o.m->jpeg_quality = QUtil::string_to_int(parameter.c_str());
  166 + o.m->jpeg_quality = to_int("jpeg-quality", parameter, 0, 100);
142 167 return this;
143 168 }
144 169  
... ...
qpdf/qtest/arg-parsing.test
... ... @@ -15,7 +15,7 @@ cleanup();
15 15  
16 16 my $td = new TestDriver('arg-parsing');
17 17  
18   -my $n_tests = 30;
  18 +my $n_tests = 32;
19 19  
20 20 $td->runtest("required argument",
21 21 {$td->COMMAND => "qpdf --password minimal.pdf"},
... ... @@ -175,5 +175,17 @@ foreach my $arg (@bad_enc)
175 175 $td->NORMALIZE_NEWLINES);
176 176 }
177 177  
  178 +$td->runtest("bad compression-level",
  179 + {$td->COMMAND => "qpdf --compression-level=false minimal.pdf"},
  180 + {$td->REGEXP => "invalid compression-level: must be a number between 1 and 9",
  181 + $td->EXIT_STATUS => 2},
  182 + $td->NORMALIZE_NEWLINES);
  183 +
  184 +$td->runtest("bad jpeg-quality",
  185 + {$td->COMMAND => "qpdf --jpeg-quality=101 minimal.pdf"},
  186 + {$td->REGEXP => "invalid jpeg-quality: must be a number between 0 and 100",
  187 + $td->EXIT_STATUS => 2},
  188 + $td->NORMALIZE_NEWLINES);
  189 +
178 190 cleanup();
179 191 $td->report($n_tests);
... ...