blib/lib/CGI/Info.pm

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