blib/lib/CGI/Info.pm

filter: Statementstmt 95.7% 1157 / 1208 Branchbran 87.4% 621 / 710 Conditioncond 70.6% 341 / 483 MC/DCmcdc 49.2% 124 / 252 Subroutinesub 100% 113 / 113 Podpod 100% 30 / 30 totaltotal 85.3% 2386 / 2796 CC 529 SCAR 40.1
CC
529
Cov
88%
params
184.8
is_search_engine
66.0
is_robot
31.7
CRAP 55.3
↑ Summary bin/info.pl »
1 package CGI::Info;
2  
3 38 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 38 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 38 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 38 ▶use 5.010; # Minimum version for features used here
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 # Core modules
10 38 ▶use boolean;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 38 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 38 ▶use Cwd ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 38 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 38 ▶use Scalar::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 38 ▶use Socket; # AF_INET constant
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 # CPAN modules
18 38 ▶use Object::Configure 0.19;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 38 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 38 ▶use Log::Abstraction 0.10;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 38 ▶use Net::CIDR;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 38 ▶use Params::Get 0.13;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 38 ▶use Params::Validate::Strict 0.35;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 38 ▶use Return::Set;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 38 ▶use Sys::Path;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 38 ▶use Sub::Protected;
Subroutine BEGIN: called CC=1 SCAR=0.0
27  
28 38 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
29  
30 # ---------------------------------------------------------------------------
31 # Module-level constants -- avoids magic numbers scattered through the code
32 # ---------------------------------------------------------------------------
33 38 Readonly my $MAX_UPLOAD_SIZE_DEFAULT => 512 * 1024; # 512 KB default upload cap
34 38 Readonly my $MAX_PARAMS_DEFAULT => 1000; # Maximum number of input parameters
35 38 Readonly my $MAX_PARTS_DEFAULT => 100; # Maximum number of multipart parts
36 38 Readonly my $MAX_PART_HEADERS_DEFAULT => 20; # Maximum header lines per multipart part
37 38 Readonly my $MAX_NESTING_DEPTH_DEFAULT => 8; # Maximum [] nesting in parameter names
38 38 Readonly my $DTD_WARNING_INTERVAL_DEFAULT => 60; # Seconds between allow_dtd audit warnings
39 38 Readonly my $DTD_WARNING_MAX_KEYS => 100; # Request paths tracked by that limiter
40 38 Readonly my @COMPLEXITY_LIMITS => qw(max_body_size max_params max_parts max_part_headers max_nesting_depth);
41 38 Readonly my $CACHE_TTL_ROBOT => '1 day'; # TTL for robot-detection cache entries
42 38 Readonly my $CACHE_TTL_SEARCH => '1 day'; # TTL for search-engine cache entries
43  
44 # Compiled once at module-load time: replaces the 29-element @crawler_lists array
45 # that was re-allocated on every is_robot() call. Building the alternation with
46 # quotemeta() is equivalent to the former List::Util::any { /^\Q$_\E/i } loop
47 # but avoids both per-call array construction and per-element regex compilation.
48 38 Readonly my $CRAWLER_REFERER_RE => do {
49 38 my @domains = (
50 'http://fix-website-errors.com',
51 'http://keywords-monitoring-your-success.com',
52 'http://free-video-tool.com',
53 'http://magnet-to-torrent.com',
54 'http://torrent-to-magnet.com',
55 'http://dogsrun.net',
56 'http://###.responsive-test.net',
57 'http://uptime.com',
58 'http://uptimechecker.com',
59 'http://top1-seo-service.com',
60 'http://fast-wordpress-start.com',
61 'http://wordpress-crew.net',
62 'http://dbutton.net',
63 'http://justprofit.xyz',
64 'http://video--production.com',
65 'http://buttons-for-website.com',
66 'http://buttons-for-your-website.com',
67 'http://success-seo.com',
68 'http://videos-for-your-business.com',
69 'http://semaltmedia.com',
70 'http://dailyrank.net',
71 'http://uptimebot.net',
72 'http://sitevaluation.org',
73 'http://100dollars-seo.com',
74 'http://forum69.info',
75 'http://partner.semalt.com',
76 'http://best-seo-offer.com',
77 'http://best-seo-solution.com',
78 'http://semalt.semalt.com',
79 'http://semalt.com',
80 'http://7makemoneyonline.com',
81 'http://anticrawler.org',
82 'http://baixar-musicas-gratis.com',
83 'http://descargar-musica-gratis.net',
84 'http://www.seokicks.de/robot.html',
85 );
86 38 my $alt = join '|', map { quotemeta $_ } @domains;
87 38 qr/^(?:$alt)/i;
88 };
89  
90 sub _sanitise_input;
91  
92 =head1 NAME
93  
94 CGI::Info - Information about the CGI environment
95  
96 =head1 VERSION
97  
98 Version 1.16
99  
100 =cut
101  
102 38 our $VERSION = '1.16';
103  
104 =head1 SYNOPSIS
105  
106 The C<CGI::Info> module is a Perl library designed to provide information about the environment in which a CGI script operates.
107 It aims to eliminate hard-coded script details,
108 enhancing code readability and portability.
109 Additionally, it offers a simple web application firewall to add a layer of security.
110  
111 All too often,
112 Perl programs have information such as the script's name
113 hard-coded into their source.
114 Generally speaking,
115 hard-coding is a bad style since it can make programs difficult to read and reduces readability and portability.
116 CGI::Info attempts to remove that.
117  
118 Furthermore, to aid script debugging, CGI::Info attempts to do sensible
119 things when you're not running the program in a CGI environment.
120  
121 Whilst you shouldn't rely on it alone to provide security to your website,
122 it is another layer and every little helps.
123  
124 use CGI::Info;
125  
126 my $info = CGI::Info->new(allow => { id => qr/^\d+$/ });
127 my $params = $info->params();
128  
129 if($info->is_mobile()) {
130 print "Mobile view\n";
131 } else {
132 print "Desktop view\n";
133 }
134  
135 my $id = $info->param('id'); # Validated against allow schema
136  
137 =head1 SUBROUTINES/METHODS
138  
139 =head2 new
140  
141 Creates a CGI::Info object.
142  
143 It takes optional arguments allow, logger and upload_dir,
144 which are documented in the params() method, plus the request-complexity
145 limits documented below.
146  
147 It takes other optional parameters:
148  
149 =over 4
150  
151 =item * C<auto_load>
152  
153 Enable/disable the AUTOLOAD feature.
154 The default is to have it enabled.
155  
156 =item * C<config_dirs>
157  
158 Where to look for C<config_file>
159  
160 =item * C<config_file>
161  
162 Points to a configuration file which contains the parameters to C<new()>.
163 The file can be in any common format,
164 including C<YAML>, C<XML>, and C<INI>.
165 This allows the parameters to be set at run time.
166  
167 On non-Windows system,
168 the class can be configured using environment variables starting with "CGI::Info::".
169 For example:
170  
171 export CGI::Info::max_upload_size=65536
172  
173 It doesn't work on Windows because of the case-insensitive nature of that system.
174  
175 If the configuration file has a section called C<CGI::Info>,
176 only that section,
177 and the C<global> section,
178 if any exists,
179 is used.
180  
181 =item * C<syslog>
182  
183 Takes an optional parameter syslog, to log messages to
184 L<Sys::Syslog>.
185 It can be a boolean to enable/disable logging to syslog, or a reference
186 to a hash to be given to Sys::Syslog::setlogsock.
187  
188 =item * C<cache>
189  
190 An object that is used to cache IP lookups.
191 This cache object is an object that understands get() and set() messages,
192 such as a L<CHI> object.
193  
194 =item * C<allow_dtd>
195  
196 When false (the default), an XML request body containing a C<!DOCTYPE> or
197 C<!ENTITY> declaration is rejected before it is returned: C<params()>
198 returns undef and the status is set to C<403>.
199 Set this to a true value to accept such bodies, for example when parsing a
200 trusted feed that ships its own DTD.
201 Entity expansion and external entity resolution are then the caller's
202 responsibility: parse the body with a proper XML parser that has entity
203 expansion disabled.
204 Every body accepted under this option is logged as a warning naming the
205 declaration, so use of the exception is visible in the audit trail; see
206 C<dtd_warning_interval> for how those warnings are rate limited.
207 This is a constructor, configuration file or environment
208 (C<CGI__Info__allow_dtd>) setting; it cannot be overridden per C<params()>
209 call.
210  
211 =item * C<dtd_warning_interval>
212  
213 The minimum number of seconds between audit warnings for XML bodies accepted
214 because of C<allow_dtd>.
215 The default is 60.
216 Declarations that are accepted but not logged are counted, and the next
217 warning reports how many were suppressed, so a frequently polled feed does
218 not hide its traffic while still not writing a line per request.
219 Set this to C<0> to log every accepted declaration.
220  
221 The limit is per process and per request path, so the warnings for
222 F</feed/a> and F</feed/b> are counted separately and one busy feed does not
223 silence another.
224 The path is taken from C<PATH_INFO>, falling back to C<SCRIPT_NAME> and then
225 to the path part of C<REQUEST_URI>, and normalised lexically: the query string
226 is dropped, C<%XX> escapes are decoded, repeated slashes are collapsed and
227 C<.> and C<..> segments are resolved, so the usual spellings of one feed
228 (F</feed/a>, F</feed/a/>, F</feed//a>, F</feed/%61>) share a single budget
229 instead of splitting it.
230 The limiter is not per object, so it also applies when a persistent handler
231 (such as mod_perl, FastCGI or PSGI) creates a new object for every request,
232 and C<reset()> does not clear it.
233 At most 100 paths are tracked at once; when that many are in use the table is
234 cleared, which can produce one extra warning per feed.
235 It is a constructor, configuration file or environment
236 (C<CGI__Info__dtd_warning_interval>) setting.
237  
238 =item * C<max_upload_size>
239  
240 The maximum file size in bytes you can upload.
241 Use C<-1> for no limit.
242 The default is 512 KB (524288 bytes).
243  
244 =item * C<max_body_size>
245  
246 The maximum number of bytes read from a POST body.
247 This is checked against C<CONTENT_LENGTH> before anything is read and
248 against any pre-populated body, so it caps the raw request rather than
249 the parsed parameter values.
250 Use C<-1> for no limit.
251 When omitted it falls back to C<max_upload_size>, preserving the historical
252 512 KB default.
253  
254 =item * C<max_params>
255  
256 The maximum number of parameters accepted from one request.
257 The check is made on the raw key=value pairs before decoding, so it also
258 bounds the amount of work done by the parser.
259 For XML bodies (C<text/xml>, C<application/xml> and structured
260 C<application/*+xml> types such as C<application/soap+xml>), this is the
261 number of XML elements, including the root element.
262 Use C<0> to reject every parameter and C<-1> for no limit.
263 The default is 1000.
264  
265 =item * C<max_parts>
266  
267 The maximum number of parts in a C<multipart/form-data> body.
268 Use C<0> to reject every part and C<-1> for no limit.
269 The default is 100.
270  
271 =item * C<max_part_headers>
272  
273 The maximum number of header lines allowed in one C<multipart/form-data>
274 part, including C<Content-Disposition> and C<Content-Type>.
275 Use C<0> to reject any part with headers and C<-1> for no limit.
276 The default is 20.
277  
278 =item * C<max_nesting_depth>
279  
280 The maximum depth of square-bracket nesting in a parameter name, for
281 example C<a[b][c]> has a depth of 2.
282 This applies to URL-encoded, JSON and multipart parameter names, not to
283 values.
284 For XML bodies (C<text/xml>, C<application/xml> and structured
285 C<application/*+xml> types such as C<application/soap+xml>), this is the XML
286 element nesting depth, where the root element is depth 1.
287 Use C<0> to reject any bracketed name (or any XML element) and C<-1> for no
288 limit.
289 The default is 8.
290  
291 =back
292  
293 Any of these limits can also be overridden for a single C<params()> call,
294 either individually or through its C<limits> hash reference; see L</params>.
295  
296 The class can be configured at runtime using environment variables and configuration
297 files; for example, setting C<$ENV{'CGI__INFO__carp_on_warn'}> causes warnings to
298 use L<Carp>. For more information see L<Object::Configure>.
299  
300 =head3 API SPECIFICATION
301  
302 =head4 INPUT
303  
304 {
305 allow => { type => 'hashref', optional => 1 },
306 allow_dtd => { type => 'boolean', optional => 1 },
307 auto_load => { type => 'boolean', optional => 1 },
308 cache => { type => 'object', optional => 1 },
309 carp_on_warn => { type => 'boolean', optional => 1 },
310 config_dirs => { type => 'arrayref', optional => 1 },
311 config_file => { type => 'string', optional => 1 },
312 dtd_warning_interval => { type => 'integer', optional => 1, min => 0 },
313 logger => { type => 'object', optional => 1 },
314 max_body_size => { type => 'integer', optional => 1, min => -1 },
315 max_nesting_depth => { type => 'integer', optional => 1, min => -1 },
316 max_params => { type => 'integer', optional => 1, min => -1 },
317 max_part_headers => { type => 'integer', optional => 1, min => -1 },
318 max_parts => { type => 'integer', optional => 1, min => -1 },
319 max_upload_size=> { type => 'integer', optional => 1, min => -1 },
320 upload_dir => { type => 'string', optional => 1 },
321 }
322  
323 =head4 OUTPUT
324  
325 { type => 'object', isa => 'CGI::Info' }
326  
327 =head3 MESSAGES
328  
329 =over 4
330  
331 =item C<< use ->new() not ::new() to instantiate >>
332  
333 B<Level>: fatal (croak).
334 B<Cause>: called as C<CGI::Info::new()> (double-colon) instead of C<< CGI::Info->new() >>.
335 B<Action>: change the call-site to use the arrow notation.
336  
337 =item C<< Logger must be an object with info() and error() methods >>
338  
339 B<Level>: fatal (croak).
340 B<Cause>: the C<logger> argument is not a blessed object, or does not
341 implement C<info()>, C<warn()>, and C<error()> methods.
342 B<Action>: pass a compliant logger such as a L<Log::Abstraction>-based object.
343  
344 =item C<< expect has been deprecated, use allow instead >>
345  
346 B<Level>: fatal (croak).
347 B<Cause>: the removed C<expect> parameter was passed to C<new()>.
348 B<Action>: replace C<expect =E<gt> [...]> with C<allow =E<gt> { key =E<gt> qr/.../ }>.
349  
350 =back
351  
352 =cut
353  
354 38 our $stdin_data; # Class variable storing STDIN in case the class
355 # is instantiated more than once
356  
357 # Rate limiter for the allow_dtd audit warning, keyed by request path so that
358 # different XML endpoints do not share one warning budget. Process-wide rather
359 # than per object: a persistent handler (mod_perl, FastCGI, PSGI) creates a new
360 # object for each request while sharing one log, and reset() must not defeat
361 # the limit.
362 # $DTD_WARNING_STATE{$path} = { last => <time>, suppressed => <count> }
363 38 our %DTD_WARNING_STATE = ();
364  
365 sub new
366 1193 ▶{
Subroutine new: called CC=23 SCAR=34.0
Pod documented
367 1193 my $class = shift;
368  
369 # Handle hash or hashref arguments
370 1193 my $params = Params::Get::get_params(undef, \@_);
371  
372 1191 ▶ if (defined($class)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $class) { } 1186 5 1191
373 1186 ▶ my $is_valid = Scalar::Util::blessed($class) || (eval { $class->isa(__PACKAGE__) });
Condition100%3/3
builtin::blessed($class) || eval { do { $class->isa(__PACKAGE__) } }
l!l&&r!l&&!r
1411711
MC/DC100%2/2
builtin::blessed($class) || eval { do { $class->isa(__PACKAGE__) } }
builtin::blessed($class) eval { do { $class->isa(__PACKAGE__) } }
Truth table100%3/3
A || B
A= builtin::blessed($class)B= eval { do { $class->isa(__PACKAGE__) } }
ABresult
1X1
011
000
374 1186 ▶ unless ($is_valid) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($is_valid) 1 1185 1186
375 # Called as CGI::Info::new(...) or similar wrong function call
376 1 croak(__PACKAGE__, ' use ->new() not ::new() to instantiate');
377 }
378 } else {
379 # If class is undef, but there are arguments/params passed
380 5 ▶ if (defined($params) && keys %{$params}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params and keys %{$params;}) 1 4 5
Condition66%2/3
defined $params and keys %{$params;}
!ll&&!rl&&r
401
MC/DC50%1/2
defined $params and keys %{$params;}
defined $params keys %{$params;}
Truth table66%2/3
A and B
A= defined $paramsB= keys %{$params;}
ABresult
0X0
100
111
381 1 croak(__PACKAGE__, ' use ->new() not ::new() to instantiate');
382 }
383 # Called as CGI::Info::new() with 0 arguments (undef $class)
384 4 $class = __PACKAGE__;
385 }
386  
387 1189 ▶ if(Scalar::Util::blessed($class)) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($class)) 14 1175 1189
388 # If $class is an object, clone it with new arguments
389 14 ▶ $params ||= {};
Condition100%2/2
$params ||= {}
l!l
86
MC/DC100%1/1
$params ||= {}
$params
Truth table100%2/2
A
A= $params
Aresult
11
00
390  
391 # Validate any new logger passed to the clone
392 14 ▶ if(defined $params->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{"logger"}) 1 13 14
393 1 ▶ unless(Scalar::Util::blessed($params->{'logger'}) && $params->{'logger'}->can('warn') && $params->{'logger'}->can('info') && $params->{'logger'}->can('error')) {
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::blessed($params->{"logger"}) and $params->{"logger"}->can("warn") and $params->{"logger"}->can("info") and $params->{"logger"}->can("error")) 1 0 1
Condition33%3/9
builtin::blessed($params->{"logger"}) and $params->{"logger"}->can("warn") and $params->{"logger"}->can("info") and $params->{"logger"}->can("error")
!ll&&!rl&&r
100
builtin::blessed($params->{"logger"}) and $params->{"logger"}->can("warn") and $params->{"logger"}->can("info")
!ll&&!rl&&r
100
builtin::blessed($params->{"logger"}) and $params->{"logger"}->can("warn")
!ll&&!rl&&r
100
MC/DC0%0/4
builtin::blessed($params->{"logger"}) and $params->{"logger"}->can("warn") and $params->{"logger"}->can("info") and $params->{"logger"}->can("error")
builtin::blessed($params->{"logger"}) $params->{"logger"}->can("warn") $params->{"logger"}->can("info") $params->{"logger"}->can("error")
Truth table20%1/5
A and B and C and D
A= builtin::blessed($params->{"logger"})B= $params->{"logger"}->can("warn")C= $params->{"logger"}->can("info")D= $params->{"logger"}->can("error")
ABCDresult
0XXX0
10XX0
110X0
11100
11111
394 1 Carp::croak('Logger must be an object with info() and error() methods');
395 }
396 }
397  
398 # expect is deprecated even when cloning
399 13 ▶ if(defined($params->{'expect'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{"expect"}) 2 11 13
400 2 ▶ my $logger = $params->{'logger'} // $class->{'logger'};
Condition33%1/3
$params->{"logger"} // $class->{"logger"}
l!l&&r!l&&!r
020
MC/DC0%0/2
$params->{"logger"} // $class->{"logger"}
$params->{"logger"} $class->{"logger"}
Truth table33%1/3
A // B
A= $params->{"logger"}B= $class->{"logger"}
ABresult
1X1
011
000
401 2 ▶ $logger->error(ref($class) . ': expect has been deprecated, use allow instead') if $logger;
Branch: 1 branch
BranchTrueFalseTotal
if $logger 2 0 2
402 2 Carp::croak(ref($class) . ': expect has been deprecated, use allow instead');
403 }
404  
405 # Drop cached params so a new allow schema is applied on next call
406 11 my %merged = (%{$class}, %{$params});
407 11 delete $merged{'paramref'};
408 11 delete $merged{'_limits_key'};
409 11 return bless \%merged, ref($class);
410 }
411  
412 # Load the configuration from a config file, if provided
413 1175 $params = Object::Configure::configure($class, $params);
414  
415 # Validate logger object has required methods
416 1174 ▶ if(defined $params->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{"logger"}) 1174 0 1174
417 1174 ▶ unless(Scalar::Util::blessed($params->{'logger'}) && $params->{'logger'}->can('warn') && $params->{'logger'}->can('info') && $params->{'logger'}->can('error')) {
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::blessed($params->{"logger"}) and $params->{"logger"}->can("warn") and $params->{"logger"}->can("info") and $params->{"logger"}->can("error")) 0 1174 1174
Condition33%3/9
builtin::blessed($params->{"logger"}) and $params->{"logger"}->can("warn") and $params->{"logger"}->can("info") and $params->{"logger"}->can("error")
!ll&&!rl&&r
001174
builtin::blessed($params->{"logger"}) and $params->{"logger"}->can("warn") and $params->{"logger"}->can("info")
!ll&&!rl&&r
001174
builtin::blessed($params->{"logger"}) and $params->{"logger"}->can("warn")
!ll&&!rl&&r
001174
MC/DC0%0/4
builtin::blessed($params->{"logger"}) and $params->{"logger"}->can("warn") and $params->{"logger"}->can("info") and $params->{"logger"}->can("error")
builtin::blessed($params->{"logger"}) $params->{"logger"}->can("warn") $params->{"logger"}->can("info") $params->{"logger"}->can("error")
Truth table20%1/5
A and B and C and D
A= builtin::blessed($params->{"logger"})B= $params->{"logger"}->can("warn")C= $params->{"logger"}->can("info")D= $params->{"logger"}->can("error")
ABCDresult
0XXX0
10XX0
110X0
11100
11111
418 0 Carp::croak("Logger must be an object with info() and error() methods");
419 }
420 }
421  
422 1174 ▶ if(defined($params->{'expect'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{"expect"}) 5 1169 1174
423 # if(ref($params->{expect}) ne 'ARRAY') {
424 # Carp::croak(__PACKAGE__, ': expect must be a reference to an array');
425 # }
426 # # warn __PACKAGE__, ': expect is deprecated, use allow instead';
427 5 ▶ if(my $logger = $params->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $logger = $params->{"logger"}) 5 0 5
428 5 $logger->error("$class: expect has been deprecated, use allow instead");
429 }
430 5 Carp::croak("$class: expect has been deprecated, use allow instead");
431 }
432  
433 # Return the blessed object with sensible defaults
434 return bless {
435 max_upload_size => $MAX_UPLOAD_SIZE_DEFAULT,
436 allow_dtd => 0, # Reject DOCTYPE/ENTITY declarations unless asked
437 dtd_warning_interval => $DTD_WARNING_INTERVAL_DEFAULT, # Rate-limit its audit warning
438 max_body_size => undef, # Falls back to max_upload_size
439 max_params => $MAX_PARAMS_DEFAULT,
440 max_parts => $MAX_PARTS_DEFAULT,
441 max_part_headers => $MAX_PART_HEADERS_DEFAULT,
442 max_nesting_depth => $MAX_NESTING_DEPTH_DEFAULT,
443 allow => undef,
444 upload_dir => undef,
445 1169 %{$params} # Caller-supplied args override the defaults above
446 }, $class;
447 }
448  
449 =head2 script_name
450  
451 Retrieves the name of the executing CGI script.
452 This is useful for POSTing,
453 thus avoiding hard-coded paths into forms.
454  
455 use CGI::Info;
456  
457 my $info = CGI::Info->new();
458 my $script_name = $info->script_name();
459 # ...
460 print "<form method=\"POST\" action=$script_name name=\"my_form\">\n";
461  
462 =head3 API SPECIFICATION
463  
464 =head4 INPUT
465  
466 None.
467  
468 =head4 OUTPUT
469  
470 {
471 type => 'string',
472 'min' => 1,
473 'nomatch' => qr/^[\/\\]/ # Does not return absolute path
474 }
475  
476 =cut
477  
478 sub script_name
479 32 ▶{
Subroutine script_name: called CC=2 SCAR=6.9
Pod documented
480 32 my $self = shift;
481  
482 32 ▶ unless($self->{script_name}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"script_name"}) 24 8 32
483 24 $self->_find_paths();
484 }
485 32 return $self->{script_name};
486 }
487  
488 46 ▶sub _find_paths :Protected {
Subroutine _find_paths: called CC=12 SCAR=25.9
489 46 my $self = shift;
490  
491 46 $self->_trace(__PACKAGE__ . ': entering _find_paths');
492  
493 46 ▶ require File::Basename && File::Basename->import() unless File::Basename->can('basename');
Branch: 1 branch
BranchTrueFalseTotal
unless "File::Basename"->can("basename") 0 46 46
Condition16%1/6
'File::Basename'->can('basename') || require File::Basename && 'File::Basename'->import
l!l&&r!l&&!r
4600
require File::Basename and "File::Basename"->import
!ll&&!rl&&r
000
MC/DC0%0/3
'File::Basename'->can('basename') || require File::Basename && 'File::Basename'->import
'File::Basename'->can('basename') require File::Basename "File::Basename"->import
Truth table0%0/4
A || B and C
A= 'File::Basename'->can('basename')B= require File::BasenameC= "File::Basename"->import
ABCresult
1XX1
0111
00X0
0100
494  
495 # Determine script name
496 46 ▶ my $script_name = $self->_get_env('SCRIPT_NAME') // $0;
Condition66%2/3
$self->_get_env("SCRIPT_NAME") // $0
l!l&&r!l&&!r
22240
MC/DC0%0/2
$self->_get_env("SCRIPT_NAME") // $0
$self->_get_env("SCRIPT_NAME") $0
Truth table66%2/3
A // B
A= $self->_get_env("SCRIPT_NAME")B= $0
ABresult
1X1
011
000
497 46 $self->{script_name} = $self->_untaint_filename({
498 filename => File::Basename::basename($script_name)
499 });
500  
501 # Determine script path
502 46 ▶ if(my $script_path = $self->_get_env('SCRIPT_FILENAME')) {
Branch: 3 branches
BranchTrueFalseTotal
if (my $script_path = $self->_get_env('SCRIPT_FILENAME')) { } 13 33 46
elsif ($script_name = $self->_get_env('SCRIPT_NAME')) { } 19 14 33
elsif ('File::Spec'->file_name_is_absolute($0)) { } 0 14 14
503 13 $self->{script_path} = $script_path;
504 } elsif($script_name = $self->_get_env('SCRIPT_NAME')) {
505 19 ▶ if(my $document_root = $self->_get_env('DOCUMENT_ROOT')) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $document_root = $self->_get_env('DOCUMENT_ROOT')) { } 8 11 19
506 8 $script_name = $self->_get_env('SCRIPT_NAME');
507  
508 # It's usually the case, e.g. /cgi-bin/foo.pl
509 8 $script_name =~ s{^/}{};
510  
511 8 $self->{script_path} = File::Spec->catfile($document_root, $script_name);
512 } else {
513 11 ▶ if(File::Spec->file_name_is_absolute($script_name) && (-r $script_name)) {
Branch: 1 branch
BranchTrueFalseTotal
if ('File::Spec'->file_name_is_absolute($script_name) and -r $script_name) { } 1 10 11
Condition100%3/3
"File::Spec"->file_name_is_absolute($script_name) and -r $script_name
!ll&&!rl&&r
371
MC/DC100%2/2
"File::Spec"->file_name_is_absolute($script_name) and -r $script_name
"File::Spec"->file_name_is_absolute($script_name) -r $script_name
Truth table100%3/3
A and B
A= "File::Spec"->file_name_is_absolute($script_name)B= -r $script_name
ABresult
0X0
100
111
514 # Called from a command line with a full path
515 1 $self->{script_path} = $script_name;
516 } else {
517 10 ▶ require Cwd unless Cwd->can('abs_path');
Branch: 1 branch
BranchTrueFalseTotal
unless "Cwd"->can("abs_path") 0 10 10
518  
519 10 ▶ if($script_name =~ /^\/(.+)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($script_name =~ m[^/(.+)]) 7 3 10
520 # It's usually the case, e.g. /cgi-bin/foo.pl
521 7 $script_name = $1;
522 }
523  
524 10 $self->{script_path} = File::Spec->catfile(Cwd::abs_path(), $script_name);
525 }
526 }
527 } elsif(File::Spec->file_name_is_absolute($0)) {
528 # Called from a command line with a full path
529 0 $self->{script_path} = $0;
530 } else {
531 14 $self->{script_path} = File::Spec->rel2abs($0);
532 }
533  
534 # Untaint and finalize script path
535 $self->{script_path} = $self->_untaint_filename({
536 filename => $self->{script_path}
537 46 });
538 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
539  
540 =head2 script_path
541  
542 Finds the full path name of the script.
543  
544 use CGI::Info;
545  
546 my $info = CGI::Info->new();
547 my $fullname = $info->script_path();
548 my @statb = stat($fullname);
549  
550 if(@statb) {
551 my $mtime = localtime $statb[9];
552 print "Last-Modified: $mtime\n";
553 # TODO: only for HTTP/1.1 connections
554 # $etag = Digest::MD5::md5_hex($html);
555 printf "ETag: \"%x\"\n", $statb[9];
556 }
557 =cut
558  
559 36 ▶sub script_path {
Subroutine script_path: called CC=2 SCAR=6.9
Pod documented
560 36 my $self = shift;
561  
562 36 ▶ unless($self->{script_path}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"script_path"}) 14 22 36
563 14 $self->_find_paths();
564 }
565 36 return $self->{script_path};
566 }
567  
568 =head2 script_dir
569  
570 Returns the file system directory containing the script.
571  
572 use CGI::Info;
573 use File::Spec;
574  
575 my $info = CGI::Info->new();
576  
577 print 'HTML files are normally stored in ', $info->script_dir(), '/', File::Spec->updir(), "\n";
578  
579 # or
580 use lib CGI::Info::script_dir() . '../lib';
581  
582 =cut
583  
584 sub script_dir
585 23 ▶{
Subroutine script_dir: called CC=5 SCAR=16.3
Pod documented
586 23 my $self = shift;
587  
588 # Ensure $self is an object
589 23 ▶ $self = __PACKAGE__->new() unless ref $self;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self 3 20 23
590  
591 # Set script path if it is not already defined
592 23 ▶ $self->_find_paths() unless $self->{script_path};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"script_path"} 8 15 23
593  
594 # Extract directory from script path based on OS
595 # Don't use File::Spec->splitpath() since that can leave the trailing slash
596 23 ▶ my $dir_regex = $^O eq 'MSWin32' ? qr{(.+)\\.+?$} : qr{(.+)/.+?$};
Branch: 1 branch
BranchTrueFalseTotal
$^O eq 'MSWin32' ? : 0 23 23
597  
598 23 ▶ return $self->{script_path} =~ $dir_regex ? $1 : $self->{script_path};
Branch: 1 branch
BranchTrueFalseTotal
$self->{'script_path'} =~ /$dir_regex/ ? : 23 0 23
599 }
600  
601 =head2 host_name
602  
603 Return the host-name of the current web server, according to CGI.
604 If the name can't be determined from the web server, the system's host-name
605 is used as a fall back.
606 This may not be the same as the machine that the CGI script is running on,
607 some ISPs and other sites run scripts on different machines from those
608 delivering static content.
609 There is a good chance that this will be domain_name() prepended with either
610 'www' or 'cgi'.
611  
612 use CGI::Info;
613  
614 my $info = CGI::Info->new();
615 my $host_name = $info->host_name();
616 my $protocol = $info->protocol();
617 # ...
618 print "Thank you for visiting our <A HREF=\"$protocol://$host_name\">Website!</A>";
619  
620 =cut
621  
622 131 ▶sub host_name {
Subroutine host_name: called CC=2 SCAR=6.9
Pod documented
623 131 my $self = shift;
624  
625 131 ▶ unless($self->{site}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"site"}) 23 108 131
626 23 $self->_find_site_details();
627 }
628  
629 131 return $self->{site};
630 }
631  
632 50 ▶sub _find_site_details :Protected {
Subroutine _find_site_details: called CC=17 SCAR=28.8
633 50 my $self = shift;
634  
635 # Log entry to the routine
636 50 $self->_trace('Entering _find_site_details');
637  
638 50 ▶ return if $self->{site} && $self->{cgi_site};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"site"} and $self->{"cgi_site"} 6 44 50
Condition66%2/3
$self->{"site"} and $self->{"cgi_site"}
!ll&&!rl&&r
4406
MC/DC50%1/2
$self->{"site"} and $self->{"cgi_site"}
$self->{"site"} $self->{"cgi_site"}
Truth table66%2/3
A and B
A= $self->{"site"}B= $self->{"cgi_site"}
ABresult
0X0
100
111
639  
640 # Determine cgi_site using environment variables or hostname
641 44 ▶ if (my $host = ($ENV{'HTTP_HOST'} || $ENV{'SERVER_NAME'} || $ENV{'SSL_TLS_SNI'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $host = $ENV{'HTTP_HOST'} || $ENV{'SERVER_NAME'} || $ENV{'SSL_TLS_SNI'}) { } 37 7 44
Condition100%6/6
$ENV{'HTTP_HOST'} || $ENV{'SERVER_NAME'} || $ENV{'SSL_TLS_SNI'}
l!l&&r!l&&!r
3617
$ENV{"HTTP_HOST"} or $ENV{"SERVER_NAME"}
l!l&&r!l&&!r
3248
MC/DC100%3/3
$ENV{'HTTP_HOST'} || $ENV{'SERVER_NAME'} || $ENV{'SSL_TLS_SNI'}
$ENV{"HTTP_HOST"} $ENV{"SERVER_NAME"} $ENV{'SSL_TLS_SNI'}
Truth table100%4/4
A or B || C
A= $ENV{"HTTP_HOST"}B= $ENV{"SERVER_NAME"}C= $ENV{'SSL_TLS_SNI'}
ABCresult
1XX1
01X1
0011
0000
642 # Import necessary module
643 37 ▶ require URI::Heuristic unless URI::Heuristic->can('uf_uristr');
Branch: 1 branch
BranchTrueFalseTotal
unless "URI::Heuristic"->can("uf_uristr") 6 31 37
644  
645 37 $self->{cgi_site} = URI::Heuristic::uf_uristr($host);
646 # Remove trailing dots from the name. They are legal in URLs
647 # and some sites link using them to avoid spoofing (nice)
648 37 $self->{cgi_site} =~ s/\.+$//; # Trim trailing dots
649  
650 37 ▶ if($ENV{'SERVER_NAME'} && ($host eq $ENV{'SERVER_NAME'}) && (my $protocol = $self->protocol()) && $self->protocol() ne 'http') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{"SERVER_NAME"} and $host eq $ENV{"SERVER_NAME"} and my $protocol = $self->protocol and $self->protocol ne "http") 2 35 37
Condition88%8/9
$ENV{"SERVER_NAME"} and $host eq $ENV{"SERVER_NAME"} and my $protocol = $self->protocol and $self->protocol ne "http"
!ll&&!rl&&r
3322
$ENV{"SERVER_NAME"} and $host eq $ENV{"SERVER_NAME"} and my $protocol = $self->protocol
!ll&&!rl&&r
3214
$ENV{"SERVER_NAME"} and $host eq $ENV{"SERVER_NAME"}
!ll&&!rl&&r
3205
MC/DC75%3/4
$ENV{"SERVER_NAME"} and $host eq $ENV{"SERVER_NAME"} and my $protocol = $self->protocol and $self->protocol ne "http"
$ENV{"SERVER_NAME"} $host eq $ENV{"SERVER_NAME"} my $protocol = $self->protocol $self->protocol ne "http"
Truth table80%4/5
A and B and C and D
A= $ENV{"SERVER_NAME"}B= $host eq $ENV{"SERVER_NAME"}C= my $protocol = $self->protocolD= $self->protocol ne "http"
ABCDresult
0XXX0
10XX0
110X0
11100
11111
651 2 $self->{cgi_site} =~ s/^http/$protocol/;
652 }
653 } else {
654 # Import necessary module
655 7 ▶ require Sys::Hostname unless Sys::Hostname->can('hostname');
Branch: 1 branch
BranchTrueFalseTotal
unless "Sys::Hostname"->can("hostname") 0 7 7
656  
657 7 $self->_debug('Falling back to using hostname');
658 7 $self->{cgi_site} = Sys::Hostname::hostname();
659 }
660  
661 # Set site details if not already defined
662 44 ▶ $self->{site} ||= $self->{cgi_site};
Condition33%1/3
$self->{"site"} ||= $self->{"cgi_site"}
l!l&&r!l&&!r
0440
MC/DC0%0/2
$self->{"site"} ||= $self->{"cgi_site"}
$self->{"site"} $self->{"cgi_site"}
Truth table33%1/3
A ||= B
A= $self->{"site"}B= $self->{"cgi_site"}
ABresult
1X1
011
000
663 44 $self->{site} =~ s/^https?:\/\/(.+)/$1/;
664 $self->{cgi_site} = ($self->protocol() || 'http') . '://' . $self->{cgi_site}
665 44 ▶ unless $self->{cgi_site} =~ /^https?:\/\//;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"cgi_site"} =~ m[^https?://] 10 34 44
Condition100%2/2
$self->protocol || 'http'
l!l
19
MC/DC100%1/1
$self->protocol || 'http'
$self->protocol
Truth table100%2/2
A
A= $self->protocol
Aresult
11
00
666  
667 # Warn if site details could not be determined
668 44 ▶ $self->_warn('Could not determine site name') unless($self->{site} && $self->{cgi_site});
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"site"} and $self->{"cgi_site"} 0 44 44
Condition33%1/3
$self->{"site"} and $self->{"cgi_site"}
!ll&&!rl&&r
0044
MC/DC0%0/2
$self->{"site"} and $self->{"cgi_site"}
$self->{"site"} $self->{"cgi_site"}
Truth table33%1/3
A and B
A= $self->{"site"}B= $self->{"cgi_site"}
ABresult
0X0
100
111
669  
670 # Log exit
671 44 $self->_trace('Leaving _find_site_details');
672 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
673  
674 =head2 domain_name
675  
676 Domain_name is the name of the controlling domain for this website.
677 Usually it will be similar to host_name, but will lack the http:// or www prefixes.
678  
679 Can be called as a class method.
680  
681 =cut
682  
683 20 ▶sub domain_name {
Subroutine domain_name: called CC=5 SCAR=16.1
Pod documented
684 20 my $self = shift;
685  
686 20 ▶ if(!ref($self)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $self) 4 16 20
687 4 $self = __PACKAGE__->new();
688 }
689 20 ▶ return $self->{domain} if $self->{domain};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"domain"} 3 17 20
690  
691 17 $self->_find_site_details();
692  
693 17 ▶ if(my $site = $self->{site}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $site = $self->{"site"}) 17 0 17
694 17 ▶ $self->{domain} = ($site =~ /^www\.(.+)/) ? $1 : $site;
Branch: 1 branch
BranchTrueFalseTotal
$site =~ /^www\.(.+)/ ? : 11 6 17
695 }
696  
697 17 return $self->{domain};
698 }
699  
700 =head2 cgi_host_url
701  
702 Return the URL of the machine running the CGI script.
703  
704 =cut
705  
706 16 ▶sub cgi_host_url {
Subroutine cgi_host_url: called CC=2 SCAR=6.9
Pod documented
707 16 my $self = shift;
708  
709 16 ▶ unless($self->{cgi_site}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"cgi_site"}) 10 6 16
710 10 $self->_find_site_details();
711 }
712  
713 16 return $self->{cgi_site};
714 }
715  
716 =head2 params
717  
718 Returns a reference to a hash list of the CGI arguments.
719  
720 CGI::Info helps you to test your script before deployment on a website:
721 if it is not in a CGI environment (e.g., the script is being tested from the
722 command line), the program's command line arguments (a list of key=value pairs)
723 are used, if there are no command line arguments,
724 then they are read from stdin as a list of key=value lines.
725 Also,
726 you can give one of --tablet, --search-engine,
727 --mobile and --robot to mimic those agents. For example:
728  
729 ./script.cgi --mobile name=Nigel
730  
731 Returns undef if the parameters can't be determined or if none were given.
732  
733 If an argument is given twice or more, then the values are put in a comma
734 separated string.
735  
736 The returned hash value can be passed into L<CGI::Untaint>.
737  
738 Takes the optional parameters allow, logger and upload_dir.
739 The request-complexity limits (C<max_body_size>, C<max_params>, C<max_parts>,
740 C<max_part_headers> and C<max_nesting_depth>) can be set on the constructor or
741 in the configuration file, and can also be overridden for a single call.
742 Pass them individually:
743  
744 my $params = $info->params(max_params => 50, max_nesting_depth => 2);
745  
746 or use a shared C<limits> hash reference:
747  
748 my $params = $info->params(limits => {
749 max_params => 50,
750 max_nesting_depth => 2,
751 });
752  
753 The C<limits> hash may contain any of the five limit names; unknown names are
754 rejected. Individual limit arguments take precedence over values in the
755 C<limits> hash. Passing a limit to C<params()> also makes that call re-parse
756 the request if the cached result was produced with different limits, so a
757 stricter limit cannot be bypassed by an earlier C<params()> call. The per-call
758 values apply only to that call; the instance's configured limits are unchanged
759 afterwards.
760 The parameters are passed in a hash, or a reference to a hash.
761 The latter is more efficient since it puts less on the stack.
762  
763 Allow is a reference to a hash list of CGI parameters that you will allow.
764 The value for each entry is either a permitted value,
765 a regular expression of permitted values for
766 the key,
767 a code reference,
768 or a hash of L<Params::Validate::Strict> rules.
769 Subroutine exceptions propagate normally, allowing custom error handling.
770 This works alongside existing regex and Params::Validate::Strict patterns.
771 A undef value means that any value will be allowed.
772 Arguments not in the list are silently ignored.
773 This is useful to help to block attacks on your site.
774  
775 Upload_dir is a string containing a directory where files being uploaded are to
776 be stored.
777 It must be a writeable directory inside a temporary area: the directory
778 returned by L</tmpdir>, a classic system temporary directory such as F</tmp>,
779 F</var/tmp> or F</usr/tmp>, the area named by C<TMPDIR>, C<TEMP> or C<TMP>, or
780 on macOS any directory below F</var/folders>.
781 This matters because a web server usually does not export C<TMPDIR>, so
782 L</tmpdir> can point somewhere different from the platform's temporary tree.
783  
784 It has to be a directory I<inside> an area, not the area root itself: C</tmp>
785 and the like are shared and world-writable, so pass a subdirectory created for
786 the application instead.
787 The test is made against the resolved path, so a directory reached through
788 C<..> is judged by where it really is, and a sibling that merely shares a name
789 prefix with a temporary area is not accepted.
790 C<%XX> escapes are decoded first, so an encoded spelling of a path is judged
791 like its decoded form.
792 On Windows both C</> and C<\> separate directories, and that is applied after
793 decoding, so an encoded C<%5C> cannot hide a C<..> traversal either.
794 Two Windows spellings are refused because they cannot be checked against a
795 temporary area by comparing strings: a drive-relative path such as C<C:uploads>
796 (and a bare C<C:>), which starts at the current directory on that drive rather
797 than at its root, and an 8.3 short name such as C<PROGRA~1>, which is an alias
798 for a long name that only the filesystem can expand.
799 Pass a long, absolute path instead.
800 The filesystem root is never treated as a temporary area.
801  
802 Takes an optional parameter logger, which is used for warnings and traces.
803 It can be an object that understands warn() and trace() messages,
804 such as a L<Log::Log4perl> or L<Log::Any> object,
805 a reference to code,
806 a reference to an array,
807 or a filename.
808  
809 The allow, logger and upload_dir arguments can also be passed to the
810 constructor.
811  
812 use CGI::Info;
813 use CGI::Untaint;
814 # ...
815 my $info = CGI::Info->new();
816 my %params;
817 if($info->params()) {
818 %params = %{$info->params()};
819 }
820 # ...
821 foreach(keys %params) {
822 print "$_ => $params{$_}\n";
823 }
824 my $u = CGI::Untaint->new(%params);
825  
826 use CGI::Info;
827 use CGI::IDS;
828 # ...
829 my $info = CGI::Info->new();
830 my $allowed = {
831 foo => qr/^\d*$/, # foo must be a number, or empty
832 bar => undef, # bar can be given and be any value
833 xyzzy => qr/^[\w\s-]+$/, # must be alphanumeric
834 # to prevent XSS, and non-empty
835 # as a sanity check
836 };
837 # or
838 $allowed = {
839 email => { type => 'string', matches => qr/^[^@]+@[^@]+\.[^@]+$/ }, # String, basic email format check
840 age => { type => 'integer', min => 0, max => 150 }, # Integer between 0 and 150
841 bio => { type => 'string', optional => 1 }, # String, optional
842 ip_address => { type => 'string', matches => qr/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/ }, #Basic IPv4 validation
843 };
844 my $paramsref = $info->params(allow => $allowed);
845 if(defined($paramsref)) {
846 my $ids = CGI::IDS->new();
847 $ids->set_scan_keys(scan_keys => 1);
848 if($ids->detect_attacks(request => $paramsref) > 0) {
849 die 'horribly';
850 }
851 }
852  
853 If the request is an XML request (i.e. the content type of the POST is
854 text/xml, application/xml or a structured application/*+xml type such as
855 application/soap+xml), CGI::Info will put the request into the params
856 element 'XML', thus:
857  
858 use CGI::Info;
859 # ...
860 my $info = CGI::Info->new();
861 my $paramsref = $info->params(); # See BUGS below
862 my $xml = $$paramsref{'XML'};
863 # ... parse and process the XML request in $xml
864  
865 Before returning the body, XML is checked against C<max_params> (the number
866 of elements, including the root) and C<max_nesting_depth> (element depth,
867 with the root at depth 1). Comments, CDATA sections and processing
868 instructions are ignored. A body containing a C<!DOCTYPE> or C<!ENTITY>
869 declaration is rejected with status C<403> and C<params()> returns undef,
870 because such declarations enable entity expansion and external entity
871 attacks. Pass C<< allow_dtd => 1 >> to the constructor to accept them for a
872 trusted feed; each accepted declaration is still logged as a warning, so the
873 exception is recorded. These are structural checks, not an XML parser; use a
874 proper parser with entity expansion disabled for untrusted XML.
875  
876 Carp if logger is not set and we detect something serious.
877  
878 Blocks some attacks,
879 such as SQL and XSS injections,
880 mustleak and directory traversals,
881 thus creating a primitive web application firewall (WAF).
882 Warning - this is an extra layer, not a replacement for your other security layers.
883  
884 The request-complexity limits (C<max_body_size>, C<max_params>, C<max_parts>,
885 C<max_part_headers> and C<max_nesting_depth>) are applied before parameter
886 decoding and, for multipart bodies, while the body is parsed.
887 A request that exceeds one of them causes C<params()> to return undef
888 and sets the HTTP status to 413 (Payload Too Large).
889  
890 =head3 Validation Subroutine Support
891  
892 The C<allow> parameter accepts subroutine references for dynamic validation,
893 enabling complex parameter checks beyond static regex patterns.
894 These callbacks:
895  
896 =over 4
897  
898 =item * Receive three arguments: the parameter key, value and the C<CGI::Info> instance
899  
900 =item * Must return a true value to allow the parameter, false to reject
901  
902 =item * Can access other parameters through the instance for contextual validation
903  
904 =back
905  
906 Basic usage:
907  
908 CGI::Info->new(
909 allow => {
910 # Simple value check
911 even_number => sub { ($_[1] % 2) == 0 },
912  
913 # Context-aware validation
914 child_age => sub {
915 my ($key, $value, $info) = @_;
916 $info->param('is_parent') ? $value <= 18 : 0
917 }
918 }
919 );
920  
921 Advanced features:
922  
923 # Combine with regex validation
924 mixed_validation => {
925 email => qr/@/, # Regex check
926 promo_code => \&validate_promo_code # Subroutine check
927 }
928  
929 # Throw custom exceptions
930 dangerous_param => sub {
931 die 'Hacking attempt!' if $_[1] =~ /DROP TABLE/;
932 return 1;
933 }
934 =cut
935  
936 # Validate one per-call limit. Undef means "no override" so that
937 # max_body_size can still fall back to max_upload_size.
938 16 ▶sub _validate_limit :Protected {
Subroutine _validate_limit: called CC=3 SCAR=11.0
939 16 my ($self, $name, $value) = @_;
940  
941 16 ▶ if(ref($value) || ($value !~ /\A[+-]?\d+\z/)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value or not $value =~ /\A[+-]?\d+\z/) 2 14 16
Condition66%2/3
ref $value or not $value =~ /\A[+-]?\d+\z/
l!l&&r!l&&!r
0214
MC/DC50%1/2
ref $value or not $value =~ /\A[+-]?\d+\z/
ref $value not $value =~ /\A[+-]?\d+\z/
Truth table66%2/3
A or not(B)
A= ref $valueB= not $value =~ /\A[+-]?\d+\z/
ABresult
1X1
011
000
942 2 Carp::croak(__PACKAGE__ . "::params: $name must be an integer");
943 }
944  
945 14 return $value + 0;
946 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
947  
948 # Collect per-call complexity-limit overrides from either a shared limits
949 # hash-ref, the individual limit arguments, or both. Individual arguments
950 # take precedence over values in the shared profile.
951 836 ▶sub _per_call_limits :Protected {
Subroutine _per_call_limits: called CC=12 SCAR=25.0
952 836 my ($self, $params) = @_;
953  
954 836 ▶ return {} unless(defined($params) && (ref($params) eq 'HASH'));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $params and ref $params eq "HASH" 734 102 836
Condition66%2/3
defined $params and ref $params eq "HASH"
!ll&&!rl&&r
7340102
MC/DC50%1/2
defined $params and ref $params eq "HASH"
defined $params ref $params eq "HASH"
Truth table66%2/3
A and B
A= defined $paramsB= ref $params eq "HASH"
ABresult
0X0
100
111
955  
956 102 my %known = map { $_ => 1 } @COMPLEXITY_LIMITS;
957 102 my %limits;
958  
959 102 ▶ if(exists($params->{limits}) && defined($params->{limits})) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params->{"limits"} and defined $params->{"limits"}) 7 95 102
Condition66%2/3
exists $params->{"limits"} and defined $params->{"limits"}
!ll&&!rl&&r
9507
MC/DC50%1/2
exists $params->{"limits"} and defined $params->{"limits"}
exists $params->{"limits"} defined $params->{"limits"}
Truth table66%2/3
A and B
A= exists $params->{"limits"}B= defined $params->{"limits"}
ABresult
0X0
100
111
960 7 my $profile = $params->{limits};
961 7 ▶ unless(ref($profile) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $profile eq "HASH") 1 6 7
962 1 Carp::croak(__PACKAGE__ . '::params: limits must be a hash reference');
963 }
964  
965 6 foreach my $name (keys %{$profile}) {
966 7 ▶ unless($known{$name}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($known{$name}) 1 6 7
967 1 Carp::croak(__PACKAGE__ . "::params: unknown complexity limit '$name' in limits");
968 }
969 6 ▶ next unless(defined($profile->{$name}));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $profile->{$name} 0 6 6
970 6 $limits{$name} = $self->_validate_limit($name, $profile->{$name});
971 }
972 }
973  
974 99 foreach my $name (@COMPLEXITY_LIMITS) {
975 492 ▶ next unless(exists($params->{$name}));
Branch: 1 branch
BranchTrueFalseTotal
unless exists $params->{$name} 482 10 492
976 10 ▶ next unless(defined($params->{$name}));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $params->{$name} 0 10 10
977 10 $limits{$name} = $self->_validate_limit($name, $params->{$name});
978 }
979  
980 98 return \%limits;
981 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
982  
983 # The effective raw-body limit. max_body_size is optional so that existing
984 # callers keep the historical max_upload_size behaviour when they do not set it.
985 1058 ▶sub _body_limit :Protected {
Subroutine _body_limit: called CC=2 SCAR=6.9
986 1058 my $self = shift;
987  
988 1058 ▶ return $self->{max_body_size} if defined($self->{max_body_size});
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"max_body_size"} 10 1048 1058
989 1048 return $self->{max_upload_size};
990 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
991  
992 # A negative limit means "unlimited"; the comparison is deliberately inclusive
993 # so that a body or parameter count exactly at the limit is accepted.
994 3095 ▶sub _over_limit :Protected {
Subroutine _over_limit: called CC=3 SCAR=11.0
995 3095 my ($self, $value, $limit) = @_;
996  
997 3095 ▶ return 0 unless defined($limit);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $limit 0 3095 3095
998 3095 ▶ return 0 if($limit < 0);
Branch: 1 branch
BranchTrueFalseTotal
if $limit < 0 2 3093 3095
999 3093 return $value > $limit;
1000 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1001  
1002 # Maximum depth of square-bracket nesting in a parameter name:
1003 # a[b][c] is 2, as is a[b[c]]. Counting opening brackets treats sibling
1004 # groups as successive levels, which is how form-to-array names are used.
1005 2094 ▶sub _param_nesting_depth :Protected {
Subroutine _param_nesting_depth: called CC=1 SCAR=0.0
1006 2094 my ($self, $key) = @_;
1007  
1008 2094 my $depth = () = $key =~ /\[/g;
1009 2094 return $depth;
1010 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1011  
1012 # Find the '>' that closes a tag, ignoring '>' inside quoted attribute values.
1013 381 ▶sub _xml_tag_end :Protected {
Subroutine _xml_tag_end: called CC=7 SCAR=19.6
1014 381 my ($self, $xml, $pos) = @_;
1015  
1016 381 my $length = length($xml);
1017 381 my $quote;
1018 381 ▶ while($pos < $length) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos < $length) 5649 0 5649
1019 5649 my $char = substr($xml, $pos, 1);
1020 5649 ▶ if(defined($quote)) {
Branch: 3 branches
BranchTrueFalseTotal
if (defined $quote) { } 1297 4352 5649
elsif ($char eq '"' or $char eq q[']) { } 135 4217 4352
elsif ($char eq '>') { } 381 3836 4217
1021 1297 ▶ $quote = undef if($char eq $quote);
Branch: 1 branch
BranchTrueFalseTotal
if $char eq $quote 135 1162 1297
1022 ▶ } elsif(($char eq '"') || ($char eq "'")) {
Condition66%2/3
$char eq "\"" or $char eq "'"
l!l&&r!l&&!r
13504217
MC/DC50%1/2
$char eq "\"" or $char eq "'"
$char eq "\"" $char eq "'"
Truth table66%2/3
A or B
A= $char eq "\""B= $char eq "'"
ABresult
1X1
011
000
1023 135 $quote = $char;
1024 } elsif($char eq '>') {
1025 381 return $pos;
1026 }
1027 5268 $pos++;
1028 }
1029  
1030 0 return -1;
1031 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1032  
1033 # Count XML elements and their maximum nesting depth without parsing the
1034 # document. Comments, CDATA sections and processing instructions are skipped.
1035 # The root element is at depth 1. A self-closing element counts as one
1036 # element at depth + 1 but does not open a level for its siblings.
1037 # A DOCTYPE or ENTITY declaration is reported as forbidden: it enables entity
1038 # expansion and external entity attacks, so such a body is rejected unless the
1039 # caller opted in with allow_dtd.
1040 151 ▶sub _xml_complexity :Protected {
Subroutine _xml_complexity: called CC=15 SCAR=27.2
1041 151 my ($self, $xml) = @_;
1042  
1043 151 my $elements = 0;
1044 151 my $depth = 0;
1045 151 my $max_depth = 0;
1046 151 my $forbidden;
1047 151 my $pos = 0;
1048 151 my $length = length($xml);
1049  
1050 151 ▶ while($pos < $length) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos < $length) 387 151 538
1051 387 my $start = index($xml, '<', $pos);
1052 387 ▶ last if($start < 0);
Branch: 1 branch
BranchTrueFalseTotal
if $start < 0 0 387 387
1053  
1054 387 ▶ if(substr($xml, $start, 4) eq '<!--') {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($xml, $start, 4) eq "<!--") 3 384 387
1055 3 my $end = index($xml, '-->', $start + 4);
1056 3 ▶ last if($end < 0);
Branch: 1 branch
BranchTrueFalseTotal
if $end < 0 0 3 3
1057 3 $pos = $end + 3;
1058 3 next;
1059 }
1060 384 ▶ if(substr($xml, $start, 9) eq '<![CDATA[') {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($xml, $start, 9) eq "<![CDATA[") 3 381 384
1061 3 my $end = index($xml, ']]>', $start + 9);
1062 3 ▶ last if($end < 0);
Branch: 1 branch
BranchTrueFalseTotal
if $end < 0 0 3 3
1063 3 $pos = $end + 3;
1064 3 next;
1065 }
1066  
1067 381 my $end = $self->_xml_tag_end($xml, $start + 1);
1068 381 ▶ last if($end < 0);
Branch: 1 branch
BranchTrueFalseTotal
if $end < 0 0 381 381
1069 381 my $tag = substr($xml, $start + 1, $end - $start - 1);
1070 381 $pos = $end + 1;
1071  
1072 381 ▶ if($tag =~ /^\s*!\s*(DOCTYPE|ENTITY)\b/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tag =~ /^\s*!\s*(DOCTYPE|ENTITY)\b/i) 125 256 381
1073 125 $forbidden = uc($1);
1074 }
1075  
1076 # Declarations, DOCTYPE declarations and processing instructions.
1077 381 ▶ next if($tag =~ /^\s*[!?]/);
Branch: 1 branch
BranchTrueFalseTotal
if $tag =~ /^\s*[!?]/ 133 248 381
1078  
1079 248 ▶ if($tag =~ m{^/\s*[A-Za-z_][\w.:-]*\s*$}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tag =~ m[^/\s*[A-Za-z_][\w.:-]*\s*$]) 57 191 248
1080 57 ▶ $depth-- if($depth > 0);
Branch: 1 branch
BranchTrueFalseTotal
if $depth > 0 57 0 57
1081 57 next;
1082 }
1083  
1084 191 ▶ next unless($tag =~ m{^\s*[A-Za-z_][\w.:-]*});
Branch: 1 branch
BranchTrueFalseTotal
unless $tag =~ /^\s*[A-Za-z_][\w.:-]*/ 0 191 191
1085 191 $elements++;
1086  
1087 191 my $element_depth = $depth + 1;
1088 191 ▶ $max_depth = $element_depth if($element_depth > $max_depth);
Branch: 1 branch
BranchTrueFalseTotal
if $element_depth > $max_depth 187 4 191
1089 191 ▶ $depth = $element_depth unless($tag =~ m{/\s*$});
Branch: 1 branch
BranchTrueFalseTotal
unless $tag =~ m[/\s*$] 57 134 191
1090 }
1091  
1092 151 return { elements => $elements, depth => $max_depth, forbidden => $forbidden };
1093 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1094  
1095 # Identify the effective limits so a cached parameter set is only reused when
1096 # it was produced under the same limits. _body_limit() is used rather than
1097 # max_body_size because an unset max_body_size falls back to max_upload_size.
1098 832 ▶sub _limits_key :Protected {
Subroutine _limits_key: called CC=2 SCAR=7.1
1099 832 my $self = shift;
1100  
1101 4160 ▶ return join("\0", map { defined($_) ? $_ : 'undef' } (
Branch: 1 branch
BranchTrueFalseTotal
defined $_ ? : 4160 0 4160
1102 $self->_body_limit(),
1103 $self->{max_params},
1104 $self->{max_parts},
1105 $self->{max_part_headers},
1106 $self->{max_nesting_depth},
1107 832 ));
1108 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1109  
1110 # Record a complexity rejection once, set the status and log it. The private
1111 # flag lets callers such as _multipart_data() abort a nested parse and have
1112 # params() stop without confusing an empty result with a successful parse.
1113 22 ▶sub _reject_complexity :Protected {
Subroutine _reject_complexity: called CC=1 SCAR=0.0
1114 22 my ($self, $what) = @_;
1115  
1116 22 $self->{_limit_exceeded} = 1;
1117 22 $self->status(413);
1118 22 $self->_warn("Request complexity limit exceeded: $what");
1119 22 return;
1120 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1121  
1122 # The feed an audit warning belongs to. This is the request path, so two XML
1123 # endpoints served by one process each get their own warning budget. The path
1124 # is normalised lexically -- query string dropped, %XX decoded, repeated
1125 # slashes collapsed and '.' or '..' segments resolved -- so the usual spellings
1126 # of one feed share its budget instead of letting a client fragment it.
1127 # Nothing is looked up on disk: these are URL paths, not files.
1128 119 ▶sub _dtd_audit_key :Protected {
Subroutine _dtd_audit_key: called CC=6 SCAR=18.5
1129 119 my $self = shift;
1130  
1131 119 foreach my $var (qw(PATH_INFO SCRIPT_NAME REQUEST_URI)) {
1132 127 my $path = $ENV{$var};
1133 127 ▶ next unless(defined($path) && length($path));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path and length $path 12 115 127
Condition66%2/3
defined $path and length $path
!ll&&!rl&&r
120115
MC/DC50%1/2
defined $path and length $path
defined $path length $path
Truth table66%2/3
A and B
A= defined $pathB= length $path
ABresult
0X0
100
111
1134  
1135 115 $path =~ s/\?.*//s;
1136  
1137 115 my $key = $self->_tidy_path($path);
1138 115 ▶ next unless(defined($key) && length($key));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key and length $key 0 115 115
Condition33%1/3
defined $key and length $key
!ll&&!rl&&r
00115
MC/DC0%0/2
defined $key and length $key
defined $key length $key
Truth table33%1/3
A and B
A= defined $keyB= length $key
ABresult
0X0
100
111
1139 115 return $key;
1140 }
1141  
1142 4 return '';
1143 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1144  
1145 # Log that allow_dtd let a DOCTYPE/ENTITY declaration through, at most once per
1146 # dtd_warning_interval seconds per request path. A trusted feed that is polled
1147 # continuously would otherwise write one warning per request; the number of
1148 # declarations accepted for that feed but not logged is reported by its next
1149 # warning. An interval of 0 (or less) logs every occurrence.
1150 119 ▶sub _audit_allowed_dtd :Protected {
Subroutine _audit_allowed_dtd: called CC=10 SCAR=23.0
1151 119 my ($self, $declaration) = @_;
1152  
1153 119 my $interval = $self->{dtd_warning_interval};
1154 119 ▶ $interval = $DTD_WARNING_INTERVAL_DEFAULT unless defined($interval);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $interval 0 119 119
1155  
1156 119 my $key = $self->_dtd_audit_key();
1157 # The key comes from the request path, so cap the table: a server that sees
1158 # an unbounded number of paths must not accumulate entries forever.
1159 119 ▶ %DTD_WARNING_STATE = () if(scalar(keys %DTD_WARNING_STATE) >= $DTD_WARNING_MAX_KEYS);
Branch: 1 branch
BranchTrueFalseTotal
if scalar keys %CGI::Info::DTD_WARNING_STATE >= $DTD_WARNING_MAX_KEYS 1 118 119
1160  
1161 119 my $now = time();
1162 119 my $state = $DTD_WARNING_STATE{$key};
1163 119 ▶ if(($interval > 0) && defined($state) && $state->{last} && (($now - $state->{last}) < $interval)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($interval > 0 and defined $state and $state->{"last"} and $now - $state->{"last"} < $interval) 11 108 119
Condition88%8/9
$interval > 0 and defined $state and $state->{"last"} and $now - $state->{"last"} < $interval
!ll&&!rl&&r
107111
$interval > 0 and defined $state and $state->{"last"}
!ll&&!rl&&r
107012
$interval > 0 and defined $state
!ll&&!rl&&r
105212
MC/DC75%3/4
$interval > 0 and defined $state and $state->{"last"} and $now - $state->{"last"} < $interval
$interval > 0 defined $state $state->{"last"} $now - $state->{"last"} < $interval
Truth table80%4/5
A and B and C and D
A= $interval > 0B= defined $stateC= $state->{"last"}D= $now - $state->{"last"} < $interval
ABCDresult
0XXX0
10XX0
110X0
11100
11111
1164 11 $state->{suppressed}++;
1165 11 return;
1166 }
1167  
1168 108 ▶ my $suppressed = defined($state) ? $state->{suppressed} : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $state ? : 4 104 108
1169 108 $DTD_WARNING_STATE{$key} = { last => $now, suppressed => 0 };
1170  
1171 108 ▶ my $earlier = $suppressed
Branch: 2 branches
BranchTrueFalseTotal
$suppressed ? : 2 106 108
$suppressed == 1 ? : 1 1 2
1172 ? " ($suppressed earlier declaration" . (($suppressed == 1) ? '' : 's') . ' not logged)'
1173 : '';
1174 108 $self->_warn("XML $declaration declaration allowed by allow_dtd$earlier");
1175  
1176 108 return;
1177 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1178  
1179 836 ▶sub params {
Subroutine params: called CC=149 SCAR=52.2
Pod documented
1180 836 my $self = shift;
1181  
1182 836 my $params = Params::Get::get_params(undef, @_);
1183 836 my $overrides = $self->_per_call_limits($params);
1184  
1185 # Localise the limit slots so per-call values apply to the rest of this
1186 # call (including _multipart_data()) and are restored on return.
1187 local $self->{max_body_size} = exists($overrides->{max_body_size})
1188 832 ▶ ? $overrides->{max_body_size} : $self->{max_body_size};
Branch: 1 branch
BranchTrueFalseTotal
exists $overrides->{'max_body_size'} ? : 2 830 832
1189 local $self->{max_params} = exists($overrides->{max_params})
1190 832 ▶ ? $overrides->{max_params} : $self->{max_params};
Branch: 1 branch
BranchTrueFalseTotal
exists $overrides->{'max_params'} ? : 5 827 832
1191 local $self->{max_parts} = exists($overrides->{max_parts})
1192 832 ▶ ? $overrides->{max_parts} : $self->{max_parts};
Branch: 1 branch
BranchTrueFalseTotal
exists $overrides->{'max_parts'} ? : 2 830 832
1193 local $self->{max_part_headers} = exists($overrides->{max_part_headers})
1194 832 ▶ ? $overrides->{max_part_headers} : $self->{max_part_headers};
Branch: 1 branch
BranchTrueFalseTotal
exists $overrides->{'max_part_headers'} ? : 1 831 832
1195 local $self->{max_nesting_depth} = exists($overrides->{max_nesting_depth})
1196 832 ▶ ? $overrides->{max_nesting_depth} : $self->{max_nesting_depth};
Branch: 1 branch
BranchTrueFalseTotal
exists $overrides->{'max_nesting_depth'} ? : 3 829 832
1197  
1198 832 my $limits_key = $self->_limits_key();
1199  
1200 832 ▶ if((defined($self->{paramref})) && (defined($self->{_limits_key})) && ($self->{_limits_key} eq $limits_key) && ((!defined($params->{'allow'})) || defined($self->{allow}) && ($params->{'allow'} eq $self->{allow}))) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"paramref"} and defined $self->{"_limits_key"} and $self->{"_limits_key"} eq $limits_key and !defined($params->{"allow"}) || defined $self->{"allow"} && $params->{"allow"} eq $self->{"allow"}) 190 642 832
Condition93%14/15
defined $self->{"paramref"} and defined $self->{"_limits_key"} and $self->{"_limits_key"} eq $limits_key and !defined($params->{"allow"}) || defined $self->{"allow"} && $params->{"allow"} eq $self->{"allow"}
!ll&&!rl&&r
6402190
defined $self->{"paramref"} and defined $self->{"_limits_key"} and $self->{"_limits_key"} eq $limits_key
!ll&&!rl&&r
6382192
defined $self->{"paramref"} and defined $self->{"_limits_key"}
!ll&&!rl&&r
6380194
not defined $params->{"allow"} or defined $self->{"allow"} and $params->{"allow"} eq $self->{"allow"}
l!l&&r!l&&!r
18822
defined $self->{"allow"} and $params->{"allow"} eq $self->{"allow"}
!ll&&!rl&&r
112
MC/DC83%5/6
defined $self->{"paramref"} and defined $self->{"_limits_key"} and $self->{"_limits_key"} eq $limits_key and !defined($params->{"allow"}) || defined $self->{"allow"} && $params->{"allow"} eq $self->{"allow"}
defined $self->{"paramref"} defined $self->{"_limits_key"} $self->{"_limits_key"} eq $limits_key not defined $params->{"allow"} defined $self->{"allow"} $params->{"allow"} eq $self->{"allow"}
Truth table85%6/7
A and B and C and not(D) or E and F
A= defined $self->{"paramref"}B= defined $self->{"_limits_key"}C= $self->{"_limits_key"} eq $limits_keyD= not defined $params->{"allow"}E= defined $self->{"allow"}F= $params->{"allow"} eq $self->{"allow"}
ABCDEFresult
0XXXXX0
10XXXX0
110XXX0
11100X0
1110100
1111XX1
1110111
1201 190 return $self->{paramref};
1202 }
1203  
1204 642 ▶ if(defined($params->{allow})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{"allow"}) 72 570 642
1205 72 $self->{allow} = $params->{allow};
1206 }
1207 642 ▶ if(defined($params->{upload_dir})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{"upload_dir"}) 10 632 642
1208 10 $self->{upload_dir} = $params->{upload_dir};
1209 }
1210 642 ▶ if(defined($params->{'logger'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{"logger"}) 2 640 642
1211 2 $self->set_logger($params->{'logger'});
1212 }
1213 642 $self->_trace('Entering params');
1214  
1215 # A fresh parse may fail part-way through; do not leave a previous call's
1216 # accepted parameter set (or its limit key) available for a later call.
1217 642 delete $self->{paramref};
1218 642 delete $self->{_limits_key};
1219 642 delete $self->{_limit_exceeded};
1220  
1221 642 my @pairs;
1222 642 my $content_type = $ENV{'CONTENT_TYPE'};
1223 642 my %FORM;
1224  
1225 642 ▶ if((!$ENV{'GATEWAY_INTERFACE'}) || (!$ENV{'REQUEST_METHOD'})) {
Branch: 5 branches
BranchTrueFalseTotal
if (not $ENV{'GATEWAY_INTERFACE'} && $ENV{'REQUEST_METHOD'}) { } 51 591 642
elsif ($ENV{'REQUEST_METHOD'} eq 'GET' or $ENV{'REQUEST_METHOD'} eq 'HEAD') { } 332 259 591
elsif ($ENV{'REQUEST_METHOD'} eq 'POST') { } 238 21 259
elsif ($ENV{'REQUEST_METHOD'} eq 'OPTIONS') { } 7 14 21
elsif ($ENV{'REQUEST_METHOD'} eq 'DELETE') { } 8 6 14
Condition66%2/3
$ENV{'GATEWAY_INTERFACE'} && $ENV{'REQUEST_METHOD'}
!ll&&!rl&&r
510591
MC/DC50%1/2
$ENV{'GATEWAY_INTERFACE'} && $ENV{'REQUEST_METHOD'}
$ENV{'GATEWAY_INTERFACE'} $ENV{'REQUEST_METHOD'}
Truth table66%2/3
A && B
A= $ENV{'GATEWAY_INTERFACE'}B= $ENV{'REQUEST_METHOD'}
ABresult
0X0
100
111
1226 # require IO::Interactive;
1227 # IO::Interactive->import();
1228  
1229 51 ▶ if(@ARGV) {
Branch: 2 branches
BranchTrueFalseTotal
if (@ARGV) { } 45 6 51
elsif ($CGI::Info::stdin_data) { } 0 6 6
1230 45 @pairs = @ARGV;
1231 45 ▶ if(defined($pairs[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $pairs[0]) 45 0 45
1232 45 ▶ if($pairs[0] eq '--robot') {
Branch: 4 branches
BranchTrueFalseTotal
if ($pairs[0] eq '--robot') { } 6 39 45
elsif ($pairs[0] eq '--mobile') { } 7 32 39
elsif ($pairs[0] eq '--search-engine') { } 6 26 32
elsif ($pairs[0] eq '--tablet') { } 6 20 26
1233 6 $self->{is_robot} = 1;
1234 6 shift @pairs;
1235 } elsif($pairs[0] eq '--mobile') {
1236 7 $self->{is_mobile} = 1;
1237 7 shift @pairs;
1238 } elsif($pairs[0] eq '--search-engine') {
1239 6 $self->{is_search_engine} = 1;
1240 6 shift @pairs;
1241 } elsif($pairs[0] eq '--tablet') {
1242 6 $self->{is_tablet} = 1;
1243 6 shift @pairs;
1244 }
1245 }
1246 } elsif($stdin_data) {
1247 # Re-use previously read STDIN (class variable shared across instances)
1248 0 @pairs = split(/\n/, $stdin_data);
1249 }
1250 ▶ } elsif(($ENV{'REQUEST_METHOD'} eq 'GET') || ($ENV{'REQUEST_METHOD'} eq 'HEAD')) {
Condition100%3/3
$ENV{"REQUEST_METHOD"} eq "GET" or $ENV{"REQUEST_METHOD"} eq "HEAD"
l!l&&r!l&&!r
3284259
MC/DC100%2/2
$ENV{"REQUEST_METHOD"} eq "GET" or $ENV{"REQUEST_METHOD"} eq "HEAD"
$ENV{"REQUEST_METHOD"} eq "GET" $ENV{"REQUEST_METHOD"} eq "HEAD"
Truth table100%3/3
A or B
A= $ENV{"REQUEST_METHOD"} eq "GET"B= $ENV{"REQUEST_METHOD"} eq "HEAD"
ABresult
1X1
011
000
1251 332 ▶ if(my $query = $ENV{'QUERY_STRING'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $query = $ENV{'QUERY_STRING'}) { } 323 9 332
1252 323 ▶ if((defined($content_type)) && ($content_type =~ /multipart\/form-data/i)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $content_type and $content_type =~ m[multipart/form-data]i) 4 319 323
Condition66%2/3
defined $content_type and $content_type =~ m[multipart/form-data]i
!ll&&!rl&&r
31904
MC/DC50%1/2
defined $content_type and $content_type =~ m[multipart/form-data]i
defined $content_type $content_type =~ m[multipart/form-data]i
Truth table66%2/3
A and B
A= defined $content_typeB= $content_type =~ m[multipart/form-data]i
ABresult
0X0
100
111
1253 4 ▶ if($ENV{'REMOTE_ADDR'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{'REMOTE_ADDR'}) { } 2 2 4
1254 2 $self->_warn({ warning => "$ENV{REMOTE_ADDR}: Multipart/form-data not supported for GET (query string = $query)" });
1255 } else {
1256 2 $self->_warn('Multipart/form-data not supported for GET');
1257 }
1258 3 $self->status(501); # Not implemented
1259 3 return;
1260 }
1261 319 $query =~ s/\\u0026/\&/g;
1262 319 @pairs = split(/&/, $query);
1263 } else {
1264 9 return;
1265 }
1266 } elsif($ENV{'REQUEST_METHOD'} eq 'POST') {
1267 238 my $content_length = $self->_get_env('CONTENT_LENGTH');
1268 238 ▶ if((!defined($content_length)) || ($content_length =~ /\D/)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $content_length or $content_length =~ /\D/) 12 226 238
Condition100%3/3
not defined $content_length or $content_length =~ /\D/
l!l&&r!l&&!r
93226
MC/DC100%2/2
not defined $content_length or $content_length =~ /\D/
not defined $content_length $content_length =~ /\D/
Truth table100%3/3
not(A) or B
A= not defined $content_lengthB= $content_length =~ /\D/
ABresult
1X1
011
000
1269 12 $self->{status} = 411;
1270 12 return;
1271 }
1272 226 my $body_limit = $self->_body_limit();
1273 226 ▶ if($self->_over_limit($content_length, $body_limit)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_over_limit($content_length, $body_limit)) 13 213 226
1274 # TODO: Design a way to tell the caller to send HTTP
1275 # status 413
1276 13 $self->{status} = 413;
1277 13 $self->_warn('Large upload prohibited');
1278 13 return;
1279 }
1280 213 ▶ if(($self->{max_upload_size} >= 0) && ($content_length > $self->{max_upload_size})) { # Set maximum posts
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"max_upload_size"} >= 0 and $content_length > $self->{"max_upload_size"}) 0 213 213
Condition66%2/3
$self->{"max_upload_size"} >= 0 and $content_length > $self->{"max_upload_size"}
!ll&&!rl&&r
12120
MC/DC0%0/2
$self->{"max_upload_size"} >= 0 and $content_length > $self->{"max_upload_size"}
$self->{"max_upload_size"} >= 0 $content_length > $self->{"max_upload_size"}
Truth table66%2/3
A and B
A= $self->{"max_upload_size"} >= 0B= $content_length > $self->{"max_upload_size"}
ABresult
0X0
100
111
1281 0 $self->{status} = 413;
1282 0 $self->_warn('Large upload prohibited');
1283 0 return;
1284 }
1285 213 ▶ if(defined($stdin_data) && $self->_over_limit(length($stdin_data), $body_limit)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $CGI::Info::stdin_data and $self->_over_limit(length $CGI::Info::stdin_data, $body_limit)) 1 212 213
Condition100%3/3
defined $CGI::Info::stdin_data and $self->_over_limit(length $CGI::Info::stdin_data, $body_limit)
!ll&&!rl&&r
173391
MC/DC100%2/2
defined $CGI::Info::stdin_data and $self->_over_limit(length $CGI::Info::stdin_data, $body_limit)
defined $CGI::Info::stdin_data $self->_over_limit(length $CGI::Info::stdin_data, $body_limit)
Truth table100%3/3
A and B
A= defined $CGI::Info::stdin_dataB= $self->_over_limit(length $CGI::Info::stdin_data, $body_limit)
ABresult
0X0
100
111
1286 1 $self->{status} = 413;
1287 1 $self->_warn('Large upload prohibited');
1288 1 return;
1289 }
1290  
1291 212 ▶ if((!defined($content_type)) || ($content_type =~ /application\/x-www-form-urlencoded/)) {
Branch: 4 branches
BranchTrueFalseTotal
if (not defined $content_type or $content_type =~ m[application/x-www-form-urlencoded]) { } 18 194 212
elsif ($content_type =~ m[multipart/form-data]i) { } 36 158 194
elsif ($content_type =~ m[^\s*(?:(?:text|application)/xml|application/[^/;\s]+\+xml)\s*(?:;.*)?$]i) { } 151 7 158
elsif ($content_type =~ m[application/json]i) { } 5 2 7
Condition100%3/3
not defined $content_type or $content_type =~ m[application/x-www-form-urlencoded]
l!l&&r!l&&!r
315194
MC/DC100%2/2
not defined $content_type or $content_type =~ m[application/x-www-form-urlencoded]
not defined $content_type $content_type =~ m[application/x-www-form-urlencoded]
Truth table100%3/3
not(A) or B
A= not defined $content_typeB= $content_type =~ m[application/x-www-form-urlencoded]
ABresult
1X1
011
000
1292 18 my $buffer;
1293 18 ▶ if($stdin_data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($CGI::Info::stdin_data) { } 14 4 18
1294 14 $buffer = $stdin_data;
1295 } else {
1296 4 ▶ if(read(STDIN, $buffer, $content_length) != $content_length) {
Branch: 1 branch
BranchTrueFalseTotal
if (&CGI::Info::read("STDIN", \$buffer, $content_length) != $content_length) 1 3 4
1297 1 $self->_warn('POST failed: something else may have read STDIN');
1298 }
1299 4 $stdin_data = $buffer;
1300 }
1301 18 @pairs = split(/&/, $buffer);
1302  
1303 # if($ENV{'QUERY_STRING'}) {
1304 # my @getpairs = split(/&/, $ENV{'QUERY_STRING'});
1305 # push(@pairs, @getpairs);
1306 # }
1307 } elsif($content_type =~ /multipart\/form-data/i) {
1308 36 ▶ if(!defined($self->{upload_dir})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"upload_dir"}) 3 33 36
1309 3 ▶ if($ENV{'REMOTE_ADDR'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{'REMOTE_ADDR'}) { } 1 2 3
1310 # This could be an attack
1311 1 $self->_warn({ warning => "$ENV{REMOTE_ADDR}: Attempt to upload a file of $content_length bytes when upload_dir has not been set" });
1312 } else {
1313 2 $self->_warn({ warning => 'Attempt to upload a file when upload_dir has not been set' });
1314 }
1315 2 $self->status(501); # Not implemented
1316 2 return;
1317 }
1318  
1319 # Validate 'upload_dir'
1320 # Ensure the upload directory is safe and accessible
1321 # - Check permissions
1322 # - Validate path to prevent directory traversal attacks
1323 # TODO: Consider using a temporary directory for uploads and moving them later
1324 33 ▶ if(!File::Spec->file_name_is_absolute($self->{upload_dir})) {
Branch: 1 branch
BranchTrueFalseTotal
unless ("File::Spec"->file_name_is_absolute($self->{"upload_dir"})) 5 28 33
1325 5 $self->_warn({
1326 warning => "upload_dir $self->{upload_dir} isn't a full pathname"
1327 });
1328 4 $self->status(500);
1329 4 delete $self->{upload_dir};
1330 4 return;
1331 }
1332 28 ▶ if(!-d $self->{upload_dir}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $self->{"upload_dir"}) 7 21 28
1333 7 $self->_warn({
1334 warning => "upload_dir $self->{upload_dir} isn't a directory"
1335 });
1336 5 $self->status(500);
1337 5 delete $self->{upload_dir};
1338 5 return;
1339 }
1340 21 ▶ if(!-w $self->{upload_dir}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-w $self->{"upload_dir"}) 2 19 21
1341 2 delete $self->{paramref};
1342 2 delete $self->{_limits_key};
1343 2 $self->_warn({
1344 warning => "upload_dir $self->{upload_dir} isn't writeable"
1345 });
1346 1 $self->status(500);
1347 1 delete $self->{upload_dir};
1348 1 return;
1349 }
1350 19 ▶ if(my $problem = $self->_win32_path_problem($self->{'upload_dir'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $problem = $self->_win32_path_problem($self->{"upload_dir"})) 1 18 19
1351 $self->_warn({
1352 1 warning => 'upload_dir ' . $self->{'upload_dir'} . " $problem, so it can't be checked against the temporary areas"
1353 });
1354 1 $self->status(500);
1355 1 delete $self->{upload_dir};
1356 1 return;
1357 }
1358 18 ▶ if(!$self->_in_temp_area($self->{'upload_dir'})) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_in_temp_area($self->{"upload_dir"})) 4 14 18
1359 4 my $root = $self->_temp_area_root($self->{'upload_dir'});
1360 $self->_warn({
1361 warning => defined($root)
1362 ? 'upload_dir ' . $self->{'upload_dir'} . " is the temporary area root $root, not a directory inside it"
1363 4 ▶ : 'upload_dir ' . $self->{'upload_dir'} . " isn't in a temporary area ("
Branch: 1 branch
BranchTrueFalseTotal
defined $root ? : 2 2 4
1364 . join(', ', $self->_temp_areas()) . ')'
1365 });
1366 4 $self->status(500);
1367 4 delete $self->{upload_dir};
1368 4 return;
1369 }
1370 14 ▶ if($content_type =~ /boundary=(\S+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($content_type =~ /boundary=(\S+)$/) 14 0 14
1371 14 @pairs = $self->_multipart_data({
1372 length => $content_length,
1373 boundary => $1
1374 });
1375 12 ▶ return if($self->{_limit_exceeded});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_limit_exceeded"} 6 6 12
1376 }
1377 } elsif($content_type =~ m{^\s*(?:(?:text|application)/xml|application/[^/;\s]+\+xml)\s*(?:;.*)?$}i) {
1378 151 my $buffer;
1379 151 ▶ if($stdin_data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($CGI::Info::stdin_data) { } 9 142 151
1380 9 $buffer = $stdin_data;
1381 } else {
1382 142 ▶ if(read(STDIN, $buffer, $content_length) != $content_length) {
Branch: 1 branch
BranchTrueFalseTotal
if (&CGI::Info::read("STDIN", \$buffer, $content_length) != $content_length) 0 142 142
1383 0 $self->_warn({
1384 warning => 'XML failed: something else may have read STDIN'
1385 });
1386 }
1387 142 $stdin_data = $buffer;
1388 }
1389  
1390 151 my $complexity = $self->_xml_complexity($buffer);
1391 151 ▶ if(defined($complexity->{forbidden})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $complexity->{"forbidden"}) 125 26 151
1392 125 ▶ if(!$self->{allow_dtd}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"allow_dtd"}) 6 119 125
1393 6 $self->status(403);
1394 6 $self->_warn("XML $complexity->{forbidden} declaration blocked");
1395 6 return;
1396 }
1397 # Audit trail: a DTD is only ever accepted because the caller
1398 # opted in, so record that the exception was used.
1399 119 $self->_audit_allowed_dtd($complexity->{forbidden});
1400 }
1401 145 ▶ if($self->_over_limit($complexity->{elements}, $self->{max_params})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_over_limit($complexity->{"elements"}, $self->{"max_params"})) 6 139 145
1402 6 $self->_reject_complexity("more than $self->{max_params} XML elements");
1403 6 return;
1404 }
1405 139 ▶ if($self->_over_limit($complexity->{depth}, $self->{max_nesting_depth})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_over_limit($complexity->{"depth"}, $self->{"max_nesting_depth"})) 4 135 139
1406 4 $self->_reject_complexity("XML nesting deeper than $self->{max_nesting_depth}");
1407 4 return;
1408 }
1409  
1410 135 $FORM{XML} = $buffer;
1411  
1412 135 $self->{paramref} = \%FORM;
1413 135 $self->{_limits_key} = $limits_key;
1414  
1415 135 return \%FORM;
1416 } elsif($content_type =~ /application\/json/i) {
1417 5 ▶ require JSON::MaybeXS && JSON::MaybeXS->import() unless JSON::MaybeXS->can('parse_json');
Branch: 1 branch
BranchTrueFalseTotal
unless "JSON::MaybeXS"->can("parse_json") 5 0 5
Condition33%2/6
'JSON::MaybeXS'->can('parse_json') || require JSON::MaybeXS && 'JSON::MaybeXS'->import
l!l&&r!l&&!r
050
require JSON::MaybeXS and "JSON::MaybeXS"->import
!ll&&!rl&&r
050
MC/DC0%0/3
'JSON::MaybeXS'->can('parse_json') || require JSON::MaybeXS && 'JSON::MaybeXS'->import
'JSON::MaybeXS'->can('parse_json') require JSON::MaybeXS "JSON::MaybeXS"->import
Truth table0%0/4
A || B and C
A= 'JSON::MaybeXS'->can('parse_json')B= require JSON::MaybeXSC= "JSON::MaybeXS"->import
ABCresult
1XX1
0111
00X0
0100
1418 # require JSON::MaybeXS;
1419 # JSON::MaybeXS->import();
1420  
1421 5 my $buffer;
1422  
1423 5 ▶ if($stdin_data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($CGI::Info::stdin_data) { } 4 1 5
1424 4 $buffer = $stdin_data;
1425 } else {
1426 1 ▶ if(read(STDIN, $buffer, $content_length) != $content_length) {
Branch: 1 branch
BranchTrueFalseTotal
if (&CGI::Info::read("STDIN", \$buffer, $content_length) != $content_length) 0 1 1
1427 0 $self->_warn({
1428 warning => 'read failed: something else may have read STDIN'
1429 });
1430 }
1431 1 $stdin_data = $buffer;
1432 }
1433 # JSON::Parse::assert_valid_json($buffer);
1434 # my $paramref = JSON::Parse::parse_json($buffer);
1435 5 my $paramref = decode_json($buffer);
1436 4 foreach my $key(keys(%{$paramref})) {
1437 8 push @pairs, "$key=" . $paramref->{$key};
1438 }
1439 } else {
1440 2 my $buffer;
1441 2 ▶ if($stdin_data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($CGI::Info::stdin_data) { } 1 1 2
1442 1 $buffer = $stdin_data;
1443 } else {
1444 1 ▶ if(read(STDIN, $buffer, $content_length) != $content_length) {
Branch: 1 branch
BranchTrueFalseTotal
if (&CGI::Info::read("STDIN", \$buffer, $content_length) != $content_length) 0 1 1
1445 0 $self->_warn({
1446 warning => 'read failed: something else may have read STDIN'
1447 });
1448 }
1449 1 $stdin_data = $buffer;
1450 }
1451  
1452 2 $self->_warn({
1453 warning => "POST: Invalid or unsupported content type: $content_type: $buffer",
1454 });
1455 }
1456 } elsif($ENV{'REQUEST_METHOD'} eq 'OPTIONS') {
1457 7 $self->{status} = 405;
1458 7 return;
1459 } elsif($ENV{'REQUEST_METHOD'} eq 'DELETE') {
1460 8 $self->{status} = 405;
1461 8 return;
1462 } else {
1463 # TODO: Design a way to tell the caller to send HTTP
1464 # status 501
1465 6 $self->{status} = 501;
1466 $self->_warn({
1467 warning => 'Use POST, GET or HEAD, not ' . $ENV{REQUEST_METHOD}
1468 6 });
1469 }
1470  
1471 404 ▶ if($self->_over_limit(scalar(@pairs), $self->{max_params})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_over_limit(scalar @pairs, $self->{"max_params"})) 3 401 404
1472 3 $self->_reject_complexity("more than $self->{max_params} parameters");
1473 3 return;
1474 }
1475  
1476 401 ▶ unless(scalar @pairs) {
Branch: 1 branch
BranchTrueFalseTotal
unless (scalar @pairs) 20 381 401
1477 20 return;
1478 }
1479  
1480 381 require String::Clean::XSS;
1481 381 String::Clean::XSS->import();
1482 # require String::EscapeCage;
1483 # String::EscapeCage->import();
1484  
1485 381 foreach my $arg (@pairs) {
1486 2085 my($key, $value) = split(/=/, $arg, 2);
1487  
1488 2085 ▶ next unless($key);
Branch: 1 branch
BranchTrueFalseTotal
unless $key 10 2075 2085
1489  
1490 2075 $key =~ s/\0//g; # Strip encoded NUL byte poison
1491 2075 $key =~ s/%00//g; # Strip NUL byte poison
1492 2075 $key =~ s/%([a-fA-F\d][a-fA-F\d])/pack("C", hex($1))/eg;
1493 2075 $key =~ tr/+/ /;
1494 2075 ▶ if(defined($value)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $value) { } 2073 2 2075
1495 2073 $value =~ s/%00//g; # Strip encoded NUL byte poison
1496 2073 $value =~ s/%([a-fA-F\d][a-fA-F\d])/pack("C", hex($1))/eg; # URL-decode (1st pass)
1497 2073 $value =~ s/%([a-fA-F\d][a-fA-F\d])/pack("C", hex($1))/eg; # URL-decode (2nd pass: catches %252F -> %2F -> /)
1498 2073 $value =~ tr/+/ /;
1499 2073 $value =~ s/\0//g; # Strip NUL: %2500 -> %00 -> NUL
1500 2073 $value =~ s/%00//g; # Strip literal %00
1501 } else {
1502 2 $value = '';
1503 }
1504  
1505 2075 ▶ if($self->_over_limit($self->_param_nesting_depth($key), $self->{max_nesting_depth})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_over_limit($self->_param_nesting_depth($key), $self->{"max_nesting_depth"})) 3 2072 2075
1506 3 $self->_reject_complexity("parameter name nesting deeper than $self->{max_nesting_depth}");
1507 3 return;
1508 }
1509  
1510 2072 $key = _sanitise_input($key);
1511  
1512 2072 ▶ if($self->{allow}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"allow"}) 183 1889 2072
1513 # Is this a permitted argument?
1514 183 ▶ if(!exists($self->{allow}->{$key})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $self->{"allow"}{$key}) 31 152 183
1515 31 $self->_info("Discard unallowed argument '$key'");
1516 31 $self->status(422);
1517 31 next; # Skip to the next parameter
1518 }
1519  
1520 # Do we allow any value, or must it be validated?
1521 152 ▶ if(defined(my $schema = $self->{allow}->{$key})) { # Get the schema for this key
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $schema = $self->{"allow"}{$key})) 133 19 152
1522 133 ▶ if(!ref($schema)) {
Branch: 3 branches
BranchTrueFalseTotal
if (not ref $schema) { } 11 122 133
elsif (ref $schema eq 'Regexp') { } 59 63 122
elsif (ref $schema eq 'CODE') { } 28 35 63
1523 # Can only contain one value
1524 11 ▶ if($value ne $schema) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value ne $schema) 5 6 11
1525 5 $self->_info("Block $key = $value");
1526 5 $self->status(422);
1527 5 next; # Skip to the next parameter
1528 }
1529 } elsif(ref($schema) eq 'Regexp') {
1530 59 ▶ if($value !~ $schema) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($value =~ /$schema/) 30 29 59
1531 # Simple regex
1532 30 $self->_info("Block $key = $value");
1533 30 $self->status(422);
1534 30 next; # Skip to the next parameter
1535 }
1536 } elsif(ref($schema) eq 'CODE') {
1537 28 ▶ unless($schema->($key, $value, $self)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&$schema($key, $value, $self)) 11 15 26
1538 11 $self->_info("Block $key = $value");
1539 11 next;
1540 }
1541 } else {
1542 # Set of rules
1543 35 eval {
1544 $value = Params::Validate::Strict::validate_strict({
1545 schema => { $key => $schema },
1546 args => { $key => $value },
1547 unknown_parameter_handler => 'die',
1548 35 logger => $self->{'logger'}
1549 });
1550 };
1551 35 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 9 26 35
1552 9 $self->_info("Block $key = $value: $@");
1553 9 $self->status(422);
1554 9 next; # Skip to the next parameter
1555 }
1556 26 ▶ if(scalar keys %{$value}) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %{$value;}) { } 26 0 26
1557 26 $value = $value->{$key};
1558 } else {
1559 0 $self->_info("Block $key = $value");
1560 0 $self->status(422);
1561 0 next; # Skip to the next parameter
1562 }
1563 }
1564 }
1565 }
1566  
1567 # if($self->{expect} && (List::Util::none { $_ eq $key } @{$self->{expect}})) {
1568 # next;
1569 # }
1570 1984 my $orig_value = $value;
1571 1984 $value = _sanitise_input($value);
1572  
1573 # WAF: inspect all methods (GET and POST) for injection patterns.
1574 # Previously gated on GET only, which allowed POST to bypass all checks.
1575 {
1576 # ($value =~ /\/AND\/.++\(SELECT\//) || # United/**/States)/**/AND/**/(SELECT/**/6734/**/FROM/**/(SELECT(SLEEP(5)))lRNi)/**/AND/**/(8984=8984
1577 # From http://www.symantec.com/connect/articles/detection-sql-injection-and-cross-site-scripting-attacks
1578 # Facebook FBCLID can have "--"
1579  
1580 # Pre-filter: only run quote-based regexes if value contains injection chars.
1581  
1582 # Compute pre-filter flags from orig_value so quotes stripped by
1583 # convert_XSS don't cause injection patterns to be missed
1584  
1585 1984 ▶ my $has_quote = index($orig_value, "'") >= 0 || index($orig_value, '%27') >= 0;
Condition66%2/3
index($orig_value, q[']) != -1 || index($orig_value, '%27') != -1
l!l&&r!l&&!r
2001964
MC/DC50%1/2
index($orig_value, q[']) != -1 || index($orig_value, '%27') != -1
index($orig_value, q[']) != -1 index($orig_value, '%27') != -1
Truth table66%2/3
A || B
A= index($orig_value, q[']) != -1B= index($orig_value, '%27') != -1
ABresult
1X1
011
000
1586 1984 ▶ my $has_hash = index($orig_value, '#') >= 0 || index($orig_value, '%23') >= 0;
Condition33%1/3
index($orig_value, '#') != -1 || index($orig_value, '%23') != -1
l!l&&r!l&&!r
001984
MC/DC0%0/2
index($orig_value, '#') != -1 || index($orig_value, '%23') != -1
index($orig_value, '#') != -1 index($orig_value, '%23') != -1
Truth table33%1/3
A || B
A= index($orig_value, '#') != -1B= index($orig_value, '%23') != -1
ABresult
1X1
011
000
1587 1984 ▶ my $has_equals = index($orig_value, '=') >= 0 || index($orig_value, '%3D') >= 0;
Condition66%2/3
index($orig_value, '=') != -1 || index($orig_value, '%3D') != -1
l!l&&r!l&&!r
3601948
MC/DC50%1/2
index($orig_value, '=') != -1 || index($orig_value, '%3D') != -1
index($orig_value, '=') != -1 index($orig_value, '%3D') != -1
Truth table66%2/3
A || B
A= index($orig_value, '=') != -1B= index($orig_value, '%3D') != -1
ABresult
1X1
011
000
1588 1984 ▶ my $has_semi = index($orig_value, ';') >= 0 || index($orig_value, '%3B') >= 0;
Condition66%2/3
index($orig_value, ';') != -1 || index($orig_value, '%3B') != -1
l!l&&r!l&&!r
601978
MC/DC50%1/2
index($orig_value, ';') != -1 || index($orig_value, '%3B') != -1
index($orig_value, ';') != -1 index($orig_value, '%3B') != -1
Truth table66%2/3
A || B
A= index($orig_value, ';') != -1B= index($orig_value, '%3B') != -1
ABresult
1X1
011
000
1589 1984 my $has_dash = index($orig_value, '--') >= 0;
1590  
1591 # All WAF patterns run on $orig_value (pre-XSS-sanitisation)
1592 # convert_XSS encodes ', =, < etc. as HTML entities, which would hide
1593 # injection patterns from the WAF if we checked $value instead.
1594 1984 ▶ if($has_quote || $has_hash || ($has_equals && $has_dash)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_quote or $has_hash or $has_equals and $has_dash) 24 1960 1984
Condition88%8/9
$has_quote or $has_hash or $has_equals and $has_dash
l!l&&r!l&&!r
2041960
$has_quote or $has_hash
l!l&&r!l&&!r
2001964
$has_equals and $has_dash
!ll&&!rl&&r
1944164
MC/DC75%3/4
$has_quote or $has_hash or $has_equals and $has_dash
$has_quote $has_hash $has_equals $has_dash
Truth table80%4/5
A or B or C and D
A= $has_quoteB= $has_hashC= $has_equalsD= $has_dash
ABCDresult
1XXX1
01XX1
00111
000X0
00100
1595 24 ▶ if(($orig_value =~ /(?:%27|'|%23|#)/i) ||
Branch: 1 branch
BranchTrueFalseTotal
if ($orig_value =~ /(?:%27|'|%23|#)/i or $has_equals and $has_quote || $has_semi || $has_dash and $orig_value =~ /(?:%3D|=)[^-]*+(?:%27|'|--|%3B|;)/i or $has_quote and $orig_value =~ /\w*(?:%27|')(?:%6F|o|%4F)(?:%72|r|%52)\s*(?:OR|AND|UNION|SELECT|--)/xi or $has_quote and $orig_value =~ /(?:%27|')union/xi) 24 0 24
Condition29%8/27
$orig_value =~ /(?:%27|'|%23|#)/i or $has_equals and $has_quote || $has_semi || $has_dash and $orig_value =~ /(?:%3D|=)[^-]*+(?:%27|'|--|%3B|;)/i or $has_quote and $orig_value =~ /\w*(?:%27|')(?:%6F|o|%4F)(?:%72|r|%52)\s*(?:OR|AND|UNION|SELECT|--)/xi or $has_quote and $orig_value =~ /(?:%27|')union/xi
l!l&&r!l&&!r
2400
$orig_value =~ /(?:%27|'|%23|#)/i or $has_equals and $has_quote || $has_semi || $has_dash and $orig_value =~ /(?:%3D|=)[^-]*+(?:%27|'|--|%3B|;)/i or $has_quote and $orig_value =~ /\w*(?:%27|')(?:%6F|o|%4F)(?:%72|r|%52)\s*(?:OR|AND|UNION|SELECT|--)/xi
l!l&&r!l&&!r
2400
$orig_value =~ /(?:%27|'|%23|#)/i or $has_equals and $has_quote || $has_semi || $has_dash and $orig_value =~ /(?:%3D|=)[^-]*+(?:%27|'|--|%3B|;)/i
l!l&&r!l&&!r
2040
$has_equals and $has_quote || $has_semi || $has_dash and $orig_value =~ /(?:%3D|=)[^-]*+(?:%27|'|--|%3B|;)/i
!ll&&!rl&&r
004
$has_equals and $has_quote || $has_semi || $has_dash
!ll&&!rl&&r
004
$has_quote or $has_semi or $has_dash
l!l&&r!l&&!r
040
$has_quote or $has_semi
l!l&&r!l&&!r
004
$has_quote and $orig_value =~ /\w*(?:%27|')(?:%6F|o|%4F)(?:%72|r|%52)\s*(?:OR|AND|UNION|SELECT|--)/xi
!ll&&!rl&&r
000
$has_quote and $orig_value =~ /(?:%27|')union/xi
!ll&&!rl&&r
000
MC/DC0%0/10
$orig_value =~ /(?:%27|'|%23|#)/i or $has_equals and $has_quote || $has_semi || $has_dash and $orig_value =~ /(?:%3D|=)[^-]*+(?:%27|'|--|%3B|;)/i or $has_quote and $orig_value =~ /\w*(?:%27|')(?:%6F|o|%4F)(?:%72|r|%52)\s*(?:OR|AND|UNION|SELECT|--)/xi or $has_quote and $orig_value =~ /(?:%27|')union/xi
$orig_value =~ /(?:%27|'|%23|#)/i $has_equals $has_quote $has_semi $has_dash $orig_value =~ /(?:%3D|=)[^-]*+(?:%27|'|--|%3B|;)/i $has_quote $orig_value =~ /\w*(?:%27|')(?:%6F|o|%4F)(?:%72|r|%52)\s*(?:OR|AND|UNION|SELECT|--)/xi $has_quote $orig_value =~ /(?:%27|')union/xi
Truth table5%2/39
A or B and C or D or E and F or G and H or I and J
A= $orig_value =~ /(?:%27|'|%23|#)/iB= $has_equalsC= $has_quoteD= $has_semiE= $has_dashF= $orig_value =~ /(?:%3D|=)[^-]*+(?:%27|'|--|%3B|;)/iG= $has_quoteH= $orig_value =~ /\w*(?:%27|')(?:%6F|o|%4F)(?:%72|r|%52)\s*(?:OR|AND|UNION|SELECT|--)/xiI= $has_quoteJ= $orig_value =~ /(?:%27|')union/xi
ABCDEFGHIJresult
1XXXXXXXXX1
011XX1XXXX1
0101X1XXXX1
010011XXXX1
00XXXX11XX1
01000X11XX1
011XX011XX1
0101X011XX1
01001011XX1
00XXXX0X111
00XXXX10111
01000X0X111
01000X10111
011XX00X111
011XX010111
0101X00X111
0101X010111
0100100X111
01001010111
00XXXX0X0X0
00XXXX0X100
00XXXX100X0
00XXXX10100
01000X0X0X0
01000X0X100
01000X100X0
01000X10100
011XX00X0X0
011XX00X100
011XX0100X0
011XX010100
0101X00X0X0
0101X00X100
0101X0100X0
0101X010100
0100100X0X0
0100100X100
010010100X0
01001010100
1596 (($has_equals && ($has_quote || $has_semi || $has_dash)) &&
1597 $orig_value =~ /(?:%3D|=)[^-]*+(?:%27|'|--|%3B|;)/i) ||
1598 ($has_quote &&
1599 # Detect 'or'-style injection: word + quote + url-encoded or literal 'or' + SQL keyword.
1600 # (?:%6F|o|%4F) = 'o', (?:%72|r|%52) = 'r', both case-folded via /i.
1601 $orig_value =~ /\w*(?:%27|')(?:%6F|o|%4F)(?:%72|r|%52)\s*(?:OR|AND|UNION|SELECT|--)/ix) ||
1602 ($has_quote &&
1603 $orig_value =~ /(?:%27|')union/ix)) {
1604 24 $self->status(403);
1605 24 ▶ if($ENV{'REMOTE_ADDR'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{'REMOTE_ADDR'}) { } 5 19 24
1606 5 $self->_warn($ENV{'REMOTE_ADDR'} . ": SQL injection attempt blocked for '$key=$orig_value'");
1607 } else {
1608 19 $self->_warn("SQL injection attempt blocked for '$key=$orig_value'");
1609 }
1610 24 return;
1611 }
1612 }
1613  
1614 1960 ▶ my $has_select = index($orig_value, 'SELECT') >= 0 || index($orig_value, 'select') >= 0;
Condition66%2/3
index($orig_value, 'SELECT') != -1 || index($orig_value, 'select') != -1
l!l&&r!l&&!r
801952
MC/DC50%1/2
index($orig_value, 'SELECT') != -1 || index($orig_value, 'select') != -1
index($orig_value, 'SELECT') != -1 index($orig_value, 'select') != -1
Truth table66%2/3
A || B
A= index($orig_value, 'SELECT') != -1B= index($orig_value, 'select') != -1
ABresult
1X1
011
000
1615 1960 my $has_dump = index($orig_value, 'var_dump') >= 0;
1616 1960 my $has_exec = index($orig_value, 'exec') >= 0;
1617 1960 my $has_or = index($orig_value, ' OR ') >= 0;
1618 1960 my $has_and = index($orig_value, ' AND ') >= 0;
1619 1960 ▶ my $has_slash = index($orig_value, '/**/') >= 0 || index($orig_value, '/AND/') >= 0;
Condition66%2/3
index($orig_value, '/**/') != -1 || index($orig_value, '/AND/') != -1
l!l&&r!l&&!r
201958
MC/DC50%1/2
index($orig_value, '/**/') != -1 || index($orig_value, '/AND/') != -1
index($orig_value, '/**/') != -1 index($orig_value, '/AND/') != -1
Truth table66%2/3
A || B
A= index($orig_value, '/**/') != -1B= index($orig_value, '/AND/') != -1
ABresult
1X1
011
000
1620  
1621 1960 ▶ if(# \b anchors prevent matching inside longer words.
Branch: 1 branch
BranchTrueFalseTotal
if ($has_select and $orig_value =~ /\bselect\b.{1,500}?\bfrom\b/is or $has_and and $orig_value =~ /\sAND\s1=1/xi or $has_or and $orig_value =~ /\bOR\s+\d+\s*=\s*\d+/i or $has_or and $has_and and $orig_value =~ /\sOR\s.{1,500}?\sAND\s/ or $has_slash and $orig_value =~ m[/\*\*/ORDER/\*\*/BY/\*\*]xi or $has_dump and $orig_value =~ /var_dump[^m]*+md5/ or $has_slash and $has_select and $orig_value =~ m[/AND/[^(]*+\(SELECT/] or $has_exec and $orig_value =~ /exec[\s+]++[sx]p\w+/xi) 18 1942 1960
Condition80%41/51
$has_select and $orig_value =~ /\bselect\b.{1,500}?\bfrom\b/is or $has_and and $orig_value =~ /\sAND\s1=1/xi or $has_or and $orig_value =~ /\bOR\s+\d+\s*=\s*\d+/i or $has_or and $has_and and $orig_value =~ /\sOR\s.{1,500}?\sAND\s/ or $has_slash and $orig_value =~ m[/\*\*/ORDER/\*\*/BY/\*\*]xi or $has_dump and $orig_value =~ /var_dump[^m]*+md5/ or $has_slash and $has_select and $orig_value =~ m[/AND/[^(]*+\(SELECT/] or $has_exec and $orig_value =~ /exec[\s+]++[sx]p\w+/xi
l!l&&r!l&&!r
1441942
$has_select and $orig_value =~ /\bselect\b.{1,500}?\bfrom\b/is or $has_and and $orig_value =~ /\sAND\s1=1/xi or $has_or and $orig_value =~ /\bOR\s+\d+\s*=\s*\d+/i or $has_or and $has_and and $orig_value =~ /\sOR\s.{1,500}?\sAND\s/ or $has_slash and $orig_value =~ m[/\*\*/ORDER/\*\*/BY/\*\*]xi or $has_dump and $orig_value =~ /var_dump[^m]*+md5/ or $has_slash and $has_select and $orig_value =~ m[/AND/[^(]*+\(SELECT/]
l!l&&r!l&&!r
1401946
$has_select and $orig_value =~ /\bselect\b.{1,500}?\bfrom\b/is or $has_and and $orig_value =~ /\sAND\s1=1/xi or $has_or and $orig_value =~ /\bOR\s+\d+\s*=\s*\d+/i or $has_or and $has_and and $orig_value =~ /\sOR\s.{1,500}?\sAND\s/ or $has_slash and $orig_value =~ m[/\*\*/ORDER/\*\*/BY/\*\*]xi or $has_dump and $orig_value =~ /var_dump[^m]*+md5/
l!l&&r!l&&!r
1311946
$has_select and $orig_value =~ /\bselect\b.{1,500}?\bfrom\b/is or $has_and and $orig_value =~ /\sAND\s1=1/xi or $has_or and $orig_value =~ /\bOR\s+\d+\s*=\s*\d+/i or $has_or and $has_and and $orig_value =~ /\sOR\s.{1,500}?\sAND\s/ or $has_slash and $orig_value =~ m[/\*\*/ORDER/\*\*/BY/\*\*]xi
l!l&&r!l&&!r
1211947
$has_select and $orig_value =~ /\bselect\b.{1,500}?\bfrom\b/is or $has_and and $orig_value =~ /\sAND\s1=1/xi or $has_or and $orig_value =~ /\bOR\s+\d+\s*=\s*\d+/i or $has_or and $has_and and $orig_value =~ /\sOR\s.{1,500}?\sAND\s/
l!l&&r!l&&!r
931948
$has_select and $orig_value =~ /\bselect\b.{1,500}?\bfrom\b/is or $has_and and $orig_value =~ /\sAND\s1=1/xi or $has_or and $orig_value =~ /\bOR\s+\d+\s*=\s*\d+/i
l!l&&r!l&&!r
721951
$has_select and $orig_value =~ /\bselect\b.{1,500}?\bfrom\b/is or $has_and and $orig_value =~ /\sAND\s1=1/xi
l!l&&r!l&&!r
521953
$has_select and $orig_value =~ /\bselect\b.{1,500}?\bfrom\b/is
!ll&&!rl&&r
195235
$has_and and $orig_value =~ /\sAND\s1=1/xi
!ll&&!rl&&r
194942
$has_or and $orig_value =~ /\bOR\s+\d+\s*=\s*\d+/i
!ll&&!rl&&r
194832
$has_or and $has_and and $orig_value =~ /\sOR\s.{1,500}?\sAND\s/
!ll&&!rl&&r
194803
$has_or and $has_and
!ll&&!rl&&r
194803
$has_slash and $orig_value =~ m[/\*\*/ORDER/\*\*/BY/\*\*]xi
!ll&&!rl&&r
194701
$has_dump and $orig_value =~ /var_dump[^m]*+md5/
!ll&&!rl&&r
194601
$has_slash and $has_select and $orig_value =~ m[/AND/[^(]*+\(SELECT/]
!ll&&!rl&&r
194600
$has_slash and $has_select
!ll&&!rl&&r
194600
$has_exec and $orig_value =~ /exec[\s+]++[sx]p\w+/xi
!ll&&!rl&&r
194204
MC/DC0%0/18
$has_select and $orig_value =~ /\bselect\b.{1,500}?\bfrom\b/is or $has_and and $orig_value =~ /\sAND\s1=1/xi or $has_or and $orig_value =~ /\bOR\s+\d+\s*=\s*\d+/i or $has_or and $has_and and $orig_value =~ /\sOR\s.{1,500}?\sAND\s/ or $has_slash and $orig_value =~ m[/\*\*/ORDER/\*\*/BY/\*\*]xi or $has_dump and $orig_value =~ /var_dump[^m]*+md5/ or $has_slash and $has_select and $orig_value =~ m[/AND/[^(]*+\(SELECT/] or $has_exec and $orig_value =~ /exec[\s+]++[sx]p\w+/xi
too many conditions
1622 # {1,500}? is lazy+bounded: avoids catastrophic backtracking on
1623 # "SELECT aaaa...aaaa" (no FROM) while still catching real queries.
1624 ($has_select && $orig_value =~ /\bselect\b.{1,500}?\bfrom\b/is) ||
1625 ($has_and && $orig_value =~ /\sAND\s1=1/ix) ||
1626 # Numeric tautology without quotes: OR 1=1, OR 2=2, etc.
1627 ($has_or && $orig_value =~ /\bOR\s+\d+\s*=\s*\d+/i) ||
1628 # Bounded lazy .{1,500}? avoids backtracking on "OR aaaa..." with no AND.
1629 ($has_or && $has_and && $orig_value =~ /\sOR\s.{1,500}?\sAND\s/) ||
1630 ($has_slash && $orig_value =~ /\/\*\*\/ORDER\/\*\*\/BY\/\*\*/ix) ||
1631 ($has_dump && $orig_value =~ /var_dump[^m]*+md5/) ||
1632 ($has_slash && $has_select && $orig_value =~ /\/AND\/[^(]*+\(SELECT\//) ||
1633 ($has_exec && $orig_value =~ /exec[\s+]++[sx]p\w+/ix)) {
1634 18 $self->status(403);
1635 18 ▶ if($ENV{'REMOTE_ADDR'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{'REMOTE_ADDR'}) { } 6 12 18
1636 6 $self->_warn($ENV{'REMOTE_ADDR'} . ": SQL injection attempt blocked for '$key=$orig_value'");
1637 } else {
1638 12 $self->_warn("SQL injection attempt blocked for '$key=$orig_value'");
1639 }
1640 18 return;
1641 }
1642  
1643 1942 ▶ if(my $agent = $ENV{'HTTP_USER_AGENT'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $agent = $ENV{"HTTP_USER_AGENT"}) 36 1906 1942
1644 # Bounded lazy .{1,500}? separates SQL keyword pairs without catastrophic backtracking.
1645 # Possessive .++ would consume the trailing anchor — never match. Unbounded .+ risks ReDoS.
1646 36 ▶ if(($agent =~ /\bSELECT\b.{1,500}?\bAND\b/i) || ($agent =~ /\bORDER\s+BY\b/i) || ($agent =~ /\bOR\s+NOT\b/i) || ($agent =~ /\bAND\b\s+\d+=\d+/) || ($agent =~ /\bTHEN\b.{1,300}?\bELSE\b.{1,300}?\bEND\b/i) || ($agent =~ /\bAND\b.{1,500}?\bSELECT\b/i) || ($agent =~ /\sAND\s.{1,500}?\sAND\s/)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($agent =~ /\bSELECT\b.{1,500}?\bAND\b/i or $agent =~ /\bORDER\s+BY\b/i or $agent =~ /\bOR\s+NOT\b/i or $agent =~ /\bAND\b\s+\d+=\d+/ or $agent =~ /\bTHEN\b.{1,300}?\bELSE\b.{1,300}?\bEND\b/i or $agent =~ /\bAND\b.{1,500}?\bSELECT\b/i or $agent =~ /\sAND\s.{1,500}?\sAND\s/) 3 33 36
Condition72%13/18
$agent =~ /\bSELECT\b.{1,500}?\bAND\b/i or $agent =~ /\bORDER\s+BY\b/i or $agent =~ /\bOR\s+NOT\b/i or $agent =~ /\bAND\b\s+\d+=\d+/ or $agent =~ /\bTHEN\b.{1,300}?\bELSE\b.{1,300}?\bEND\b/i or $agent =~ /\bAND\b.{1,500}?\bSELECT\b/i or $agent =~ /\sAND\s.{1,500}?\sAND\s/
l!l&&r!l&&!r
3033
$agent =~ /\bSELECT\b.{1,500}?\bAND\b/i or $agent =~ /\bORDER\s+BY\b/i or $agent =~ /\bOR\s+NOT\b/i or $agent =~ /\bAND\b\s+\d+=\d+/ or $agent =~ /\bTHEN\b.{1,300}?\bELSE\b.{1,300}?\bEND\b/i or $agent =~ /\bAND\b.{1,500}?\bSELECT\b/i
l!l&&r!l&&!r
3033
$agent =~ /\bSELECT\b.{1,500}?\bAND\b/i or $agent =~ /\bORDER\s+BY\b/i or $agent =~ /\bOR\s+NOT\b/i or $agent =~ /\bAND\b\s+\d+=\d+/ or $agent =~ /\bTHEN\b.{1,300}?\bELSE\b.{1,300}?\bEND\b/i
l!l&&r!l&&!r
3033
$agent =~ /\bSELECT\b.{1,500}?\bAND\b/i or $agent =~ /\bORDER\s+BY\b/i or $agent =~ /\bOR\s+NOT\b/i or $agent =~ /\bAND\b\s+\d+=\d+/
l!l&&r!l&&!r
3033
$agent =~ /\bSELECT\b.{1,500}?\bAND\b/i or $agent =~ /\bORDER\s+BY\b/i or $agent =~ /\bOR\s+NOT\b/i
l!l&&r!l&&!r
3033
$agent =~ /\bSELECT\b.{1,500}?\bAND\b/i or $agent =~ /\bORDER\s+BY\b/i
l!l&&r!l&&!r
2133
MC/DC28%2/7
$agent =~ /\bSELECT\b.{1,500}?\bAND\b/i or $agent =~ /\bORDER\s+BY\b/i or $agent =~ /\bOR\s+NOT\b/i or $agent =~ /\bAND\b\s+\d+=\d+/ or $agent =~ /\bTHEN\b.{1,300}?\bELSE\b.{1,300}?\bEND\b/i or $agent =~ /\bAND\b.{1,500}?\bSELECT\b/i or $agent =~ /\sAND\s.{1,500}?\sAND\s/
$agent =~ /\bSELECT\b.{1,500}?\bAND\b/i $agent =~ /\bORDER\s+BY\b/i $agent =~ /\bOR\s+NOT\b/i $agent =~ /\bAND\b\s+\d+=\d+/ $agent =~ /\bTHEN\b.{1,300}?\bELSE\b.{1,300}?\bEND\b/i $agent =~ /\bAND\b.{1,500}?\bSELECT\b/i $agent =~ /\sAND\s.{1,500}?\sAND\s/
Truth table37%3/8
A or B or C or D or E or F or G
A= $agent =~ /\bSELECT\b.{1,500}?\bAND\b/iB= $agent =~ /\bORDER\s+BY\b/iC= $agent =~ /\bOR\s+NOT\b/iD= $agent =~ /\bAND\b\s+\d+=\d+/E= $agent =~ /\bTHEN\b.{1,300}?\bELSE\b.{1,300}?\bEND\b/iF= $agent =~ /\bAND\b.{1,500}?\bSELECT\b/iG= $agent =~ /\sAND\s.{1,500}?\sAND\s/
ABCDEFGresult
1XXXXXX1
01XXXXX1
001XXXX1
0001XXX1
00001XX1
000001X1
00000011
00000000
1647 3 $self->status(403);
1648 3 ▶ if($ENV{'REMOTE_ADDR'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{'REMOTE_ADDR'}) { } 2 1 3
1649 2 $self->_warn($ENV{'REMOTE_ADDR'} . ": SQL injection attempt blocked for '$agent'");
1650 } else {
1651 1 $self->_warn("SQL injection attempt blocked for '$agent'");
1652 }
1653 3 return;
1654 }
1655 }
1656  
1657 # XSS detection using [^>]+ instead of .+ or .++ :
1658 # - [^>]+ stops naturally at '>' — no backtracking, no ReDoS.
1659 # - [^>] also matches '\n', so multi-line payloads like
1660 # "<img\nsrc=x\nonerror=alert(1)>" are caught without /s.
1661 # - Replaces both the old [^\n]+ (stopped at newline — bypass)
1662 # and the broken .++ (possessive consumed '>' — never matched).
1663 1939 ▶ if(($value =~ /(?:%3C|<)(?:%2F|\/)*[a-z0-9%]+(?:%3E|>)/ix) ||
Branch: 1 branch
BranchTrueFalseTotal
if ($value =~ m[(?:%3C|<)(?:%2F|/)*[a-z0-9%]+(?:%3E|>)]xi or $value =~ /(?:%3C|<)[^>]+(?:%3E|>)/i or $orig_value =~ m[(?:%3C|<)(?:%2F|/)*[a-z0-9%]+(?:%3E|>)]xi or $orig_value =~ /(?:%3C|<)[^>]+(?:%3E|>)/i) 22 1917 1939
Condition66%6/9
$value =~ m[(?:%3C|<)(?:%2F|/)*[a-z0-9%]+(?:%3E|>)]xi or $value =~ /(?:%3C|<)[^>]+(?:%3E|>)/i or $orig_value =~ m[(?:%3C|<)(?:%2F|/)*[a-z0-9%]+(?:%3E|>)]xi or $orig_value =~ /(?:%3C|<)[^>]+(?:%3E|>)/i
l!l&&r!l&&!r
1751917
$value =~ m[(?:%3C|<)(?:%2F|/)*[a-z0-9%]+(?:%3E|>)]xi or $value =~ /(?:%3C|<)[^>]+(?:%3E|>)/i or $orig_value =~ m[(?:%3C|<)(?:%2F|/)*[a-z0-9%]+(?:%3E|>)]xi
l!l&&r!l&&!r
0171922
$value =~ m[(?:%3C|<)(?:%2F|/)*[a-z0-9%]+(?:%3E|>)]xi or $value =~ /(?:%3C|<)[^>]+(?:%3E|>)/i
l!l&&r!l&&!r
001939
MC/DC50%2/4
$value =~ m[(?:%3C|<)(?:%2F|/)*[a-z0-9%]+(?:%3E|>)]xi or $value =~ /(?:%3C|<)[^>]+(?:%3E|>)/i or $orig_value =~ m[(?:%3C|<)(?:%2F|/)*[a-z0-9%]+(?:%3E|>)]xi or $orig_value =~ /(?:%3C|<)[^>]+(?:%3E|>)/i
$value =~ m[(?:%3C|<)(?:%2F|/)*[a-z0-9%]+(?:%3E|>)]xi $value =~ /(?:%3C|<)[^>]+(?:%3E|>)/i $orig_value =~ m[(?:%3C|<)(?:%2F|/)*[a-z0-9%]+(?:%3E|>)]xi $orig_value =~ /(?:%3C|<)[^>]+(?:%3E|>)/i
Truth table60%3/5
A or B or C or D
A= $value =~ m[(?:%3C|<)(?:%2F|/)*[a-z0-9%]+(?:%3E|>)]xiB= $value =~ /(?:%3C|<)[^>]+(?:%3E|>)/iC= $orig_value =~ m[(?:%3C|<)(?:%2F|/)*[a-z0-9%]+(?:%3E|>)]xiD= $orig_value =~ /(?:%3C|<)[^>]+(?:%3E|>)/i
ABCDresult
1XXX1
01XX1
001X1
00011
00000
1664 ($value =~ /(?:%3C|<)[^>]+(?:%3E|>)/i) ||
1665 ($orig_value =~ /(?:%3C|<)(?:%2F|\/)*[a-z0-9%]+(?:%3E|>)/ix) ||
1666 ($orig_value =~ /(?:%3C|<)[^>]+(?:%3E|>)/i)) {
1667 22 $self->status(403);
1668 22 $self->_warn("XSS injection attempt blocked for '$value'");
1669 22 return;
1670 }
1671  
1672 # Block javascript: URI scheme — no angle brackets, but still executes
1673 # script when used in href or src attributes.
1674 1917 ▶ if($orig_value =~ /\bjavascript\s*:/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($orig_value =~ /\bjavascript\s*:/i) 2 1915 1917
1675 2 $self->status(403);
1676 2 $self->_warn("XSS injection attempt blocked for '$value'");
1677 2 return;
1678 }
1679  
1680 1915 ▶ if($value =~ /mustleak\.com\//) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value =~ m[mustleak\.com/]) 7 1908 1915
1681 7 $self->status(403);
1682 7 $self->_warn("Blocked mustleak attack for '$key'");
1683 7 return;
1684 }
1685  
1686 1908 ▶ if($value =~ /\.\.\//) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value =~ m[\.\./]) 15 1893 1908
1687 15 $self->status(403);
1688 15 $self->_warn("Blocked directory traversal attack for '$key'");
1689 14 return;
1690 }
1691 }
1692 1893 ▶ if(length($value) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $value > 0) 1881 12 1893
1693 # Don't add if it's already there
1694 1881 ▶ if($FORM{$key} && ($FORM{$key} ne $value)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($FORM{$key} and $FORM{$key} ne $value) { } 9 1872 1881
Condition100%3/3
$FORM{$key} and $FORM{$key} ne $value
!ll&&!rl&&r
187119
MC/DC100%2/2
$FORM{$key} and $FORM{$key} ne $value
$FORM{$key} $FORM{$key} ne $value
Truth table100%3/3
A and B
A= $FORM{$key}B= $FORM{$key} ne $value
ABresult
0X0
100
111
1695 9 $FORM{$key} .= ",$value";
1696 } else {
1697 1872 $FORM{$key} = $value;
1698 }
1699 }
1700 }
1701  
1702 285 ▶ unless(%FORM) {
Branch: 1 branch
BranchTrueFalseTotal
unless (%FORM) 41 244 285
1703 41 return;
1704 }
1705  
1706 244 ▶ if($self->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 244 0 244
1707 244 ▶ while(my ($key,$value) = each %FORM) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %FORM) 1862 244 2106
1708 1862 $self->_debug("$key=$value");
1709 }
1710 }
1711  
1712 244 $self->{paramref} = \%FORM;
1713 244 $self->{_limits_key} = $limits_key;
1714  
1715 244 return Return::Set::set_return(\%FORM, { type => 'hashref', min => 1 });
1716 }
1717  
1718 =head2 param($field)
1719  
1720 Get a single CGI parameter value by name.
1721 When called without arguments it delegates to C<params()> and returns all parameters.
1722 When called with a field name it returns that parameter's (sanitised) value,
1723 or C<undef> if the parameter was not supplied or is not in the allow list.
1724  
1725 use CGI::Info;
1726 my $info = CGI::Info->new();
1727 my $bar = $info->param('foo');
1728  
1729 # With an allow list:
1730 my $info2 = CGI::Info->new();
1731 my $allowed = { foo => qr/\d+/ };
1732 $info2->params(allow => $allowed);
1733 my $bar2 = $info2->param('bar'); # logs a warning; returns undef
1734  
1735 =over 4
1736  
1737 =item $field
1738  
1739 Optional. The name of the CGI parameter to retrieve.
1740 If omitted, all parameters (as a hash-ref) are returned via C<params()>.
1741  
1742 =back
1743  
1744 =head3 API SPECIFICATION
1745  
1746 =head4 Input
1747  
1748 {
1749 field => { type => 'scalar', optional => 1 },
1750 }
1751  
1752 =head4 Output
1753  
1754 # When $field is supplied
1755 { type => 'scalar', optional => 1 }
1756 # When $field is omitted (delegates to params())
1757 { type => 'hashref', optional => 1 }
1758  
1759 =head3 MESSAGES
1760  
1761 | Level | Message | Meaning | Action |
1762 |-------|------------------------------------------|--------------------------------------|-----------------------------------------|
1763 | warn | param: <field> isn't in the allow list | Caller requested a parameter outside | Review the allow list passed to new() |
1764 | | | the schema set by params(allow=>\%h) | or params(); add the key if legitimate |
1765  
1766 =cut
1767  
1768 87 ▶sub param {
Subroutine param: called CC=8 SCAR=20.8
Pod documented
1769 87 my ($self, $field) = @_;
1770  
1771 87 ▶ if(!defined($field)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $field) 6 81 87
1772 6 return $self->params();
1773 }
1774 # Is this a permitted argument?
1775 81 ▶ if($self->{allow} && !exists($self->{allow}->{$field})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"allow"} and not exists $self->{"allow"}{$field}) 11 70 81
Condition100%3/3
$self->{"allow"} and not exists $self->{"allow"}{$field}
!ll&&!rl&&r
502011
MC/DC100%2/2
$self->{"allow"} and not exists $self->{"allow"}{$field}
$self->{"allow"} not exists $self->{"allow"}{$field}
Truth table100%3/3
A and not(B)
A= $self->{"allow"}B= not exists $self->{"allow"}{$field}
ABresult
0X0
100
111
1776 11 $self->_warn({
1777 warning => "param: $field isn't in the allow list"
1778 });
1779 7 return;
1780 }
1781  
1782 # Prevent deep recursion which can happen when a validation routine calls param()
1783 70 my $allow;
1784 70 ▶ if($self->{in_param} && $self->{allow}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"in_param"} and $self->{"allow"}) 4 66 70
Condition66%2/3
$self->{"in_param"} and $self->{"allow"}
!ll&&!rl&&r
6604
MC/DC50%1/2
$self->{"in_param"} and $self->{"allow"}
$self->{"in_param"} $self->{"allow"}
Truth table66%2/3
A and B
A= $self->{"in_param"}B= $self->{"allow"}
ABresult
0X0
100
111
1785 4 $allow = delete $self->{allow};
1786 }
1787 70 $self->{in_param} = 1;
1788  
1789 70 my $params = $self->params();
1790  
1791 70 $self->{in_param} = 0;
1792 70 ▶ $self->{allow} = $allow if($allow);
Branch: 1 branch
BranchTrueFalseTotal
if $allow 4 66 70
1793  
1794 70 ▶ if($params) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params) 63 7 70
1795 63 return Return::Set::set_return($params->{$field}, { type => 'string' });
1796 }
1797 }
1798  
1799 4062 ▶sub _sanitise_input :Protected {
Subroutine _sanitise_input: called CC=6 SCAR=18.9
1800 4062 my $arg = shift;
1801  
1802 # Protected function: inline check because the ($) prototype means no $self,
1803 4062 ▶ unless($ENV{HARNESS_ACTIVE}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ENV{"HARNESS_ACTIVE"}) 2334 1728 4062
1804 2334 my $calling_pkg = (caller)[0];
1805 2334 ▶ unless($calling_pkg && ($calling_pkg eq __PACKAGE__ || $calling_pkg->isa(__PACKAGE__))) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($calling_pkg and $calling_pkg eq __PACKAGE__ || $calling_pkg->isa(__PACKAGE__)) 0 2334 2334
Condition33%2/6
$calling_pkg and $calling_pkg eq __PACKAGE__ || $calling_pkg->isa(__PACKAGE__)
!ll&&!rl&&r
002334
$calling_pkg eq __PACKAGE__ or $calling_pkg->isa(__PACKAGE__)
l!l&&r!l&&!r
233400
MC/DC0%0/3
$calling_pkg and $calling_pkg eq __PACKAGE__ || $calling_pkg->isa(__PACKAGE__)
$calling_pkg $calling_pkg eq __PACKAGE__ $calling_pkg->isa(__PACKAGE__)
Truth table25%1/4
A and B or C
A= $calling_pkgB= $calling_pkg eq __PACKAGE__C= $calling_pkg->isa(__PACKAGE__)
ABCresult
0XX0
1000
11X1
1011
1806 0 Carp::croak('_sanitise_input() is a protected function and cannot be called from outside ' . __PACKAGE__);
1807 }
1808 }
1809  
1810 4062 ▶ return if(!defined($arg));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $arg 1 4061 4062
1811  
1812 # Remove hacking attempts and spaces
1813 4061 $arg =~ s/[\r\n]//g;
1814 4061 $arg =~ s/\s+$//;
1815 4061 $arg =~ s/^\s+//;
1816  
1817 # Possessive quantifier prevents catastrophic backtracking when input
1818 # contains '<!--' with no matching closing '-->'.
1819 4061 $arg =~ s/<!--[^-]*+(?:-(?!->)[^-]*+)*+-->//g;
1820 # Allow :
1821 # $arg =~ s/[;<>\*|`&\$!?#\(\)\[\]\{\}'"\\\r]//g;
1822  
1823 # return $arg;
1824 # return String::EscapeCage->new(convert_XSS($arg))->escapecstring();
1825 4061 return convert_XSS($arg);
1826 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1827  
1828 14 ▶sub _multipart_data :Protected {
Subroutine _multipart_data: called CC=28 SCAR=33.8
1829 14 my ($self, $args) = @_;
1830  
1831 14 $self->_trace('Entering _multipart_data');
1832  
1833 14 my $total_bytes = $$args{length};
1834  
1835 14 $self->_debug("_multipart_data: total_bytes = $total_bytes");
1836  
1837 14 ▶ if($total_bytes == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($total_bytes == 0) 0 14 14
1838 0 return;
1839 }
1840  
1841 14 ▶ unless($stdin_data) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($CGI::Info::stdin_data) 12 2 14
1842 # Read no more than the declared body length. The old line loop read
1843 # until EOF, which ignored CONTENT_LENGTH and could grow without bound
1844 # if the server passed more bytes than the declared request body.
1845 12 my $buffer = '';
1846 12 my $remaining = $total_bytes;
1847 12 ▶ while($remaining > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($remaining > 0) 13 11 24
1848 13 my $chunk;
1849 13 my $got = read(STDIN, $chunk, $remaining);
1850 13 ▶ last unless(defined($got) && ($got > 0));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $got and $got > 0 1 12 13
Condition66%2/3
defined $got and $got > 0
!ll&&!rl&&r
0112
MC/DC50%1/2
defined $got and $got > 0
defined $got $got > 0
Truth table66%2/3
A and B
A= defined $gotB= $got > 0
ABresult
0X0
100
111
1851 12 $buffer .= $chunk;
1852 12 $remaining -= $got;
1853 }
1854 12 $buffer =~ s/\r//g;
1855 12 $stdin_data = $buffer;
1856 12 ▶ if(!$stdin_data) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($CGI::Info::stdin_data) 0 12 12
1857 0 return;
1858 }
1859 }
1860  
1861 14 my $boundary = $$args{boundary};
1862  
1863 14 my @pairs;
1864 14 my $writing_file = 0;
1865 14 my $key;
1866 my $value;
1867 14 my $in_header = 0;
1868 14 my $fout;
1869 14 my $part_count = 0;
1870 14 my $header_count = 0;
1871  
1872 14 foreach my $line(split(/\n/, $stdin_data)) {
1873 83 ▶ if($line =~ /^--\Q$boundary\E--$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^--\Q$boundary\E--$/) 5 78 83
1874 5 last;
1875 }
1876 78 ▶ if($line =~ /^--\Q$boundary\E$/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($line =~ /^--\Q$boundary\E$/) { } 22 56 78
elsif ($in_header) { } 39 17 56
1877 22 $part_count++;
1878 22 ▶ if($self->_over_limit($part_count, $self->{max_parts})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_over_limit($part_count, $self->{"max_parts"})) 3 19 22
1879 3 ▶ close $fout if($writing_file);
Branch: 1 branch
BranchTrueFalseTotal
if $writing_file 0 3 3
1880 3 $self->_reject_complexity("more than $self->{max_parts} multipart parts");
1881 3 return;
1882 }
1883 19 ▶ if($writing_file) {
Branch: 2 branches
BranchTrueFalseTotal
if ($writing_file) { } 0 19 19
elsif (defined $key) { } 6 13 19
1884 0 close $fout;
1885 0 $writing_file = 0;
1886 } elsif(defined($key)) {
1887 6 push(@pairs, "$key=$value");
1888 6 $value = undef;
1889 }
1890 19 $in_header = 1;
1891 19 $header_count = 0;
1892 } elsif($in_header) {
1893 39 ▶ if(length($line) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $line == 0) { } 14 25 39
1894 14 $in_header = 0;
1895 } else {
1896 25 $header_count++;
1897 25 ▶ if($self->_over_limit($header_count, $self->{max_part_headers})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_over_limit($header_count, $self->{"max_part_headers"})) 2 23 25
1898 2 ▶ close $fout if($writing_file);
Branch: 1 branch
BranchTrueFalseTotal
if $writing_file 0 2 2
1899 2 $self->_reject_complexity("more than $self->{max_part_headers} headers in a multipart part");
1900 2 return;
1901 }
1902 23 ▶ if($line =~ /^Content-Disposition: (.+)/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^Content-Disposition: (.+)/i) 19 4 23
1903 19 my $field = $1;
1904 19 ▶ if($field =~ /name="(.+?)"/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($field =~ /name="(.+?)"/) 19 0 19
1905 19 $key = $1;
1906 19 ▶ if($self->_over_limit($self->_param_nesting_depth($key), $self->{max_nesting_depth})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_over_limit($self->_param_nesting_depth($key), $self->{"max_nesting_depth"})) 1 18 19
1907 1 ▶ close $fout if($writing_file);
Branch: 1 branch
BranchTrueFalseTotal
if $writing_file 0 1 1
1908 1 $self->_reject_complexity("parameter name nesting deeper than $self->{max_nesting_depth}");
1909 1 return;
1910 }
1911 }
1912 # [^"]+ instead of .+ : stops at first '"' without backtracking,
1913 # and cannot accidentally capture across the closing delimiter.
1914 18 ▶ if($field =~ /filename="([^"]+)?"/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($field =~ /filename="([^"]+)?"/) 5 13 18
1915 5 my $filename = $1;
1916 5 ▶ unless(defined($filename)) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $filename) { } 5 0 5
if (do { $filename =~ m[[\\/\|]] }) { } 2 3 5
1917 0 $self->_warn('No upload filename given');
1918 } elsif($filename =~ /[\\\/\|]/) {
1919 2 $self->_warn("Disallowing invalid filename: $filename");
1920 } else {
1921 3 $filename = $self->_create_file_name({
1922 filename => $filename
1923 });
1924  
1925 # Don't do this since it taints the string and I can't work out how to untaint it
1926 # my $full_path = Cwd::realpath(File::Spec->catfile($self->{upload_dir}, $filename));
1927 # $full_path = m/^(\/[\w\.]+)$/;
1928 3 my $full_path = File::Spec->catfile($self->{upload_dir}, $filename);
1929 3 ▶ unless(open($fout, '>', $full_path)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&CGI::Info::open($fout, ">", $full_path)) 0 3 3
1930 0 $self->_warn("Can't open $full_path");
1931 }
1932 3 $writing_file = 1;
1933 3 push(@pairs, "$key=$filename");
1934 }
1935 }
1936 }
1937 }
1938 # TODO: handle Content-Type: text/plain, etc.
1939 } else {
1940 17 ▶ if($writing_file) {
Branch: 1 branch
BranchTrueFalseTotal
if ($writing_file) { } 5 12 17
1941 5 print $fout "$line\n";
1942 } else {
1943 12 $value .= $line;
1944 }
1945 }
1946 }
1947  
1948 6 ▶ if($writing_file) {
Branch: 1 branch
BranchTrueFalseTotal
if ($writing_file) 3 3 6
1949 3 close $fout;
1950 }
1951  
1952 6 $self->_trace('Leaving _multipart_data');
1953  
1954 6 return @pairs;
1955 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1956  
1957 # Robust filename generation (preventing overwriting).
1958 # Previously used "! -e $rc" which checked existence in the CURRENT WORKING
1959 # DIRECTORY, not the upload directory — a logic bug and a TOCTOU race.
1960 # Now checks in the actual upload directory and caps iterations to avoid
1961 # an infinite loop if the directory fills up.
1962 6 ▶sub _create_file_name :Protected {
Subroutine _create_file_name: called CC=6 SCAR=18.1
1963 6 my ($self, $args) = @_;
1964  
1965 6 my $upload_dir = $self->{upload_dir};
1966 6 my $filename = $$args{filename} . '_' . time;
1967  
1968 6 my $counter = 0;
1969 6 my $rc;
1970 6 ▶ do {
Branch: 2 branches
BranchTrueFalseTotal
(not -e ($upload_dir ? "File::Spec"->catfile($upload_dir, $rc) : $rc) or $counter > 1000) or do { do { $rc = $filename . ($counter ? "_$counter" : ""); ++$counter } } 6 1 7
$upload_dir ? : 3 4 7
Condition66%2/3
not -e ($upload_dir ? "File::Spec"->catfile($upload_dir, $rc) : $rc) or $counter > 1000
l!l&&r!l&&!r
601
MC/DC50%1/2
not -e ($upload_dir ? "File::Spec"->catfile($upload_dir, $rc) : $rc) or $counter > 1000
not -e ($upload_dir ? "File::Spec"->catfile($upload_dir, $rc) : $rc) $counter > 1000
Truth table66%2/3
not(A) or B
A= not -e ($upload_dir ? "File::Spec"->catfile($upload_dir, $rc) : $rc)B= $counter > 1000
ABresult
1X1
011
000
1971 7 ▶ $rc = $filename . ($counter ? "_$counter" : '');
Branch: 1 branch
BranchTrueFalseTotal
$counter ? : 1 6 7
1972 7 $counter++;
1973 # Check in upload_dir when set; otherwise check relative to CWD.
1974 # File::Spec->catfile('', ...) produces an absolute path, so we
1975 # must not pass an empty string as the directory component.
1976 } until(
1977 ! -e ($upload_dir ? File::Spec->catfile($upload_dir, $rc) : $rc)
1978 || $counter > 1000
1979 );
1980 6 ▶ if($counter > 1000) {
Branch: 1 branch
BranchTrueFalseTotal
if ($counter > 1000) 0 6 6
1981 0 Carp::croak('_create_file_name: unable to find a unique filename after 1000 attempts');
1982 }
1983  
1984 6 return $rc;
1985 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1986  
1987 # Untaint a filename. Regex from CGI::Untaint::Filenames
1988 107 ▶sub _untaint_filename :Protected {
Subroutine _untaint_filename: called CC=2 SCAR=6.9
1989 107 my ($self, $args) = @_;
1990  
1991 107 ▶ if($$args{filename} =~ /(^[\w\+_\040\#\(\)\{\}\[\]\/\-\^,\.:;&%@\\~]+\$?$)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"filename"} =~ m<(^[\w\+_\040\#\(\)\{\}\[\]/\-\^,\.:;&%\@\\~]+\$?$)>) 105 2 107
1992 105 return $1;
1993 }
1994 2 return;
1995 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1996  
1997 =head2 is_mobile
1998  
1999 Returns a boolean if the website is being viewed on a mobile
2000 device such as a smartphone.
2001 All tablets are mobile, but not all mobile devices are tablets.
2002  
2003 Can be overridden by the IS_MOBILE environment setting
2004  
2005 =cut
2006  
2007 225 ▶sub is_mobile {
Subroutine is_mobile: called CC=21 SCAR=30.7
Pod documented
2008 225 my $self = shift;
2009  
2010 225 ▶ if(defined($self->{is_mobile})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"is_mobile"}) 126 99 225
2011 126 return $self->{is_mobile};
2012 }
2013  
2014 99 ▶ if($ENV{'IS_MOBILE'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{"IS_MOBILE"}) 4 95 99
2015 4 return $ENV{'IS_MOBILE'}
2016 }
2017  
2018 # Support Sec-CH-UA-Mobile
2019 95 ▶ if(my $ch_ua_mobile = $ENV{'HTTP_SEC_CH_UA_MOBILE'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ch_ua_mobile = $ENV{"HTTP_SEC_CH_UA_MOBILE"}) 12 83 95
2020 12 ▶ if($ch_ua_mobile eq '?1') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ch_ua_mobile eq "?1") 5 7 12
2021 5 $self->{is_mobile} = 1;
2022 5 return 1;
2023 }
2024 }
2025  
2026 90 ▶ if($ENV{'HTTP_X_WAP_PROFILE'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{"HTTP_X_WAP_PROFILE"}) 3 87 90
2027 # E.g. Blackberry
2028 # TODO: Check the sanity of this variable
2029 3 $self->{is_mobile} = 1;
2030 3 return 1;
2031 }
2032  
2033 87 ▶ if(my $agent = $ENV{'HTTP_USER_AGENT'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $agent = $ENV{"HTTP_USER_AGENT"}) 69 18 87
2034 # Was '.+(Android|iPhone).+' — .+ before and after adds no useful
2035 # constraint but causes ReDoS on long UAs without those tokens.
2036 69 ▶ if($agent =~ /\b(?:Android|iPhone)\b/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($agent =~ /\b(?:Android|iPhone)\b/) 20 49 69
2037 20 $self->{is_mobile} = 1;
2038 20 return 1;
2039 }
2040  
2041 # From http://detectmobilebrowsers.com/
2042 49 ▶ if($agent =~ m/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i || substr($ENV{'HTTP_USER_AGENT'}, 0, 4) =~ m/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($agent =~ m[(android|bb\d+|meego).+mobile|avantgo|bada/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino]i or substr($ENV{"HTTP_USER_AGENT"}, 0, 4) =~ m[1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-]i) 1 48 49
Condition66%2/3
$agent =~ m[(android|bb\d+|meego).+mobile|avantgo|bada/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino]i or substr($ENV{"HTTP_USER_AGENT"}, 0, 4) =~ m[1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-]i
l!l&&r!l&&!r
1048
MC/DC50%1/2
$agent =~ m[(android|bb\d+|meego).+mobile|avantgo|bada/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino]i or substr($ENV{"HTTP_USER_AGENT"}, 0, 4) =~ m[1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-]i
$agent =~ m[(android|bb\d+|meego).+mobile|avantgo|bada/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino]i substr($ENV{"HTTP_USER_AGENT"}, 0, 4) =~ m[1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-]i
Truth table66%2/3
A or B
A= $agent =~ m[(android|bb\d+|meego).+mobile|avantgo|bada/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino]iB= substr($ENV{"HTTP_USER_AGENT"}, 0, 4) =~ m[1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-]i
ABresult
1X1
011
000
2043 1 $self->{is_mobile} = 1;
2044 1 return 1;
2045 }
2046  
2047 # Save loading and calling HTTP::BrowserDetect
2048 48 my $remote = $ENV{'REMOTE_ADDR'};
2049 48 ▶ if(defined($remote) && $self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $remote and $self->{"cache"}) 4 44 48
Condition100%3/3
defined $remote and $self->{"cache"}
!ll&&!rl&&r
5394
MC/DC100%2/2
defined $remote and $self->{"cache"}
defined $remote $self->{"cache"}
Truth table100%3/3
A and B
A= defined $remoteB= $self->{"cache"}
ABresult
0X0
100
111
2050 4 ▶ if(my $type = $self->{cache}->get("$remote/$agent")) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $type = $self->{"cache"}->get("$remote/$agent")) 3 1 4
2051 3 return $self->{is_mobile} = ($type eq 'mobile');
2052 }
2053 }
2054  
2055 45 ▶ unless($self->{browser_detect}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"browser_detect"}) 37 8 45
2056 37 ▶ if(eval { require HTTP::BrowserDetect; }) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { require HTTP::BrowserDetect } }) 37 0 37
2057 37 HTTP::BrowserDetect->import();
2058 37 $self->{browser_detect} = HTTP::BrowserDetect->new($agent);
2059 }
2060 }
2061  
2062 45 ▶ if($self->{browser_detect}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"browser_detect"}) 45 0 45
2063 45 my $device = $self->{browser_detect}->device();
2064 # Without the ?1:0 it will set to the empty string not 0
2065 45 ▶ my $is_mobile = (defined($device) && ($device =~ /blackberry|webos|iphone|ipod|ipad|android/i)) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $device && $device =~ /blackberry|webos|iphone|ipod|ipad|android/i ? : 4 41 45
Condition66%2/3
defined $device and $device =~ /blackberry|webos|iphone|ipod|ipad|android/i
!ll&&!rl&&r
4104
MC/DC50%1/2
defined $device and $device =~ /blackberry|webos|iphone|ipod|ipad|android/i
defined $device $device =~ /blackberry|webos|iphone|ipod|ipad|android/i
Truth table66%2/3
A and B
A= defined $deviceB= $device =~ /blackberry|webos|iphone|ipod|ipad|android/i
ABresult
0X0
100
111
2066 45 ▶ if($is_mobile && $self->{cache} && defined($remote)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_mobile and $self->{"cache"} and defined $remote) 0 45 45
Condition50%3/6
$is_mobile and $self->{"cache"} and defined $remote
!ll&&!rl&&r
4500
$is_mobile and $self->{"cache"}
!ll&&!rl&&r
4140
MC/DC0%0/3
$is_mobile and $self->{"cache"} and defined $remote
$is_mobile $self->{"cache"} defined $remote
Truth table50%2/4
A and B and C
A= $is_mobileB= $self->{"cache"}C= defined $remote
ABCresult
0XX0
10X0
1100
1111
2067 0 $self->{cache}->set("$remote/$agent", 'mobile', $CACHE_TTL_SEARCH);
2068 }
2069 45 return $self->{is_mobile} = $is_mobile;
2070 }
2071 }
2072  
2073 18 return 0;
2074 }
2075  
2076 =head2 is_tablet
2077  
2078 Returns a boolean if the website is being viewed on a tablet such as an iPad.
2079  
2080 =cut
2081  
2082 19 ▶sub is_tablet {
Subroutine is_tablet: called CC=4 SCAR=13.9
Pod documented
2083 19 my $self = shift;
2084  
2085 19 ▶ if(defined($self->{is_tablet})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"is_tablet"}) 4 15 19
2086 4 return $self->{is_tablet};
2087 }
2088  
2089 # Was '.+(iPad|TabletPC).+' — same ReDoS risk as the mobile pattern above.
2090 15 ▶ if($ENV{'HTTP_USER_AGENT'} && ($ENV{'HTTP_USER_AGENT'} =~ /\b(?:iPad|TabletPC)\b/)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{'HTTP_USER_AGENT'} and $ENV{'HTTP_USER_AGENT'} =~ /\b(?:iPad|TabletPC)\b/) { } 5 10 15
Condition100%3/3
$ENV{"HTTP_USER_AGENT"} and $ENV{"HTTP_USER_AGENT"} =~ /\b(?:iPad|TabletPC)\b/
!ll&&!rl&&r
195
MC/DC100%2/2
$ENV{"HTTP_USER_AGENT"} and $ENV{"HTTP_USER_AGENT"} =~ /\b(?:iPad|TabletPC)\b/
$ENV{"HTTP_USER_AGENT"} $ENV{"HTTP_USER_AGENT"} =~ /\b(?:iPad|TabletPC)\b/
Truth table100%3/3
A and B
A= $ENV{"HTTP_USER_AGENT"}B= $ENV{"HTTP_USER_AGENT"} =~ /\b(?:iPad|TabletPC)\b/
ABresult
0X0
100
111
2091 # TODO: add others when I see some nice user_agents
2092 5 $self->{is_tablet} = 1;
2093 } else {
2094 10 $self->{is_tablet} = 0;
2095 }
2096  
2097 15 return $self->{is_tablet};
2098 }
2099  
2100 =head2 as_string
2101  
2102 Converts CGI parameters into a formatted string representation with optional raw mode (no escaping of special characters).
2103 Useful for debugging or generating keys for a cache.
2104  
2105 my $string_representation = $info->as_string();
2106 my $raw_string = $info->as_string({ raw => 1 });
2107  
2108 =head3 API SPECIFICATION
2109  
2110 =head4 INPUT
2111  
2112 {
2113 raw => {
2114 'type' => 'boolean',
2115 'optional' => 1,
2116 }
2117 }
2118  
2119 =head4 OUTPUT
2120  
2121 {
2122 type => 'string',
2123 optional => 1,
2124 }
2125  
2126 =cut
2127  
2128 sub as_string
2129 60 ▶{
Subroutine as_string: called CC=5 SCAR=16.1
Pod documented
2130 60 my $self = shift;
2131  
2132 60 ▶ my $args = Params::Validate::Strict::validate_strict({
Condition100%2/2
Params::Get::get_params(undef, @_) || {}
l!l
852
MC/DC100%1/1
Params::Get::get_params(undef, @_) || {}
Params::Get::get_params(undef, @_)
Truth table100%2/2
A
A= Params::Get::get_params(undef, @_)
Aresult
11
00
2133 args => Params::Get::get_params(undef, @_) || {},
2134 schema => {
2135 raw => {
2136 'type' => 'boolean',
2137 'optional' => 1
2138 }
2139 }
2140 });
2141  
2142 # Retrieve object parameters
2143 60 ▶ my $params = $self->params() || return '';
Condition100%2/2
$self->params || (return '')
l!l
4713
MC/DC100%1/1
$self->params || (return '')
$self->params
Truth table100%2/2
A
A= $self->params
Aresult
11
00
2144  
2145 47 my $rc;
2146  
2147 47 ▶ if($args->{'raw'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{'raw'}) { } 7 40 47
2148 # Raw mode: return key=value pairs without escaping
2149 $rc = join '; ', map {
2150 10 "$_=" . $params->{$_}
2151 7 } sort keys %{$params};
2152 } else {
2153 # Escaped mode: escape special characters
2154 $rc = join '; ', map {
2155 62 my $value = $params->{$_};
2156  
2157 62 $value =~ s/\\/\\\\/g; # Escape backslashes
2158 62 $value =~ s/(;|=)/\\$1/g; # Escape semicolons and equals signs
2159 62 "$_=$value"
2160 40 } sort keys %{$params};
2161 }
2162  
2163 47 ▶ $rc ||= '';
Condition50%1/2
$rc ||= ""
l!l
470
MC/DC0%0/1
$rc ||= ""
$rc
Truth table50%1/2
A
A= $rc
Aresult
11
00
2164  
2165 47 $self->_trace("as_string: returning '$rc'");
2166  
2167 47 return $rc;
2168 }
2169  
2170 =head2 protocol
2171  
2172 Returns the connection protocol, presumably 'http' or 'https', or undef if
2173 it can't be determined.
2174  
2175 =cut
2176  
2177 63 ▶sub protocol {
Subroutine protocol: called CC=16 SCAR=28.4
Pod documented
2178 63 my $self = shift;
2179  
2180 # Cached: ENV is read-only during a CGI request, so the result never changes.
2181 # Use exists (not defined) so we cache undef for the "unknown" case too.
2182 # Guard with ref() because protocol() may be called as a class method.
2183 63 ▶ return $self->{'protocol'} if ref($self) && exists $self->{'protocol'};
Branch: 1 branch
BranchTrueFalseTotal
if ref $self and exists $self->{"protocol"} 6 57 63
Condition100%3/3
ref $self and exists $self->{"protocol"}
!ll&&!rl&&r
4536
MC/DC100%2/2
ref $self and exists $self->{"protocol"}
ref $self exists $self->{"protocol"}
Truth table100%3/3
A and B
A= ref $selfB= exists $self->{"protocol"}
ABresult
0X0
100
111
2184  
2185 # RFC 3986 §3.1: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
2186 # Character-class [^:]+ avoids the O(n) backtracking of the former (.+)://
2187 57 my $result;
2188 57 ▶ if($ENV{'SCRIPT_URI'} && ($ENV{'SCRIPT_URI'} =~ /^([a-zA-Z][a-zA-Z0-9+\-.]*):\/\//)) {
Branch: 3 branches
BranchTrueFalseTotal
if ($ENV{'SCRIPT_URI'} and $ENV{'SCRIPT_URI'} =~ m[^([a-zA-Z][a-zA-Z0-9+\-.]*)://]) { } 9 48 57
elsif ($ENV{'SERVER_PROTOCOL'} and $ENV{'SERVER_PROTOCOL'} =~ m[^HTTP/]) { } 7 41 48
elsif (my $port = $ENV{'SERVER_PORT'}) { } 21 20 41
Condition100%3/3
$ENV{"SCRIPT_URI"} and $ENV{"SCRIPT_URI"} =~ m[^([a-zA-Z][a-zA-Z0-9+\-.]*)://]
!ll&&!rl&&r
4719
MC/DC100%2/2
$ENV{"SCRIPT_URI"} and $ENV{"SCRIPT_URI"} =~ m[^([a-zA-Z][a-zA-Z0-9+\-.]*)://]
$ENV{"SCRIPT_URI"} $ENV{"SCRIPT_URI"} =~ m[^([a-zA-Z][a-zA-Z0-9+\-.]*)://]
Truth table100%3/3
A and B
A= $ENV{"SCRIPT_URI"}B= $ENV{"SCRIPT_URI"} =~ m[^([a-zA-Z][a-zA-Z0-9+\-.]*)://]
ABresult
0X0
100
111
2189 9 $result = $1;
2190 ▶ } elsif($ENV{'SERVER_PROTOCOL'} && ($ENV{'SERVER_PROTOCOL'} =~ /^HTTP\//)) {
Condition100%3/3
$ENV{"SERVER_PROTOCOL"} and $ENV{"SERVER_PROTOCOL"} =~ m[^HTTP/]
!ll&&!rl&&r
3927
MC/DC100%2/2
$ENV{"SERVER_PROTOCOL"} and $ENV{"SERVER_PROTOCOL"} =~ m[^HTTP/]
$ENV{"SERVER_PROTOCOL"} $ENV{"SERVER_PROTOCOL"} =~ m[^HTTP/]
Truth table100%3/3
A and B
A= $ENV{"SERVER_PROTOCOL"}B= $ENV{"SERVER_PROTOCOL"} =~ m[^HTTP/]
ABresult
0X0
100
111
2191 7 $result = 'http';
2192 } elsif(my $port = $ENV{'SERVER_PORT'}) {
2193 21 ▶ if(defined(my $name = getservbyport($port, 'tcp'))) {
Branch: 3 branches
BranchTrueFalseTotal
if (defined(my $name = getservbyport($port, 'tcp'))) { } 0 21 21
elsif ($port == 80) { } 7 14 21
elsif ($port == 443) { } 6 8 14
2194 0 ▶ if($name =~ /^https?$/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($name =~ /^https?$/) { } 0 0 0
elsif ($name eq 'www') { } 0 0 0
2195 0 $result = $name;
2196 } elsif($name eq 'www') {
2197 # e.g. NetBSD and OpenBSD
2198 0 $result = 'http';
2199 }
2200 # else: unrecognised service name — $result stays undef
2201 } elsif($port == 80) {
2202 # e.g. Solaris
2203 7 $result = 'http';
2204 } elsif($port == 443) {
2205 6 $result = 'https';
2206 }
2207 }
2208  
2209 57 ▶ if(!defined($result) && $ENV{'REMOTE_ADDR'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $result and $ENV{"REMOTE_ADDR"}) 2 55 57
Condition100%3/3
not defined $result and $ENV{"REMOTE_ADDR"}
!ll&&!rl&&r
29262
MC/DC100%2/2
not defined $result and $ENV{"REMOTE_ADDR"}
not defined $result $ENV{"REMOTE_ADDR"}
Truth table100%3/3
not(A) and B
A= not defined $resultB= $ENV{"REMOTE_ADDR"}
ABresult
0X0
100
111
2210 2 $self->_warn("Can't determine the calling protocol");
2211 }
2212 57 ▶ $self->{'protocol'} = $result if ref($self);
Branch: 1 branch
BranchTrueFalseTotal
if ref $self 53 4 57
2213 57 return $result;
2214 }
2215  
2216 =head2 tmpdir
2217  
2218 Returns the name of a directory that you can use to create temporary files
2219 in.
2220  
2221 The routine is preferable to L<File::Spec/tmpdir> since CGI programs are
2222 often running on shared servers. Having said that, tmpdir will fall back
2223 to File::Spec->tmpdir() if it can't find somewhere better.
2224  
2225 If the parameter 'default' is given, then use that directory as a
2226 fall-back rather than the value in File::Spec->tmpdir().
2227 No sanity tests are done, so if you give the default value of
2228 '/non-existant', that will be returned.
2229  
2230 Tmpdir allows a reference of the options to be passed.
2231  
2232 use CGI::Info;
2233  
2234 my $info = CGI::Info->new();
2235 my $dir = $info->tmpdir(default => '/var/tmp');
2236 $dir = $info->tmpdir({ default => '/var/tmp' });
2237  
2238 # or
2239  
2240 my $dir = CGI::Info->tmpdir();
2241 =cut
2242  
2243 97 ▶sub tmpdir {
Subroutine tmpdir: called CC=16 SCAR=27.8
Pod documented
2244 97 my $self = shift;
2245  
2246 97 my $name = 'tmp';
2247 97 ▶ if($^O eq 'MSWin32') {
Branch: 1 branch
BranchTrueFalseTotal
if ($^O eq "MSWin32") 17 80 97
2248 17 $name = 'temp';
2249 }
2250  
2251 97 my $dir;
2252  
2253 97 ▶ if(!ref($self)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $self) 5 92 97
2254 5 $self = __PACKAGE__->new();
2255 }
2256 97 my $params = Params::Get::get_params(undef, @_);
2257  
2258 97 ▶ if($ENV{'C_DOCUMENT_ROOT'} && (-d $ENV{'C_DOCUMENT_ROOT'})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{"C_DOCUMENT_ROOT"} and -d $ENV{"C_DOCUMENT_ROOT"}) 11 86 97
Condition100%3/3
$ENV{"C_DOCUMENT_ROOT"} and -d $ENV{"C_DOCUMENT_ROOT"}
!ll&&!rl&&r
80611
MC/DC100%2/2
$ENV{"C_DOCUMENT_ROOT"} and -d $ENV{"C_DOCUMENT_ROOT"}
$ENV{"C_DOCUMENT_ROOT"} -d $ENV{"C_DOCUMENT_ROOT"}
Truth table100%3/3
A and B
A= $ENV{"C_DOCUMENT_ROOT"}B= -d $ENV{"C_DOCUMENT_ROOT"}
ABresult
0X0
100
111
2259 11 $dir = File::Spec->catdir($ENV{'C_DOCUMENT_ROOT'}, $name);
2260 11 ▶ if((-d $dir) && (-w $dir)) {
Branch: 1 branch
BranchTrueFalseTotal
if (-d $dir and -w $dir) 4 7 11
Condition66%2/3
-d $dir and -w $dir
!ll&&!rl&&r
704
MC/DC50%1/2
-d $dir and -w $dir
-d $dir -w $dir
Truth table66%2/3
A and B
A= -d $dirB= -w $dir
ABresult
0X0
100
111
2261 4 return $self->_untaint_filename({ filename => $dir });
2262 }
2263 7 $dir = $ENV{'C_DOCUMENT_ROOT'};
2264 7 ▶ if((-d $dir) && (-w $dir)) {
Branch: 1 branch
BranchTrueFalseTotal
if (-d $dir and -w $dir) 7 0 7
Condition33%1/3
-d $dir and -w $dir
!ll&&!rl&&r
007
MC/DC0%0/2
-d $dir and -w $dir
-d $dir -w $dir
Truth table33%1/3
A and B
A= -d $dirB= -w $dir
ABresult
0X0
100
111
2265 7 return $self->_untaint_filename({ filename => $dir });
2266 }
2267 }
2268 86 ▶ if($ENV{'DOCUMENT_ROOT'} && (-d $ENV{'DOCUMENT_ROOT'})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{"DOCUMENT_ROOT"} and -d $ENV{"DOCUMENT_ROOT"}) 2 84 86
Condition100%3/3
$ENV{"DOCUMENT_ROOT"} and -d $ENV{"DOCUMENT_ROOT"}
!ll&&!rl&&r
7952
MC/DC100%2/2
$ENV{"DOCUMENT_ROOT"} and -d $ENV{"DOCUMENT_ROOT"}
$ENV{"DOCUMENT_ROOT"} -d $ENV{"DOCUMENT_ROOT"}
Truth table100%3/3
A and B
A= $ENV{"DOCUMENT_ROOT"}B= -d $ENV{"DOCUMENT_ROOT"}
ABresult
0X0
100
111
2269 2 $dir = File::Spec->catdir($ENV{'DOCUMENT_ROOT'}, File::Spec->updir(), $name);
2270 2 ▶ if((-d $dir) && (-w $dir)) {
Branch: 1 branch
BranchTrueFalseTotal
if (-d $dir and -w $dir) 1 1 2
Condition66%2/3
-d $dir and -w $dir
!ll&&!rl&&r
101
MC/DC50%1/2
-d $dir and -w $dir
-d $dir -w $dir
Truth table66%2/3
A and B
A= -d $dirB= -w $dir
ABresult
0X0
100
111
2271 1 return $self->_untaint_filename({ filename => $dir });
2272 }
2273 }
2274 85 ▶ if($params->{'default'} && ref($params->{'default'})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{"default"} and ref $params->{"default"}) 2 83 85
Condition100%3/3
$params->{"default"} and ref $params->{"default"}
!ll&&!rl&&r
7672
MC/DC100%2/2
$params->{"default"} and ref $params->{"default"}
$params->{"default"} ref $params->{"default"}
Truth table100%3/3
A and B
A= $params->{"default"}B= ref $params->{"default"}
ABresult
0X0
100
111
2275 2 croak(ref($self), ': tmpdir must be given a scalar');
2276 }
2277 83 ▶ return $params->{default} ? $params->{default} : File::Spec->tmpdir();
Branch: 1 branch
BranchTrueFalseTotal
$params->{'default'} ? : 7 76 83
2278 }
2279  
2280 # Lexical tidy-up shared by the audit key and the upload directory check:
2281 # decode %XX, collapse repeated slashes and resolve '.' and '..' segments
2282 # without touching the filesystem. A leading slash is preserved for absolute
2283 # paths; an empty result means the path had no usable segments. With
2284 # $windows set, backslashes are separators too, and are translated after
2285 # decoding so that an encoded '%5C' cannot hide a traversal from the segment
2286 # resolution.
2287 429 ▶sub _tidy_path :Protected {
Subroutine _tidy_path: called CC=9 SCAR=22.0
2288 429 my ($self, $path, $windows) = @_;
2289  
2290 429 ▶ return unless defined($path);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 0 429 429
2291  
2292 # Decoding first means '%2e%2e' is treated like '..' and '%2F' like '/'.
2293 429 $path =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/ge;
2294 429 ▶ $path =~ tr{\\}{/} if($windows);
Branch: 1 branch
BranchTrueFalseTotal
if $windows 68 361 429
2295 429 $path =~ s{/+}{/}g;
2296  
2297 429 ▶ my $absolute = ($path =~ m{\A/}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$path =~ m[\A/] ? : 394 35 429
2298 429 my @segments;
2299 429 foreach my $segment (split(m{/}, $path, -1)) {
2300 1269 ▶ next if(($segment eq '') || ($segment eq '.'));
Branch: 1 branch
BranchTrueFalseTotal
if $segment eq "" or $segment eq "." 398 871 1269
Condition100%3/3
$segment eq "" or $segment eq "."
l!l&&r!l&&!r
3971871
MC/DC100%2/2
$segment eq "" or $segment eq "."
$segment eq "" $segment eq "."
Truth table100%3/3
A or B
A= $segment eq ""B= $segment eq "."
ABresult
1X1
011
000
2301 871 ▶ if($segment eq '..') {
Branch: 1 branch
BranchTrueFalseTotal
if ($segment eq "..") 59 812 871
2302 59 pop(@segments);
2303 59 next;
2304 }
2305 812 push(@segments, $segment);
2306 }
2307  
2308 429 my $normalised = join('/', @segments);
2309 429 ▶ return $absolute ? "/$normalised" : $normalised;
Branch: 1 branch
BranchTrueFalseTotal
$absolute ? : 394 35 429
2310 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2311  
2312 # Canonicalise a path for comparison: resolve '.' and '..' and symlinks when
2313 # the path exists (so '/tmp/../etc' cannot masquerade as '/tmp/...'), then
2314 # apply the lexical tidy-up above. Decoding there means an encoded spelling of
2315 # a temporary path is judged like its decoded form, and on Windows both
2316 # separator kinds are resolved, including an encoded '%5C'.
2317 488 ▶sub _temp_path :Protected {
Subroutine _temp_path: called CC=7 SCAR=19.8
2318 488 my $self = shift;
2319 488 my $path = shift;
2320  
2321 488 ▶ return unless(defined($path) && length($path));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path and length $path 174 314 488
Condition66%2/3
defined $path and length $path
!ll&&!rl&&r
1740314
MC/DC50%1/2
defined $path and length $path
defined $path length $path
Truth table66%2/3
A and B
A= defined $pathB= length $path
ABresult
0X0
100
111
2322 314 ▶ if(-d $path) {
Branch: 1 branch
BranchTrueFalseTotal
if (-d $path) 219 95 314
2323 219 my $real = Cwd::abs_path($path);
2324 219 ▶ $path = $real if(defined($real) && length($real));
Branch: 1 branch
BranchTrueFalseTotal
if defined $real and length $real 219 0 219
Condition33%1/3
defined $real and length $real
!ll&&!rl&&r
00219
MC/DC0%0/2
defined $real and length $real
defined $real length $real
Truth table33%1/3
A and B
A= defined $realB= length $real
ABresult
0X0
100
111
2325 }
2326 314 my $windows = ($^O eq 'MSWin32');
2327 314 ▶ $path = lc($path) if($windows);
Branch: 1 branch
BranchTrueFalseTotal
if $windows 68 246 314
2328  
2329 314 return $self->_tidy_path($path, $windows);
2330 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2331  
2332 # Windows spellings that cannot be checked by comparing strings. A
2333 # drive-relative path (C:foo) starts from the per-drive current directory
2334 # rather than from the drive root, so it can point anywhere; and an 8.3 short
2335 # name (PROGRA~1) is an alias for a long name that cannot be expanded without
2336 # asking the filesystem. Both are refused rather than guessed at, so
2337 # upload_dir is always judged by an unambiguous path. A tilde that is not
2338 # followed by digits is an ordinary character, not an alias.
2339 85 ▶sub _win32_path_problem :Protected {
Subroutine _win32_path_problem: called CC=6 SCAR=17.9
2340 85 my ($self, $dir) = @_;
2341  
2342 85 ▶ return unless(defined($dir) && ($^O eq 'MSWin32'));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dir and $^O eq "MSWin32" 57 28 85
Condition66%2/3
defined $dir and $^O eq "MSWin32"
!ll&&!rl&&r
05728
MC/DC50%1/2
defined $dir and $^O eq "MSWin32"
defined $dir $^O eq "MSWin32"
Truth table66%2/3
A and B
A= defined $dirB= $^O eq "MSWin32"
ABresult
0X0
100
111
2343  
2344 28 my $path = $dir;
2345 28 $path =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/ge;
2346 28 $path =~ tr{\\}{/};
2347  
2348 # 'C:foo', and a bare 'C:', are relative to the working directory on that
2349 # drive, unlike 'C:/foo'.
2350 28 ▶ if($path =~ m{\A[A-Za-z]:(?!/)}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path =~ m[\A[A-Za-z]:(?!/)]) 4 24 28
2351 4 return "is relative to the current directory on its drive";
2352 }
2353  
2354 24 foreach my $segment (split(m{/}, $path, -1)) {
2355 109 ▶ if($segment =~ m{\A[^~]*~\d{1,6}(?:\.[^.]*)?\z}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($segment =~ /\A[^~]*~\d{1,6}(?:\.[^.]*)?\z/) 6 103 109
2356 6 return "uses the 8.3 short name '$segment'";
2357 }
2358 }
2359  
2360 18 return;
2361 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2362  
2363 # The directories that count as temporary work areas for upload_dir.
2364 # tmpdir() on its own is not enough: a web server normally does not export
2365 # TMPDIR, so a directory that an operator created interactively in the
2366 # platform's own temporary tree (for example /var/folders/... on macOS) would
2367 # not be recognised and every upload would fail with a 500. The classic
2368 # system temp directories and the TMPDIR/TEMP/TMP overrides are accepted too.
2369 59 ▶sub _temp_areas :Protected {
Subroutine _temp_areas: called CC=5 SCAR=16.2
2370 59 my $self = shift;
2371  
2372 59 my @areas = ($self->tmpdir(), File::Spec->tmpdir());
2373 59 push(@areas, @ENV{qw(TMPDIR TEMP TMP)});
2374 59 ▶ if($^O eq 'MSWin32') {
Branch: 2 branches
BranchTrueFalseTotal
if ($^O eq 'MSWin32') { } 17 42 59
elsif ($^O eq 'darwin') { } 7 35 42
2375 17 push(@areas, map { File::Spec->catdir($_, 'Temp') } grep { defined($_) } @ENV{qw(SYSTEMROOT WINDIR)});
2376 } elsif($^O eq 'darwin') {
2377 # Core Perl has no confstr(_CS_DARWIN_USER_TEMP_DIR), but the whole of
2378 # /var/folders is the per-user temporary tree.
2379 7 push(@areas, '/var/folders', '/private/var/folders');
2380 } else {
2381 35 push(@areas, qw(/tmp /var/tmp /usr/tmp));
2382 }
2383  
2384 59 my %seen;
2385 # The filesystem root is never a temporary area: accepting it would defeat
2386 # the point of the check.
2387 257 ▶ return grep { defined($_) && (length($_) > 1) && !$seen{$_}++ }
Condition50%3/6
defined $_ && length $_ > 1 && !$seen{$_}++
!ll&&!rl&&r
089168
defined $_ and length $_ > 1
!ll&&!rl&&r
00257
MC/DC33%1/3
defined $_ && length $_ > 1 && !$seen{$_}++
defined $_ length $_ > 1 !$seen{$_}++
Truth table50%2/4
A and B && not(C)
A= defined $_B= length $_ > 1C= !$seen{$_}++
ABCresult
0XX0
10X0
1100
1111
2388 59 map { $self->_temp_path($_) } @areas;
2389 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2390  
2391 # Is $dir a directory inside one of the temporary areas? Compared on
2392 # canonical paths and on directory boundaries, so '/tmpfoo' is not accepted
2393 # for '/tmp'. The root of an area is not accepted either: those directories
2394 # are shared and world-writable, while an upload directory should be one the
2395 # operator created for this application. That applies even when the area is
2396 # itself nested in another one, such as a TMPDIR of /tmp/1234.
2397 49 ▶sub _in_temp_area :Protected {
Subroutine _in_temp_area: called CC=7 SCAR=19.5
2398 49 my ($self, $dir) = @_;
2399  
2400 49 ▶ return if($self->_win32_path_problem($dir));
Branch: 1 branch
BranchTrueFalseTotal
if $self->_win32_path_problem($dir) 3 46 49
2401  
2402 46 my $path = $self->_temp_path($dir);
2403 46 ▶ return unless defined($path);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 0 46 46
2404  
2405 46 my @areas = $self->_temp_areas();
2406 # An area root is never an upload directory, even when it sits inside
2407 # another area (a TMPDIR of /tmp/1234, for example).
2408 46 foreach my $area (@areas) {
2409 121 ▶ return if($path eq $area);
Branch: 1 branch
BranchTrueFalseTotal
if $path eq $area 5 116 121
2410 }
2411 41 foreach my $area (@areas) {
2412 80 ▶ return 1 if(index($path, "$area/") == 0);
Branch: 1 branch
BranchTrueFalseTotal
if index($path, "$area/") == 0 25 55 80
2413 }
2414  
2415 16 return;
2416 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2417  
2418 # The temporary area whose root $dir is, if any. Used to explain why such a
2419 # directory was rejected rather than calling it "not in a temporary area".
2420 7 ▶sub _temp_area_root :Protected {
Subroutine _temp_area_root: called CC=5 SCAR=16.1
2421 7 my ($self, $dir) = @_;
2422  
2423 7 ▶ return if($self->_win32_path_problem($dir));
Branch: 1 branch
BranchTrueFalseTotal
if $self->_win32_path_problem($dir) 1 6 7
2424  
2425 6 my $path = $self->_temp_path($dir);
2426 6 ▶ return unless defined($path);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 0 6 6
2427 6 foreach my $area ($self->_temp_areas()) {
2428 12 ▶ return $area if($path eq $area);
Branch: 1 branch
BranchTrueFalseTotal
if $path eq $area 4 8 12
2429 }
2430  
2431 2 return;
2432 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2433  
2434 =head2 rootdir
2435  
2436 Returns the document root. This is preferable to looking at DOCUMENT_ROOT
2437 in the environment because it will also work when we're not running as a CGI
2438 script, which is useful for script debugging.
2439  
2440 This can be run as a class or object method.
2441  
2442 use CGI::Info;
2443  
2444 print CGI::Info->rootdir();
2445  
2446 =cut
2447  
2448 36 ▶sub rootdir {
Subroutine rootdir: called CC=12 SCAR=27.7
Pod documented
2449 36 ▶ if($ENV{'C_DOCUMENT_ROOT'} && (-d $ENV{'C_DOCUMENT_ROOT'})) {
Branch: 2 branches
BranchTrueFalseTotal
if ($ENV{'C_DOCUMENT_ROOT'} and -d $ENV{'C_DOCUMENT_ROOT'}) { } 15 21 36
elsif ($ENV{'DOCUMENT_ROOT'} and -d $ENV{'DOCUMENT_ROOT'}) { } 9 22 31
Condition100%3/3
$ENV{"C_DOCUMENT_ROOT"} and -d $ENV{"C_DOCUMENT_ROOT"}
!ll&&!rl&&r
20115
MC/DC100%2/2
$ENV{"C_DOCUMENT_ROOT"} and -d $ENV{"C_DOCUMENT_ROOT"}
$ENV{"C_DOCUMENT_ROOT"} -d $ENV{"C_DOCUMENT_ROOT"}
Truth table100%3/3
A and B
A= $ENV{"C_DOCUMENT_ROOT"}B= -d $ENV{"C_DOCUMENT_ROOT"}
ABresult
0X0
100
111
2450 15 return $ENV{'C_DOCUMENT_ROOT'};
2451 ▶ } elsif($ENV{'DOCUMENT_ROOT'} && (-d $ENV{'DOCUMENT_ROOT'})) {
Condition100%3/3
$ENV{"DOCUMENT_ROOT"} and -d $ENV{"DOCUMENT_ROOT"}
!ll&&!rl&&r
1029
MC/DC100%2/2
$ENV{"DOCUMENT_ROOT"} and -d $ENV{"DOCUMENT_ROOT"}
$ENV{"DOCUMENT_ROOT"} -d $ENV{"DOCUMENT_ROOT"}
Truth table100%3/3
A and B
A= $ENV{"DOCUMENT_ROOT"}B= -d $ENV{"DOCUMENT_ROOT"}
ABresult
0X0
100
111
2452 9 return $ENV{'DOCUMENT_ROOT'};
2453 }
2454 # $0 is tainted under -T; untaint with a permissive but defined capture.
2455 # The leading . before cgi-bin was also a regex bug (matched any char);
2456 # corrected to match a path separator so the kludge fires only on real paths.
2457 12 my ($script_name) = $0 =~ /^(.+)$/;
2458 12 ▶ return '' unless defined $script_name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $script_name 0 12 12
2459  
2460 12 ▶ unless(File::Spec->file_name_is_absolute($script_name)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ("File::Spec"->file_name_is_absolute($script_name)) 12 0 12
2461 12 $script_name = File::Spec->rel2abs($script_name);
2462 }
2463 12 ▶ if($script_name =~ /[\/\\]cgi-bin/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($script_name =~ m([/\\]cgi-bin)) 0 12 12
2464 0 $script_name =~ s/[\/\\]cgi-bin.*//;
2465 }
2466 12 ▶ if(-f $script_name) { # More kludge
Branch: 1 branch
BranchTrueFalseTotal
if (-f $script_name) 12 0 12
2467 12 ▶ if($^O eq 'MSWin32') {
Branch: 1 branch
BranchTrueFalseTotal
if ($^O eq 'MSWin32') { } 0 12 12
2468 0 ▶ if($script_name =~ /(.+)\\.+?$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($script_name =~ /(.+)\\.+?$/) 0 0 0
2469 0 return $1;
2470 }
2471 } else {
2472 12 ▶ if($script_name =~ /(.+)\/.+?$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($script_name =~ m[(.+)/.+?$]) 12 0 12
2473 12 return $1;
2474 }
2475 }
2476 }
2477 0 return $script_name;
2478 }
2479  
2480 =head2 root_dir
2481  
2482 Synonym of rootdir(), for compatibility with L<CHI>.
2483  
2484 =cut
2485  
2486 sub root_dir
2487 9 ▶{
Subroutine root_dir: called CC=3 SCAR=11.0
Pod documented
2488 9 ▶ if($_[0] && ref($_[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_[0] and ref $_[0]) 4 5 9
Condition100%3/3
$_[0] and ref $_[0]
!ll&&!rl&&r
144
MC/DC100%2/2
$_[0] and ref $_[0]
$_[0] ref $_[0]
Truth table100%3/3
A and B
A= $_[0]B= ref $_[0]
ABresult
0X0
100
111
2489 4 my $self = shift;
2490  
2491 4 return $self->rootdir(@_);
2492 }
2493 5 return __PACKAGE__->rootdir(@_);
2494 }
2495  
2496 =head2 documentroot
2497  
2498 Synonym of rootdir(), for compatibility with Apache.
2499  
2500 =cut
2501  
2502 sub documentroot
2503 8 ▶{
Subroutine documentroot: called CC=3 SCAR=11.0
Pod documented
2504 8 ▶ if($_[0] && ref($_[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_[0] and ref $_[0]) 3 5 8
Condition100%3/3
$_[0] and ref $_[0]
!ll&&!rl&&r
233
MC/DC100%2/2
$_[0] and ref $_[0]
$_[0] ref $_[0]
Truth table100%3/3
A and B
A= $_[0]B= ref $_[0]
ABresult
0X0
100
111
2505 3 my $self = shift;
2506  
2507 3 return $self->rootdir(@_);
2508 }
2509 5 return __PACKAGE__->rootdir(@_);
2510 }
2511  
2512 =head2 logdir($dir)
2513  
2514 Gets and sets the name of a directory where you can store logs.
2515  
2516 =over 4
2517  
2518 =item $dir
2519  
2520 Path to the directory where logs will be stored.
2521  
2522 =back
2523  
2524 =cut
2525  
2526 21 ▶sub logdir {
Subroutine logdir: called CC=14 SCAR=26.8
Pod documented
2527 21 my $self = shift;
2528 21 my $dir = shift;
2529  
2530 21 ▶ if(!ref($self)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $self) 1 20 21
2531 1 $self = __PACKAGE__->new();
2532 }
2533  
2534 21 ▶ if($dir) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dir) 11 10 21
2535 11 ▶ if(length($dir) && (-d $dir) && (-w $dir)) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $dir and -d $dir and -w $dir) 5 6 11
Condition83%5/6
length $dir and -d $dir and -w $dir
!ll&&!rl&&r
425
length $dir and -d $dir
!ll&&!rl&&r
047
MC/DC66%2/3
length $dir and -d $dir and -w $dir
length $dir -d $dir -w $dir
Truth table75%3/4
A and B and C
A= length $dirB= -d $dirC= -w $dir
ABCresult
0XX0
10X0
1100
1111
2536 5 return $self->{'logdir'} = $dir;
2537 }
2538 6 $self->_warn("Invalid logdir: $dir");
2539 6 Carp::croak("Invalid logdir: $dir");
2540 }
2541  
2542 10 foreach my $rc($self->{logdir}, $ENV{'LOGDIR'}, Sys::Path->logdir(), $self->tmpdir()) {
2543 26 ▶ if(defined($rc) && length($rc) && (-d $rc) && (-w $rc)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rc and length $rc and -d $rc and -w $rc) 10 16 26
Condition77%7/9
defined $rc and length $rc and -d $rc and -w $rc
!ll&&!rl&&r
16010
defined $rc and length $rc and -d $rc
!ll&&!rl&&r
11510
defined $rc and length $rc
!ll&&!rl&&r
11015
MC/DC50%2/4
defined $rc and length $rc and -d $rc and -w $rc
defined $rc length $rc -d $rc -w $rc
Truth table60%3/5
A and B and C and D
A= defined $rcB= length $rcC= -d $rcD= -w $rc
ABCDresult
0XXX0
10XX0
110X0
11100
11111
2544 10 $dir = $rc;
2545 10 last;
2546 }
2547 }
2548 10 ▶ $self->_warn("Can't determine logdir") if((!defined($dir)) || (length($dir) == 0));
Branch: 1 branch
BranchTrueFalseTotal
if not defined $dir or length $dir == 0 0 10 10
Condition33%1/3
not defined $dir or length $dir == 0
l!l&&r!l&&!r
0010
MC/DC0%0/2
not defined $dir or length $dir == 0
not defined $dir length $dir == 0
Truth table33%1/3
not(A) or B
A= not defined $dirB= length $dir == 0
ABresult
1X1
011
000
2549 10 ▶ $self->{logdir} ||= $dir;
Condition66%2/3
$self->{"logdir"} ||= $dir
l!l&&r!l&&!r
460
MC/DC0%0/2
$self->{"logdir"} ||= $dir
$self->{"logdir"} $dir
Truth table66%2/3
A ||= B
A= $self->{"logdir"}B= $dir
ABresult
1X1
011
000
2550  
2551 10 return $dir;
2552 }
2553  
2554 =head2 is_robot
2555  
2556 Is the visitor a real person or a robot?
2557  
2558 use CGI::Info;
2559  
2560 my $info = CGI::Info->new();
2561 unless($info->is_robot()) {
2562 # update site visitor statistics
2563 }
2564  
2565 If the client is seen to be attempting an SQL injection,
2566 set the HTTP status to 403,
2567 and return 1.
2568  
2569 =cut
2570  
2571 101 ▶sub is_robot {
Subroutine is_robot: called CC=31 SCAR=34.6
Pod documented
2572 101 my $self = shift;
2573  
2574 101 ▶ if(defined($self->{is_robot})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"is_robot"}) 31 70 101
2575 31 return $self->{is_robot};
2576 }
2577  
2578 70 my $agent = $ENV{'HTTP_USER_AGENT'};
2579 70 my $remote = $ENV{'REMOTE_ADDR'};
2580  
2581 70 ▶ unless($remote && $agent) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($remote and $agent) 10 60 70
Condition100%3/3
$remote and $agent
!ll&&!rl&&r
9160
MC/DC100%2/2
$remote and $agent
$remote $agent
Truth table100%3/3
A and B
A= $remoteB= $agent
ABresult
0X0
100
111
2582 # Probably not running in CGI - assume real person
2583 10 return 0;
2584 }
2585  
2586 # SQL injection check MUST run before is_ai(): a WAF block must never be
2587 # bypassed just because the UA also identifies itself as an AI crawler.
2588 # See also params() — patterns here MUST stay in sync with those in params().
2589 # Bounded-lazy .{1,N}? replaces unbounded .+ to prevent O(n²/n³) backtracking
2590 # on long UAs that contain SQL keywords but not the complete injection sequence.
2591 # \b word boundaries prevent false positives on tokens like "SELECTFOO".
2592 60 ▶ if(($agent =~ /\bSELECT\b.{1,500}?\bAND\b/i) ||
Branch: 1 branch
BranchTrueFalseTotal
if ($agent =~ /\bSELECT\b.{1,500}?\bAND\b/i or $agent =~ /\bORDER\s+BY\b/i or $agent =~ /\bOR\s+NOT\b/i or $agent =~ /\bAND\b\s+\d+=\d+/ or $agent =~ /\bTHEN\b.{1,300}?\bELSE\b.{1,300}?\bEND\b/i or $agent =~ /\bAND\b.{1,500}?\bSELECT\b/i or $agent =~ /\sAND\s.{1,500}?\sAND\s/) 11 49 60
Condition77%14/18
$agent =~ /\bSELECT\b.{1,500}?\bAND\b/i or $agent =~ /\bORDER\s+BY\b/i or $agent =~ /\bOR\s+NOT\b/i or $agent =~ /\bAND\b\s+\d+=\d+/ or $agent =~ /\bTHEN\b.{1,300}?\bELSE\b.{1,300}?\bEND\b/i or $agent =~ /\bAND\b.{1,500}?\bSELECT\b/i or $agent =~ /\sAND\s.{1,500}?\sAND\s/
l!l&&r!l&&!r
11049
$agent =~ /\bSELECT\b.{1,500}?\bAND\b/i or $agent =~ /\bORDER\s+BY\b/i or $agent =~ /\bOR\s+NOT\b/i or $agent =~ /\bAND\b\s+\d+=\d+/ or $agent =~ /\bTHEN\b.{1,300}?\bELSE\b.{1,300}?\bEND\b/i or $agent =~ /\bAND\b.{1,500}?\bSELECT\b/i
l!l&&r!l&&!r
11049
$agent =~ /\bSELECT\b.{1,500}?\bAND\b/i or $agent =~ /\bORDER\s+BY\b/i or $agent =~ /\bOR\s+NOT\b/i or $agent =~ /\bAND\b\s+\d+=\d+/ or $agent =~ /\bTHEN\b.{1,300}?\bELSE\b.{1,300}?\bEND\b/i
l!l&&r!l&&!r
11049
$agent =~ /\bSELECT\b.{1,500}?\bAND\b/i or $agent =~ /\bORDER\s+BY\b/i or $agent =~ /\bOR\s+NOT\b/i or $agent =~ /\bAND\b\s+\d+=\d+/
l!l&&r!l&&!r
9249
$agent =~ /\bSELECT\b.{1,500}?\bAND\b/i or $agent =~ /\bORDER\s+BY\b/i or $agent =~ /\bOR\s+NOT\b/i
l!l&&r!l&&!r
9051
$agent =~ /\bSELECT\b.{1,500}?\bAND\b/i or $agent =~ /\bORDER\s+BY\b/i
l!l&&r!l&&!r
8151
MC/DC42%3/7
$agent =~ /\bSELECT\b.{1,500}?\bAND\b/i or $agent =~ /\bORDER\s+BY\b/i or $agent =~ /\bOR\s+NOT\b/i or $agent =~ /\bAND\b\s+\d+=\d+/ or $agent =~ /\bTHEN\b.{1,300}?\bELSE\b.{1,300}?\bEND\b/i or $agent =~ /\bAND\b.{1,500}?\bSELECT\b/i or $agent =~ /\sAND\s.{1,500}?\sAND\s/
$agent =~ /\bSELECT\b.{1,500}?\bAND\b/i $agent =~ /\bORDER\s+BY\b/i $agent =~ /\bOR\s+NOT\b/i $agent =~ /\bAND\b\s+\d+=\d+/ $agent =~ /\bTHEN\b.{1,300}?\bELSE\b.{1,300}?\bEND\b/i $agent =~ /\bAND\b.{1,500}?\bSELECT\b/i $agent =~ /\sAND\s.{1,500}?\sAND\s/
Truth table50%4/8
A or B or C or D or E or F or G
A= $agent =~ /\bSELECT\b.{1,500}?\bAND\b/iB= $agent =~ /\bORDER\s+BY\b/iC= $agent =~ /\bOR\s+NOT\b/iD= $agent =~ /\bAND\b\s+\d+=\d+/E= $agent =~ /\bTHEN\b.{1,300}?\bELSE\b.{1,300}?\bEND\b/iF= $agent =~ /\bAND\b.{1,500}?\bSELECT\b/iG= $agent =~ /\sAND\s.{1,500}?\sAND\s/
ABCDEFGresult
1XXXXXX1
01XXXXX1
001XXXX1
0001XXX1
00001XX1
000001X1
00000011
00000000
2593 ($agent =~ /\bORDER\s+BY\b/i) ||
2594 ($agent =~ /\bOR\s+NOT\b/i) ||
2595 ($agent =~ /\bAND\b\s+\d+=\d+/) ||
2596 ($agent =~ /\bTHEN\b.{1,300}?\bELSE\b.{1,300}?\bEND\b/i) ||
2597 ($agent =~ /\bAND\b.{1,500}?\bSELECT\b/i) ||
2598 ($agent =~ /\sAND\s.{1,500}?\sAND\s/)) {
2599 11 $self->status(403);
2600 11 $self->{is_robot} = 1;
2601 11 ▶ if($ENV{'REMOTE_ADDR'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{'REMOTE_ADDR'}) { } 11 0 11
2602 11 $self->_warn($ENV{'REMOTE_ADDR'} . ": SQL injection attempt blocked for '$agent'");
2603 } else {
2604 0 $self->_warn("SQL injection attempt blocked for '$agent'");
2605 }
2606 11 return 1;
2607 }
2608  
2609 # is_ai implies is_robot: check AI crawlers before the generic bot regex so
2610 # that UAs like ChatGPT-User or Google-Extended (no "bot"/"spider" token)
2611 # are still caught here.
2612 49 ▶ if($self->is_ai()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_ai) 8 41 49
2613 8 return $self->{is_robot} = 1;
2614 }
2615 # '.+bot' was replaced with '\bbot\b' — the leading .+ caused catastrophic
2616 # backtracking on long UAs that contain no 'bot' substring.
2617 41 ▶ if($agent =~ /\bbot\b|axios\/1\.6\.7|bidswitchbot|bytespider|ClaudeBot|Clickagy\.Intelligence\.Bot|msnptc|CriteoBot|is_archiver|backstreet|fuzz faster|linkfluence\.com|spider|scoutjet|gingersoftware|heritrix|dodnetdotcom|yandex|nutch|ezooms|plukkie|nova\.6scan\.com|Twitterbot|adscanner|Go-http-client|python-requests|Mediatoolkitbot|NetcraftSurveyAgent|Expanse|serpstatbot|DreamHost SiteMonitor|techiaith\.cymru|trendictionbot|ias_crawler|WPsec|Yak\/1\.0|ZoominfoBot/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($agent =~ m[\bbot\b|axios/1\.6\.7|bidswitchbot|bytespider|ClaudeBot|Clickagy\.Intelligence\.Bot|msnptc|CriteoBot|is_archiver|backstreet|fuzz faster|linkfluence\.com|spider|scoutjet|gingersoftware|heritrix|dodnetdotcom|yandex|nutch|ezooms|plukkie|nova\.6scan\.com|Twitterbot|adscanner|Go-http-client|python-requests|Mediatoolkitbot|NetcraftSurveyAgent|Expanse|serpstatbot|DreamHost SiteMonitor|techiaith\.cymru|trendictionbot|ias_crawler|WPsec|Yak/1\.0|ZoominfoBot]i) 8 33 41
2618 8 $self->{is_robot} = 1;
2619 8 return 1;
2620 }
2621  
2622 # TODO:
2623 # Download and use list from
2624 # https://raw.githubusercontent.com/mitchellkrogza/apache-ultimate-bad-bot-blocker/refs/heads/master/_generator_lists/bad-user-agents.list
2625  
2626 33 my $key = "$remote/$agent";
2627  
2628 # Check the shared cache BEFORE the referrer scan: the 29-domain referrer
2629 # check is the most expensive path in is_robot() and is unnecessary when a
2630 # prior request already classified this remote/agent pair.
2631 # The SQL injection check above MUST remain before this (security gate).
2632 33 ▶ if($self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"}) 6 27 33
2633 6 ▶ if(my $type = $self->{cache}->get($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $type = $self->{"cache"}->get($key)) 3 3 6
2634 3 return $self->{is_robot} = ($type eq 'robot');
2635 }
2636 }
2637  
2638 30 ▶ if(my $referrer = $ENV{'HTTP_REFERER'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $referrer = $ENV{"HTTP_REFERER"}) 9 21 30
2639 # $CRAWLER_REFERER_RE is compiled once at module load (see top of file):
2640 # replaces List::Util::any { /^\Q$_\E/i } @crawler_lists (29 per-call
2641 # regex compilations + array allocation eliminated).
2642 9 $referrer =~ s/\\/_/g;
2643 9 ▶ if(($referrer =~ /\)/) || ($referrer =~ $CRAWLER_REFERER_RE)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($referrer =~ /\)/ or $referrer =~ /$CRAWLER_REFERER_RE/) 8 1 9
Condition100%3/3
$referrer =~ /\)/ or $referrer =~ /$CRAWLER_REFERER_RE/
l!l&&r!l&&!r
351
MC/DC100%2/2
$referrer =~ /\)/ or $referrer =~ /$CRAWLER_REFERER_RE/
$referrer =~ /\)/ $referrer =~ /$CRAWLER_REFERER_RE/
Truth table100%3/3
A or B
A= $referrer =~ /\)/B= $referrer =~ /$CRAWLER_REFERER_RE/
ABresult
1X1
011
000
2644 8 $self->_debug("is_robot: blocked trawler $referrer");
2645 8 ▶ if($self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"}) 1 7 8
2646 1 $self->{cache}->set($key, 'robot', $CACHE_TTL_ROBOT);
2647 }
2648 8 $self->{is_robot} = 1;
2649 8 return 1;
2650 }
2651 }
2652  
2653 # Don't use HTTP_USER_AGENT to detect more than we really have to since
2654 # that is easily spoofed
2655 22 ▶ if($agent =~ /www\.majestic12\.co\.uk|facebookexternal/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($agent =~ /www\.majestic12\.co\.uk|facebookexternal/) 1 21 22
2656 # Mark Facebook as a search engine, not a robot
2657 1 ▶ if($self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"}) 0 1 1
2658 0 $self->{cache}->set($key, 'search', $CACHE_TTL_SEARCH);
2659 }
2660 1 return 0;
2661 }
2662  
2663 21 ▶ unless($self->{browser_detect}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"browser_detect"}) 10 11 21
2664 10 ▶ if(eval { require HTTP::BrowserDetect; }) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { require HTTP::BrowserDetect } }) 10 0 10
2665 10 HTTP::BrowserDetect->import();
2666 10 $self->{browser_detect} = HTTP::BrowserDetect->new($agent);
2667 }
2668 }
2669 21 ▶ if($self->{browser_detect}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"browser_detect"}) 21 0 21
2670 21 my $is_robot = $self->{browser_detect}->robot();
2671 21 ▶ if(defined($is_robot)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $is_robot) 5 16 21
2672 5 $self->_debug("HTTP::BrowserDetect '$ENV{HTTP_USER_AGENT}' returns $is_robot");
2673 }
2674 21 ▶ $is_robot = (defined($is_robot) && ($is_robot)) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $is_robot && $is_robot ? : 5 16 21
Condition66%2/3
defined $is_robot and $is_robot
!ll&&!rl&&r
1605
MC/DC50%1/2
defined $is_robot and $is_robot
defined $is_robot $is_robot
Truth table66%2/3
A and B
A= defined $is_robotB= $is_robot
ABresult
0X0
100
111
2675 21 $self->_debug("is_robot: $is_robot");
2676  
2677 21 ▶ if($is_robot) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_robot) 5 16 21
2678 5 ▶ if($self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"}) 1 4 5
2679 1 $self->{cache}->set($key, 'robot', $CACHE_TTL_ROBOT);
2680 }
2681 5 $self->{is_robot} = $is_robot;
2682 5 return $is_robot;
2683 }
2684 }
2685  
2686 16 ▶ if($self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"}) 1 15 16
2687 1 $self->{cache}->set($key, 'unknown', $CACHE_TTL_ROBOT);
2688 }
2689 16 $self->{is_robot} = 0;
2690 16 return 0;
2691 }
2692  
2693 =head2 is_search_engine
2694  
2695 Is the visitor a search engine?
2696  
2697 if(CGI::Info->new()->is_search_engine()) {
2698 # display generic information about yourself
2699 } else {
2700 # allow the user to pick and choose something to display
2701 }
2702  
2703 Can be overridden by the IS_SEARCH_ENGINE environment setting
2704  
2705 =cut
2706  
2707 sub is_search_engine
2708 67 ▶{
Subroutine is_search_engine: called CC=30 SCAR=41.9
Pod documented
2709 67 my $self = shift;
2710  
2711 67 ▶ if(defined($self->{is_search_engine})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"is_search_engine"}) 11 56 67
2712 11 return $self->{is_search_engine};
2713 }
2714  
2715 56 ▶ if($ENV{'IS_SEARCH_ENGINE'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{"IS_SEARCH_ENGINE"}) 5 51 56
2716 5 return $ENV{'IS_SEARCH_ENGINE'}
2717 }
2718  
2719 51 my $remote = $ENV{'REMOTE_ADDR'};
2720 51 my $agent = $ENV{'HTTP_USER_AGENT'};
2721  
2722 51 ▶ unless($remote && $agent) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($remote and $agent) 13 38 51
Condition100%3/3
$remote and $agent
!ll&&!rl&&r
12138
MC/DC100%2/2
$remote and $agent
$remote $agent
Truth table100%3/3
A and B
A= $remoteB= $agent
ABresult
0X0
100
111
2723 # Probably not running in CGI - assume not a search engine
2724 13 return 0;
2725 }
2726  
2727 # Build the cache key once; reuse $key for every subsequent set() call.
2728 38 my $key = "$remote/$agent";
2729  
2730 38 ▶ if($self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"}) 3 35 38
2731 3 ▶ if(my $type = $self->{cache}->get($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $type = $self->{"cache"}->get($key)) 1 2 3
2732 # Write to is_search_engine (not the old is_search typo) so the
2733 # instance-level guard at the top of this method actually fires on
2734 # the next call, avoiding a redundant shared-cache round-trip.
2735 1 return $self->{is_search_engine} = ($type eq 'search');
2736 }
2737 }
2738  
2739 # Don't use HTTP_USER_AGENT to detect more than we really have to since
2740 # that is easily spoofed
2741 37 ▶ if($agent =~ /www\.majestic12\.co\.uk|facebookexternal/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($agent =~ /www\.majestic12\.co\.uk|facebookexternal/) 3 34 37
2742 # Mark Facebook as a search engine, not a robot
2743 3 ▶ if($self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"}) 0 3 3
2744 0 $self->{cache}->set($key, 'search', $CACHE_TTL_SEARCH);
2745 }
2746 3 return 1;
2747 }
2748  
2749 34 ▶ unless($self->{browser_detect}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"browser_detect"}) 16 18 34
2750 16 ▶ if(eval { require HTTP::BrowserDetect; }) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { require HTTP::BrowserDetect } }) 16 0 16
2751 16 HTTP::BrowserDetect->import();
2752 16 $self->{browser_detect} = HTTP::BrowserDetect->new($agent);
2753 }
2754 }
2755 34 ▶ if(my $browser = $self->{browser_detect}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $browser = $self->{"browser_detect"}) 34 0 34
2756 34 ▶ my $is_search = ($browser->google() || $browser->msn() || $browser->baidu() || $browser->altavista() || $browser->yahoo() || $browser->bingbot());
Condition80%12/15
$browser->google || $browser->msn || $browser->baidu || $browser->altavista || $browser->yahoo || $browser->bingbot
l!l&&r!l&&!r
8224
$browser->google or $browser->msn or $browser->baidu or $browser->altavista or $browser->yahoo
l!l&&r!l&&!r
8026
$browser->google or $browser->msn or $browser->baidu or $browser->altavista
l!l&&r!l&&!r
8026
$browser->google or $browser->msn or $browser->baidu
l!l&&r!l&&!r
6226
$browser->google or $browser->msn
l!l&&r!l&&!r
6028
MC/DC50%3/6
$browser->google || $browser->msn || $browser->baidu || $browser->altavista || $browser->yahoo || $browser->bingbot
$browser->google $browser->msn $browser->baidu $browser->altavista $browser->yahoo $browser->bingbot
Truth table57%4/7
A or B or C or D or E || F
A= $browser->googleB= $browser->msnC= $browser->baiduD= $browser->altavistaE= $browser->yahooF= $browser->bingbot
ABCDEFresult
1XXXXX1
01XXXX1
001XXX1
0001XX1
00001X1
0000011
0000000
2757 34 ▶ if(!$is_search) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($is_search) 24 10 34
2758 24 ▶ if(($agent =~ /SeznamBot\//) ||
Branch: 1 branch
BranchTrueFalseTotal
if ($agent =~ m[SeznamBot/] or $agent =~ m[Google-InspectionTool/] or $agent =~ m[Googlebot/]) 3 21 24
Condition83%5/6
$agent =~ m[SeznamBot/] or $agent =~ m[Google-InspectionTool/] or $agent =~ m[Googlebot/]
l!l&&r!l&&!r
3021
$agent =~ m[SeznamBot/] or $agent =~ m[Google-InspectionTool/]
l!l&&r!l&&!r
2121
MC/DC66%2/3
$agent =~ m[SeznamBot/] or $agent =~ m[Google-InspectionTool/] or $agent =~ m[Googlebot/]
$agent =~ m[SeznamBot/] $agent =~ m[Google-InspectionTool/] $agent =~ m[Googlebot/]
Truth table75%3/4
A or B or C
A= $agent =~ m[SeznamBot/]B= $agent =~ m[Google-InspectionTool/]C= $agent =~ m[Googlebot/]
ABCresult
1XX1
01X1
0011
0000
2759 ($agent =~ /Google-InspectionTool\//) ||
2760 ($agent =~ /Googlebot\//)) {
2761 3 $is_search = 1;
2762 }
2763 }
2764 34 ▶ if($is_search && $self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_search and $self->{"cache"}) 1 33 34
Condition100%3/3
$is_search and $self->{"cache"}
!ll&&!rl&&r
21121
MC/DC100%2/2
$is_search and $self->{"cache"}
$is_search $self->{"cache"}
Truth table100%3/3
A and B
A= $is_searchB= $self->{"cache"}
ABresult
0X0
100
111
2765 1 $self->{cache}->set($key, 'search', $CACHE_TTL_SEARCH);
2766 }
2767 34 return $self->{is_search_engine} = $is_search;
2768 }
2769  
2770 # Untaint $remote before passing to inet_aton: under -T, tainted data
2771 # causes a fatal "Insecure dependency" in inet_aton. The strict IPv4
2772 # regex also rejects any non-address garbage that could reach this path.
2773 0 my ($safe_remote) = $remote =~ /^(\d{1,3}(?:\.\d{1,3}){3})$/;
2774 0 ▶ unless(defined $safe_remote) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $safe_remote) 0 0 0
2775 0 $self->{is_search_engine} = 0;
2776 0 return 0;
2777 }
2778 # TODO: DNS lookup, not gethostbyaddr - though that will be slow
2779 0 ▶ my $hostname = gethostbyaddr(inet_aton($safe_remote), AF_INET) || $safe_remote;
Condition0%0/3
gethostbyaddr(inet_aton($safe_remote), 2) || $safe_remote
l!l&&r!l&&!r
000
MC/DC0%0/2
gethostbyaddr(inet_aton($safe_remote), 2) || $safe_remote
gethostbyaddr(inet_aton($safe_remote), 2) $safe_remote
Truth table0%0/3
A || B
A= gethostbyaddr(inet_aton($safe_remote), 2)B= $safe_remote
ABresult
1X1
011
000
2780  
2781 0 my @cidr_blocks = ('47.235.0.0/12'); # Alibaba
2782  
2783 # \b word boundaries prevent false positives like "notgoogle.example.com".
2784 # /i because DNS hostnames are case-insensitive.
2785 0 ▶ if((defined($hostname) && ($hostname =~ /\b(?:google|msnbot|bingbot|amazonbot|GPTBot)\b/i) && ($hostname !~ /^google-proxy/i)) ||
Branch: 1 branch
BranchTrueFalseTotal
if (defined $hostname and $hostname =~ /\b(?:google|msnbot|bingbot|amazonbot|GPTBot)\b/i and not $hostname =~ /^google-proxy/i or Net::CIDR::cidrlookup($remote, @cidr_blocks)) 0 0 0
Condition0%0/9
defined $hostname and $hostname =~ /\b(?:google|msnbot|bingbot|amazonbot|GPTBot)\b/i and not $hostname =~ /^google-proxy/i or Net::CIDR::cidrlookup($remote, @cidr_blocks)
l!l&&r!l&&!r
000
defined $hostname and $hostname =~ /\b(?:google|msnbot|bingbot|amazonbot|GPTBot)\b/i and not $hostname =~ /^google-proxy/i
!ll&&!rl&&r
000
defined $hostname and $hostname =~ /\b(?:google|msnbot|bingbot|amazonbot|GPTBot)\b/i
!ll&&!rl&&r
000
MC/DC0%0/4
defined $hostname and $hostname =~ /\b(?:google|msnbot|bingbot|amazonbot|GPTBot)\b/i and not $hostname =~ /^google-proxy/i or Net::CIDR::cidrlookup($remote, @cidr_blocks)
defined $hostname $hostname =~ /\b(?:google|msnbot|bingbot|amazonbot|GPTBot)\b/i not $hostname =~ /^google-proxy/i Net::CIDR::cidrlookup($remote, @cidr_blocks)
Truth table0%0/7
A and B and not(C) or D
A= defined $hostnameB= $hostname =~ /\b(?:google|msnbot|bingbot|amazonbot|GPTBot)\b/iC= not $hostname =~ /^google-proxy/iD= Net::CIDR::cidrlookup($remote, @cidr_blocks)
ABCDresult
111X1
0XX11
10X11
11011
0XX00
10X00
11000
2786 (Net::CIDR::cidrlookup($remote, @cidr_blocks))) {
2787 0 ▶ if($self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"}) 0 0 0
2788 0 $self->{cache}->set($key, 'search', $CACHE_TTL_SEARCH);
2789 }
2790 0 $self->{is_search_engine} = 1;
2791 0 return 1;
2792 }
2793  
2794 0 $self->{is_search_engine} = 0;
2795 0 return 0;
2796 }
2797  
2798 =head2 is_ai
2799  
2800 Returns a boolean indicating whether the visitor is a known AI training or
2801 inference crawler (e.g. GPTBot, ClaudeBot, PerplexityBot).
2802  
2803 Use this to withhold training data, serve an opt-out notice, or log AI traffic
2804 separately from regular robot traffic.
2805  
2806 B<Invariant>: when C<is_ai()> returns true, C<is_robot()> also returns true,
2807 regardless of the order in which the two methods are called.
2808  
2809 Can be overridden by the C<IS_AI> environment variable.
2810  
2811 =head3 EXAMPLE
2812  
2813 use CGI::Info;
2814  
2815 my $info = CGI::Info->new();
2816 if ($info->is_ai()) {
2817 # Decline to serve training data to AI scrapers
2818 print "Status: 403 Forbidden\r\n\r\n";
2819 exit;
2820 }
2821  
2822 # Route AI crawlers to a lightweight page instead of blocking them
2823 if ($info->is_ai()) {
2824 serve_ai_summary();
2825 } else {
2826 serve_full_page();
2827 }
2828  
2829 =head3 API SPECIFICATION
2830  
2831 =head4 Input
2832  
2833 No arguments beyond the implicit object reference (C<$self>).
2834  
2835 # Params::Validate::Strict schema -- no parameters
2836 {}
2837  
2838 =head4 Output
2839  
2840 # Return::Set schema
2841 {
2842 type => SCALAR,
2843 values => [ 0, 1 ],
2844 }
2845  
2846 Returns C<1> if the visiting client is identified as an AI training or
2847 inference crawler; C<0> otherwise.
2848  
2849 =head3 MESSAGES
2850  
2851 This method produces no log messages of its own. Upstream callers such as
2852 C<is_robot()> may emit WAF warnings; see L</is_robot> for that table.
2853  
2854 =head3 PSEUDOCODE
2855  
2856 function is_ai(self):
2857 if self.{is_ai} is defined:
2858 return self.{is_ai} # instance-level cache
2859  
2860 if IS_AI environment variable is set:
2861 return self.{is_ai} = IS_AI ? 1 : 0 # override; no robot sync needed
2862 # because is_robot() calls is_ai()
2863  
2864 ua = HTTP_USER_AGENT
2865 remote = REMOTE_ADDR
2866  
2867 if not (remote and ua):
2868 return 0 # not a CGI request; assume human
2869  
2870 if ua matches any AI_PAT token (case-insensitive):
2871 self.{is_robot} = 1 # enforce is_ai => is_robot
2872 return self.{is_ai} = 1
2873  
2874 return self.{is_ai} = 0
2875  
2876 =cut
2877  
2878 164 ▶sub is_ai {
Subroutine is_ai: called CC=7 SCAR=19.5
Pod documented
2879 164 my $self = shift;
2880  
2881 # Return cached result if already determined
2882 164 ▶ if(defined($self->{is_ai})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"is_ai"}) 40 124 164
2883 40 return $self->{is_ai};
2884 }
2885  
2886 # Allow environment variable override for testing or manual classification
2887 124 ▶ if(defined(my $override = $ENV{'IS_AI'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $override = $ENV{"IS_AI"})) 14 110 124
2888 14 ▶ return $self->{is_ai} = $override ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$override ? : 9 5 14
2889 }
2890  
2891 110 my $agent = $ENV{'HTTP_USER_AGENT'};
2892 110 my $remote = $ENV{'REMOTE_ADDR'};
2893  
2894 110 ▶ unless($remote && $agent) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($remote and $agent) 15 95 110
Condition100%3/3
$remote and $agent
!ll&&!rl&&r
13295
MC/DC100%2/2
$remote and $agent
$remote $agent
Truth table100%3/3
A and B
A= $remoteB= $agent
ABresult
0X0
100
111
2895 # Probably not running in CGI - assume not an AI crawler
2896 15 return 0;
2897 }
2898  
2899 # Known AI training and inference crawlers, matched against the User-Agent.
2900 # We intentionally do not consult the shared IP/agent cache here: is_robot()
2901 # stores 'robot' for many of the same UAs, and reading 'robot' != 'ai' would
2902 # produce a false negative. Instance-level caching ($self->{is_ai}) above is
2903 # sufficient to avoid redundant regex evaluation within a single request.
2904 # Sources: vendor documentation and public bot lists.
2905 # Anthropic: ClaudeBot, Claude-Web, anthropic-ai
2906 # OpenAI: GPTBot, ChatGPT-User, OAI-SearchBot
2907 # Google: Google-Extended (AI training opt-out token)
2908 # Meta: meta-externalagent, FacebookBot (AI training)
2909 # Apple: Applebot-Extended (AI training subset)
2910 # Perplexity: PerplexityBot
2911 # Amazon: Amazonbot (Amazon AI / Alexa AI)
2912 # You.com: YouBot
2913 # Diffbot: Diffbot
2914 # Cohere: cohere-ai
2915 # Common Crawl: CCBot (primary data source for many LLM trainers)
2916 # ByteDance: Bytespider (TikTok / AI training)
2917 # Allen AI: AI2Bot
2918 # Timpi: TimpiBot
2919 95 ▶ if($agent =~ /ClaudeBot|Claude-Web|anthropic-ai|GPTBot|ChatGPT-User|OAI-SearchBot|Google-Extended|meta-externalagent|FacebookBot|Applebot-Extended|PerplexityBot|Amazonbot|YouBot|Diffbot|cohere-ai|CCBot|Bytespider|AI2Bot|TimpiBot/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($agent =~ /ClaudeBot|Claude-Web|anthropic-ai|GPTBot|ChatGPT-User|OAI-SearchBot|Google-Extended|meta-externalagent|FacebookBot|Applebot-Extended|PerplexityBot|Amazonbot|YouBot|Diffbot|cohere-ai|CCBot|Bytespider|AI2Bot|TimpiBot/i) 45 50 95
2920 # Enforce is_ai => is_robot so callers need not check both
2921 45 $self->{is_robot} = 1;
2922 45 return $self->{is_ai} = 1;
2923 }
2924  
2925 50 $self->{is_ai} = 0;
2926 50 return 0;
2927 }
2928  
2929 =head2 browser_type
2930  
2931 Returns a string classifying the visitor's client. The possible values are:
2932  
2933 =over 4
2934  
2935 =item * C<'mobile'> -- smartphone or tablet (checked first)
2936  
2937 =item * C<'ai'> -- known AI training or inference crawler (see L</is_ai>)
2938  
2939 =item * C<'search'> -- search-engine crawler
2940  
2941 =item * C<'robot'> -- other automated client
2942  
2943 =item * C<'web'> -- ordinary desktop or laptop browser
2944  
2945 =back
2946  
2947 use Carp;
2948 use Template;
2949 use CGI::Info;
2950  
2951 my $info = CGI::Info->new();
2952 my $dir = $info->rootdir() . '/templates/' . $info->browser_type();
2953  
2954 my $filename = ref($info);
2955 $filename =~ s/::/\//g;
2956 $filename = "$dir/$filename.tmpl";
2957  
2958 (-f $filename && -r $filename)
2959 or croak "Cannot open template '$filename'";
2960  
2961 my $template = Template->new();
2962 $template->process($filename, {}) or croak $template->error();
2963  
2964 =cut
2965  
2966 56 ▶sub browser_type {
Subroutine browser_type: called CC=5 SCAR=16.1
Pod documented
2967 56 my $self = shift;
2968  
2969 56 ▶ if($self->is_mobile()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_mobile) 16 40 56
2970 16 return 'mobile';
2971 }
2972 40 ▶ if($self->is_ai()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_ai) 11 29 40
2973 11 return 'ai';
2974 }
2975 29 ▶ if($self->is_search_engine()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_search_engine) 9 20 29
2976 9 return 'search';
2977 }
2978 20 ▶ if($self->is_robot()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_robot) 7 13 20
2979 7 return 'robot';
2980 }
2981 13 return 'web';
2982 }
2983  
2984 =head2 get_cookie
2985  
2986 Returns a cookie's value, or undef if no name is given, or the requested
2987 cookie isn't in the jar.
2988  
2989 Deprecated - use cookie() instead.
2990  
2991 use CGI::Info;
2992  
2993 my $i = CGI::Info->new();
2994 my $name = $i->get_cookie(cookie_name => 'name');
2995 print "Your name is $name\n";
2996 my $address = $i->get_cookie('address');
2997 print "Your address is $address\n";
2998  
2999 =cut
3000  
3001 17 ▶sub get_cookie {
Subroutine get_cookie: called CC=1 SCAR=0.0
Pod documented
3002 17 my $self = shift;
3003  
3004 17 return $self->cookie(\@_);
3005 }
3006  
3007 =head2 cookie
3008  
3009 Returns a cookie's value, or undef if no name is given, or the requested
3010 cookie isn't in the jar.
3011 API is the same as "param",
3012 it will replace the "get_cookie" method in the future.
3013  
3014 use CGI::Info;
3015  
3016 my $name = CGI::Info->new()->cookie('name');
3017 print "Your name is $name\n";
3018  
3019  
3020 =head3 API SPECIFICATION
3021  
3022 =head4 INPUT
3023  
3024 {
3025 cookie_name => {
3026 'type' => 'string',
3027 'min' => 1,
3028 'matches' => qr/^[!#-'*+\-.\^_`|~0-9A-Za-z]+$/ # RFC6265
3029 }
3030 }
3031  
3032 =head4 OUTPUT
3033  
3034 Cookie not set: C<undef>
3035  
3036 Cookie set:
3037  
3038 {
3039 type => 'string',
3040 optional => 1,
3041 matches => qr/ # RFC6265
3042 ^
3043 (?:
3044 "[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*" # quoted
3045 | [\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]* # unquoted
3046 )
3047 $
3048 /x
3049 }
3050  
3051 =cut
3052  
3053 sub cookie
3054 72 ▶{
Subroutine cookie: called CC=5 SCAR=17.5
Pod documented
3055 72 my $self = shift;
3056 72 my $params = Params::Validate::Strict::validate_strict({
3057 args => Params::Get::get_params('cookie_name', @_),
3058 schema => {
3059 cookie_name => {
3060 'type' => 'string',
3061 'min' => 1,
3062 'matches' => qr/^[!#-'*+\-.\^_`|~0-9A-Za-z]+$/ # RFC6265
3063 }
3064 }
3065 });
3066  
3067 66 my $field = $params->{'cookie_name'};
3068  
3069 # TODO: Unreachable code detected during path analysis. Investigate for removal.
3070 # validate_strict() above enforces type=>string, min=>1 and croaks for undef/ref
3071 # inputs before control ever reaches these two guards.
3072 66 ▶ if(!defined($field)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $field) 0 66 66
3073 0 $self->_error('what cookie do you want?');
3074 0 Carp::croak('what cookie do you want?');
3075 0 return; # TODO: Unreachable code detected during path analysis. Investigate for removal.
3076 }
3077 66 ▶ if(ref($field)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $field) 0 66 66
3078 0 $self->_error('Cookie name should be a string');
3079 0 Carp::croak('Cookie name should be a string');
3080 0 return; # TODO: Unreachable code detected during path analysis. Investigate for removal.
3081 }
3082  
3083 # Load cookies if not already loaded
3084 66 ▶ unless($self->{jar}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"jar"}) 41 25 66
3085 41 ▶ if(defined $ENV{'HTTP_COOKIE'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ENV{"HTTP_COOKIE"}) 36 5 41
3086 # Truncate at the first CR or LF before parsing.
3087 # HTTP header values cannot span lines; anything after a newline is
3088 # injected content (e.g. "session=abc\r\nSet-Cookie: admin=1").
3089 # Stripping rather than truncating would leave the injected text
3090 # concatenated onto a legitimate value, so we discard from \r/\n onward.
3091 36 (my $raw_cookie = $ENV{'HTTP_COOKIE'}) =~ s/[\r\n].*$//s;
3092  
3093 # grep { /=/ } filters out malformed tokens (empty strings, bare
3094 # semicolons, entries with no name=value separator) that would
3095 # otherwise cause split(/=/, $_, 2) to return a single-element list
3096 # and make the flattened list odd-length, corrupting the hash.
3097 $self->{jar} = {
3098 62 map { split(/=/, $_, 2) }
3099 36 grep { /=/ }
3100 split(/; /, $raw_cookie)
3101 };
3102 }
3103 }
3104  
3105 # Return the cookie value if it exists, otherwise return undef
3106 66 return $self->{jar}{$field};
3107 }
3108  
3109 =head2 status($status)
3110  
3111 Sets or returns the status of the object,
3112 200 for OK,
3113 otherwise an HTTP error code
3114  
3115 =over 4
3116  
3117 =item $status
3118  
3119 Optional integer value to be set or retrieved.
3120 If omitted, the value is retrieved.
3121  
3122 =back
3123  
3124 =cut
3125  
3126 sub status
3127 470 ▶{
Subroutine status: called CC=10 SCAR=23.0
Pod documented
3128 470 my $self = shift;
3129 470 my $status = shift;
3130  
3131 # Set status if provided
3132 470 ▶ return $self->{status} = $status if(defined($status));
Branch: 1 branch
BranchTrueFalseTotal
if defined $status 234 236 470
3133  
3134 # Determine status based on request method if status is not set
3135 236 ▶ unless (defined $self->{status}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"status"}) 55 181 236
3136 55 my $method = $ENV{'REQUEST_METHOD'};
3137  
3138 55 ▶ return 405 if $method && ($method eq 'OPTIONS' || $method eq 'DELETE');
Branch: 1 branch
BranchTrueFalseTotal
if $method and $method eq "OPTIONS" || $method eq "DELETE" 6 49 55
Condition100%6/6
$method and $method eq "OPTIONS" || $method eq "DELETE"
!ll&&!rl&&r
16336
$method eq "OPTIONS" or $method eq "DELETE"
l!l&&r!l&&!r
3333
MC/DC100%3/3
$method and $method eq "OPTIONS" || $method eq "DELETE"
$method $method eq "OPTIONS" $method eq "DELETE"
Truth table100%4/4
A and B or C
A= $methodB= $method eq "OPTIONS"C= $method eq "DELETE"
ABCresult
0XX0
1000
11X1
1011
3139 49 ▶ return 411 if $method && ($method eq 'POST' && !defined $ENV{'CONTENT_LENGTH'});
Branch: 1 branch
BranchTrueFalseTotal
if $method and ($method eq "POST" and not defined $ENV{"CONTENT_LENGTH"}) 4 45 49
Condition100%6/6
$method and ($method eq "POST" and not defined $ENV{"CONTENT_LENGTH"})
!ll&&!rl&&r
16294
$method eq "POST" and not defined $ENV{"CONTENT_LENGTH"}
!ll&&!rl&&r
2364
MC/DC100%3/3
$method and ($method eq "POST" and not defined $ENV{"CONTENT_LENGTH"})
$method $method eq "POST" not defined $ENV{"CONTENT_LENGTH"}
Truth table100%4/4
A and B and not(C)
A= $methodB= $method eq "POST"C= not defined $ENV{"CONTENT_LENGTH"}
ABCresult
0XX0
10X0
1100
1111
3140  
3141 45 return 200;
3142 }
3143  
3144 # Return current status or 200 by default
3145 181 ▶ return $self->{status} || 200;
Condition100%2/2
$self->{'status'} || 200
l!l
1783
MC/DC100%1/1
$self->{'status'} || 200
$self->{'status'}
Truth table100%2/2
A
A= $self->{'status'}
Aresult
11
00
3146 }
3147  
3148 =head2 messages
3149  
3150 Returns the messages that the object has generated as a ref to an array of hashes.
3151  
3152 my @messages;
3153 if(my $w = $info->messages()) {
3154 @messages = map { $_->{'message'} } @{$w};
3155 } else {
3156 @messages = ();
3157 }
3158 print STDERR join(';', @messages), "\n";
3159  
3160 =cut
3161  
3162 sub messages
3163 48 ▶{
Subroutine messages: called CC=1 SCAR=0.0
Pod documented
3164 48 my $self = shift;
3165  
3166 48 return $self->{'messages'};
3167 }
3168  
3169 =head2 messages_as_string
3170  
3171 Returns the messages of that the object has generated as a string.
3172  
3173 =cut
3174  
3175 sub messages_as_string
3176 30 ▶{
Subroutine messages_as_string: called CC=2 SCAR=6.9
Pod documented
3177 30 my $self = shift;
3178  
3179 30 ▶ if(scalar($self->{'messages'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar $self->{"messages"}) 26 4 30
3180 26 my @messages = map { $_->{'message'} } @{$self->{'messages'}};
3181 26 return join('; ', @messages);
3182 }
3183 4 return '';
3184 }
3185  
3186 =head2 cache($cache)
3187  
3188 Get/set the internal cache system.
3189  
3190 Use this rather than pass the cache argument to C<new()> if you see these error messages,
3191 "(in cleanup) Failed to get MD5_CTX pointer".
3192 It's some obscure problem that I can't work out,
3193 but calling this after C<new()> works.
3194  
3195 =over 4
3196  
3197 =item $cache
3198  
3199 Optional cache object.
3200 When not given,
3201 returns the current cache object.
3202  
3203 =back
3204  
3205 =cut
3206  
3207 sub cache
3208 29 ▶{
Subroutine cache: called CC=5 SCAR=16.1
Pod documented
3209 29 my $self = shift;
3210 29 my $cache = shift;
3211  
3212 29 ▶ if($cache) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cache) 19 10 29
3213 19 ▶ croak(ref($self), ':cache($cache) is not an object') if(!Scalar::Util::blessed($cache));
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($cache) 4 15 19
3214 15 ▶ croak(ref($self), ':cache($cache) does not support the get() method') if(!$cache->can('get'));
Branch: 1 branch
BranchTrueFalseTotal
unless $cache->can("get") 3 12 15
3215 12 ▶ croak(ref($self), ':cache($cache) does not support the set() method') if(!$cache->can('set'));
Branch: 1 branch
BranchTrueFalseTotal
unless $cache->can("set") 2 10 12
3216 10 $self->{'cache'} = $cache;
3217 }
3218 20 return $self->{'cache'};
3219 }
3220  
3221 =head2 set_logger
3222  
3223 Sets the class, array, code reference, or file that will be used for logging.
3224  
3225 Sometimes you don't know what the logger is until you've instantiated the class.
3226 This function fixes the catch-22 situation.
3227  
3228 =cut
3229  
3230 sub set_logger
3231 17 ▶{
Subroutine set_logger: called CC=3 SCAR=11.0
Pod documented
3232 17 my $self = shift;
3233 17 my $params = Params::Get::get_params('logger', @_);
3234  
3235 17 ▶ if(my $logger = $params->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $logger = $params->{'logger'}) { } 15 2 17
3236 15 ▶ if(Scalar::Util::blessed($logger)) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($logger)) { } 10 5 15
3237 10 $self->{'logger'} = $logger;
3238 } else {
3239 5 $self->{'logger'} = Log::Abstraction->new($logger);
3240 }
3241 } else {
3242 2 $self->{'logger'} = Log::Abstraction->new();
3243 }
3244 17 return $self;
3245 }
3246  
3247 # Log and remember a message
3248 3187 ▶sub _log :Protected {
Subroutine _log: called CC=3 SCAR=11.0
3249 3187 my ($self, $level, @messages) = @_;
3250  
3251 # Filter once; reuse for both the in-memory store and the logger call.
3252 # The former inner scalar(@messages) guard was always true inside this block.
3253 3187 my @defined_msgs = grep { defined } @messages;
3254 3187 ▶ return unless @defined_msgs;
Branch: 1 branch
BranchTrueFalseTotal
unless @defined_msgs 2 3185 3187
3255  
3256 # Note: consider adding caller's function name to log messages in a future release
3257 3185 push @{$self->{'messages'}}, { level => $level, message => join(' ', @defined_msgs) };
3258  
3259 3185 ▶ if(my $logger = $self->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $logger = $self->{"logger"}) 3179 6 3185
3260 3179 $logger->$level(join('', @defined_msgs));
3261 }
3262 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3263  
3264 1919 ▶sub _debug :Protected {
Subroutine _debug: called CC=1 SCAR=0.0
3265 1919 my $self = shift;
3266 1919 $self->_log('debug', @_);
3267 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3268  
3269 87 ▶sub _info :Protected {
Subroutine _info: called CC=1 SCAR=0.0
3270 87 my $self = shift;
3271 87 $self->_log('info', @_);
3272 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3273  
3274 1 ▶sub _notice :Protected {
Subroutine _notice: called CC=1 SCAR=0.0
3275 1 my $self = shift;
3276 1 $self->_log('notice', @_);
3277 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3278  
3279 851 ▶sub _trace :Protected {
Subroutine _trace: called CC=1 SCAR=0.0
3280 851 my $self = shift;
3281 851 $self->_log('trace', @_);
3282 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3283  
3284 # Emit a warning message somewhere
3285 318 ▶sub _warn :Protected {
Subroutine _warn: called CC=2 SCAR=6.9
3286 318 my $self = shift;
3287 318 my $params = Params::Get::get_params('warning', @_);
3288  
3289 318 $self->_log('warn', $params->{'warning'});
3290 303 ▶ if(!defined($self->{'logger'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $self->{"logger"}) 3 300 303
3291 3 Carp::carp($params->{'warning'});
3292 }
3293 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3294  
3295 # Emit an error message somewhere
3296 4 ▶sub _error :Protected {
Subroutine _error: called CC=2 SCAR=6.9
3297 4 my $self = shift;
3298 4 my $params = Params::Get::get_params('warning', @_);
3299  
3300 4 $self->_log('error', $params->{'warning'});
3301 4 ▶ if(!defined($self->{'logger'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $self->{"logger"}) 2 2 4
3302 2 Carp::croak($params->{'warning'});
3303 }
3304 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3305  
3306 # Ensure all environment variables are sanitized and validated before use.
3307 # Use regular expressions to enforce strict input formats.
3308 396 ▶sub _get_env :Protected {
Subroutine _get_env: called CC=3 SCAR=11.0
3309 396 my ($self, $var) = @_;
3310  
3311 396 ▶ return unless defined $ENV{$var};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ENV{$var} 89 307 396
3312  
3313 # Strict sanitization: allow alphanumeric and limited special characters
3314 307 ▶ if($ENV{$var} =~ /^[\w\.\-\/:\\]+$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{$var} =~ m(^[\w\.\-/:\\]+$)) 301 6 307
3315 301 return $ENV{$var};
3316 }
3317 6 $self->_warn("Invalid value in environment variable: $var");
3318  
3319 6 return;
3320 38 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
3321  
3322 =head2 reset
3323  
3324 Class method to reset the class.
3325 You should do this in an FCGI environment before instantiating,
3326 but nowhere else.
3327  
3328 =cut
3329  
3330 834 ▶sub reset {
Subroutine reset: called CC=2 SCAR=6.9
Pod documented
3331 834 my $class = shift;
3332  
3333 834 ▶ unless($class eq __PACKAGE__) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($class eq __PACKAGE__) 4 830 834
3334 4 carp('Reset is a class method');
3335 3 return;
3336 }
3337  
3338 830 $stdin_data = undef;
3339 }
3340  
3341 sub AUTOLOAD
3342 1205 ▶{
Subroutine AUTOLOAD: called CC=10 SCAR=24.2
3343 1205 our $AUTOLOAD;
3344  
3345 1205 ▶ my $self = shift or return;
Branch: 1 branch
BranchTrueFalseTotal
my $self = shift() or return 1205 0 1205
3346  
3347 1205 ▶ return if(!defined($AUTOLOAD));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $CGI::Info::AUTOLOAD 0 1205 1205
3348  
3349 # Extract the method name from the AUTOLOAD variable
3350 1205 my ($method) = $AUTOLOAD =~ /::(\w+)$/;
3351  
3352 # Skip if called on destruction
3353 1205 ▶ return if($method eq 'DESTROY');
Branch: 1 branch
BranchTrueFalseTotal
if $method eq "DESTROY" 1180 25 1205
3354  
3355 25 ▶ Carp::croak(__PACKAGE__, ": Unknown method $method") if(!ref($self));
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self 1 24 25
3356  
3357 # Allow the AUTOLOAD feature to be disabled
3358 24 ▶ Carp::croak(__PACKAGE__, ": Unknown method $method") if(exists($self->{'auto_load'}) && boolean($self->{'auto_load'})->isFalse());
Branch: 1 branch
BranchTrueFalseTotal
if exists $self->{"auto_load"} and &boolean($self->{"auto_load"})->isFalse 5 19 24
Condition66%2/3
exists $self->{"auto_load"} and &boolean($self->{"auto_load"})->isFalse
!ll&&!rl&&r
1905
MC/DC50%1/2
exists $self->{"auto_load"} and &boolean($self->{"auto_load"})->isFalse
exists $self->{"auto_load"} &boolean($self->{"auto_load"})->isFalse
Truth table66%2/3
A and B
A= exists $self->{"auto_load"}B= &boolean($self->{"auto_load"})->isFalse
ABresult
0X0
100
111
3359  
3360 # Ensure the method is called on the correct package object or a subclass
3361 19 ▶ return unless((ref($self) eq __PACKAGE__) || (UNIVERSAL::isa((caller)[0], __PACKAGE__)));
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self eq __PACKAGE__ or UNIVERSAL::isa((&CORE::GLOBAL::caller())[0], __PACKAGE__) 0 19 19
Condition33%1/3
ref $self eq __PACKAGE__ or UNIVERSAL::isa((&CORE::GLOBAL::caller())[0], __PACKAGE__)
l!l&&r!l&&!r
1900
MC/DC0%0/2
ref $self eq __PACKAGE__ or UNIVERSAL::isa((&CORE::GLOBAL::caller())[0], __PACKAGE__)
ref $self eq __PACKAGE__ UNIVERSAL::isa((&CORE::GLOBAL::caller())[0], __PACKAGE__)
Truth table33%1/3
A or B
A= ref $self eq __PACKAGE__B= UNIVERSAL::isa((&CORE::GLOBAL::caller())[0], __PACKAGE__)
ABresult
1X1
011
000
3362  
3363 # TODO: Unreachable code detected during path analysis. Investigate for removal.
3364 # $method is captured via /::(\w+)$/ which only yields \w+ chars; a digit-leading
3365 # name is possible in theory but Perl's method dispatch never generates one.
3366 19 ▶ Carp::croak(__PACKAGE__, ": Invalid method name: $method") unless $method =~ /^[a-zA-Z_][a-zA-Z0-9_]*$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $method =~ /^[a-zA-Z_][a-zA-Z0-9_]*$/ 0 19 19
3367  
3368 # Delegate to the param method
3369 19 return $self->param($method);
3370 }
3371  
3372 =head1 BUGS
3373  
3374 is_tablet() only currently detects the iPad and Windows PCs. Android strings
3375 don't differ between tablets and smartphones.
3376  
3377 params() returns a ref which means that calling routines can change the hash
3378 for other routines.
3379 Take a local copy before making amendments to the table if you don't want unexpected
3380 things to happen.
3381  
3382 =head1 SEE ALSO
3383  
3384 =over 4
3385  
3386 =item * L<Configure an Object at Runtime|Object::Configure>
3387  
3388 =item * L<Test Dashboard|https://nigelhorne.github.io/CGI-Info/coverage/>
3389  
3390 =item * L<HTTP::BrowserDetect>
3391  
3392 =item * L<https://github.com/mitchellkrogza/apache-ultimate-bad-bot-blocker>
3393  
3394 =back
3395  
3396 =head1 REPOSITORY
3397  
3398 L<https://github.com/nigelhorne/CGI-Info>
3399  
3400 =head1 SUPPORT
3401  
3402 This module is provided as-is without any warranty.
3403  
3404 Please report any bugs or feature requests to C<bug-cgi-info at rt.cpan.org>,
3405 or through the web interface at
3406 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=CGI-Info>.
3407 I will be notified, and then you'll
3408 automatically be notified of progress on your bug as I make changes.
3409  
3410 You can find documentation for this module with the perldoc command.
3411  
3412 perldoc CGI::Info
3413  
3414 You can also look for information at:
3415  
3416 =over 4
3417  
3418 =item * MetaCPAN
3419  
3420 L<https://metacpan.org/dist/CGI-Info>
3421  
3422 =item * RT: CPAN's request tracker
3423  
3424 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=CGI-Info>
3425  
3426 =item * CPAN Testers' Matrix
3427  
3428 L<http://matrix.cpantesters.org/?dist=CGI-Info>
3429  
3430 =item * CPAN Testers Dependencies
3431  
3432 L<http://deps.cpantesters.org/?module=CGI::Info>
3433  
3434 =back
3435  
3436 =encoding utf-8
3437  
3438 =head2 FORMAL SPECIFICATION
3439  
3440 =head3 new
3441  
3442 -- CGI::Info construction
3443 new : ClassName x Params --> CGIInfo
3444  
3445 -- Normal (non-clone) path
3446 new(class, params) ^=
3447 let configured == Object::Configure::configure(class, params)
3448 in CGIInfo {
3449 max_upload_size |-> configured.max_upload_size ?? MAX_UPLOAD_SIZE_DEFAULT,
3450 allow |-> configured.allow ?? null,
3451 upload_dir |-> configured.upload_dir ?? null,
3452 ...configured
3453 }
3454  
3455 -- Pre-conditions
3456 pre new(class, params) ^=
3457 params.logger = null
3458 v (blessed(params.logger)
3459 ^ params.logger.can('warn')
3460 ^ params.logger.can('info')
3461 ^ params.logger.can('error'))
3462 ^ params.expect = null
3463  
3464 -- Clone path (invocant is an existing object)
3465 clone : CGIInfo x Params --> CGIInfo
3466 clone(self, params) ^=
3467 let merged == (self (+) params) \ {paramref}
3468 in CGIInfo { ...merged }
3469  
3470 =head3 param
3471  
3472 Let F be the set of all possible CGI field names, V be the set of all
3473 possible (sanitised) scalar values, and allow : F -> Regex | undef be the
3474 current allow-list schema (undef means all fields are permitted).
3475  
3476 param : F? -> V | HashRef | undef
3477  
3478 param() = params()
3479  
3480 param(f) =
3481 f not in dom(allow) /\ allow /= undef => warn; undef
3482 f in params() => params()(f)
3483 otherwise => undef
3484  
3485 Safety invariant: for all f, param(f) /= undef => f in dom(allow) \/ allow = undef.
3486  
3487 =head2 is_ai
3488  
3489 -- is_ai ---------------------------------------------------------
3490 -- Given CGIInfo state i, returns a boolean result.
3491 --
3492 -- AI_PAT is the set of known AI crawler token strings.
3493 --
3494 -- ENV denotes the process environment (a partial function from
3495 -- name to value).
3496 --
3497 AI_PAT == {ClaudeBot, Claude-Web, anthropic-ai, GPTBot,
3498 ChatGPT-User, OAI-SearchBot, Google-Extended,
3499 meta-externalagent, FacebookBot, Applebot-Extended,
3500 PerplexityBot, Amazonbot, YouBot, Diffbot,
3501 cohere-ai, CCBot, Bytespider, AI2Bot, TimpiBot}
3502  
3503 is_ai ≜ λ i : CGIInfo •
3504 -- Environment override takes absolute priority
3505 IS_AI ∈ dom ENV ⟹
3506 (ENV IS_AI ≠ '0' ∧ ENV IS_AI ≠ '')
3507  
3508 -- Without both IP and UA we cannot classify
3509 ∧ IS_AI ∉ dom ENV ∧
3510 (REMOTE_ADDR ∉ dom ENV ∨ HTTP_USER_AGENT ∉ dom ENV)
3511 ⟹ false
3512  
3513 -- UA-pattern match (case-insensitive substring)
3514 ∧ IS_AI ∉ dom ENV ∧
3515 REMOTE_ADDR ∈ dom ENV ∧ HTTP_USER_AGENT ∈ dom ENV
3516 ⟹ (∃ p : AI_PAT • p ⊑ᵢ ENV HTTP_USER_AGENT)
3517  
3518 -- Invariant: is_ai ⟹ is_robot
3519 ∧ is_ai i = true ⟹ is_robot i = true
3520 -- ---------------------------------------------------------------
3521  
3522 =head1 AUTHOR
3523  
3524 Nigel Horne, C<< <njh at nigelhorne.com> >>
3525  
3526 =head1 LICENCE AND COPYRIGHT
3527  
3528 Copyright 2010-2026 Nigel Horne.
3529  
3530 Usage is subject to the GPL2 licence terms.
3531 If you use it,
3532 please let me know.
3533  
3534 =cut
3535  
3536 38 1;
↑ Summary bin/info.pl »