blib/lib/CGI/Info.pm

filter: Statementstmt 94.6% 846 / 894 Branchbran 87.2% 473 / 542 Conditioncond 70.8% 302 / 426 MC/DCmcdc 49.7% 109 / 219 Subroutinesub 100% 78 / 78 Podpod 100% 30 / 30 totaltotal 83.9% 1838 / 2189 CC 418 SCAR 40.3
CC
418
Cov
87%
params
163.2
is_search_engine
66.0
is_robot
31.7
CRAP 56.2
↑ Summary bin/info.pl »
1 package CGI::Info;
2  
3 37 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 37 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 37 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 37 ▶use 5.010; # Minimum version for features used here
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 # Core modules
10 37 ▶use boolean;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 37 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 37 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 37 ▶use Scalar::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 37 ▶use Socket; # AF_INET constant
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 # CPAN modules
17 37 ▶use Object::Configure 0.19;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 37 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 37 ▶use Log::Abstraction 0.10;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 37 ▶use Net::CIDR;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 37 ▶use Params::Get 0.13;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 37 ▶use Params::Validate::Strict 0.35;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 37 ▶use Return::Set;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 37 ▶use Sys::Path;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 37 ▶use Sub::Protected;
Subroutine BEGIN: called CC=1 SCAR=0.0
26  
27 37 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
28  
29 # ---------------------------------------------------------------------------
30 # Module-level constants -- avoids magic numbers scattered through the code
31 # ---------------------------------------------------------------------------
32 37 Readonly my $MAX_UPLOAD_SIZE_DEFAULT => 512 * 1024; # 512 KB default upload cap
33 37 Readonly my $CACHE_TTL_ROBOT => '1 day'; # TTL for robot-detection cache entries
34 37 Readonly my $CACHE_TTL_SEARCH => '1 day'; # TTL for search-engine cache entries
35  
36 # Compiled once at module-load time: replaces the 29-element @crawler_lists array
37 # that was re-allocated on every is_robot() call. Building the alternation with
38 # quotemeta() is equivalent to the former List::Util::any { /^\Q$_\E/i } loop
39 # but avoids both per-call array construction and per-element regex compilation.
40 37 Readonly my $CRAWLER_REFERER_RE => do {
41 37 my @domains = (
42 'http://fix-website-errors.com',
43 'http://keywords-monitoring-your-success.com',
44 'http://free-video-tool.com',
45 'http://magnet-to-torrent.com',
46 'http://torrent-to-magnet.com',
47 'http://dogsrun.net',
48 'http://###.responsive-test.net',
49 'http://uptime.com',
50 'http://uptimechecker.com',
51 'http://top1-seo-service.com',
52 'http://fast-wordpress-start.com',
53 'http://wordpress-crew.net',
54 'http://dbutton.net',
55 'http://justprofit.xyz',
56 'http://video--production.com',
57 'http://buttons-for-website.com',
58 'http://buttons-for-your-website.com',
59 'http://success-seo.com',
60 'http://videos-for-your-business.com',
61 'http://semaltmedia.com',
62 'http://dailyrank.net',
63 'http://uptimebot.net',
64 'http://sitevaluation.org',
65 'http://100dollars-seo.com',
66 'http://forum69.info',
67 'http://partner.semalt.com',
68 'http://best-seo-offer.com',
69 'http://best-seo-solution.com',
70 'http://semalt.semalt.com',
71 'http://semalt.com',
72 'http://7makemoneyonline.com',
73 'http://anticrawler.org',
74 'http://baixar-musicas-gratis.com',
75 'http://descargar-musica-gratis.net',
76 'http://www.seokicks.de/robot.html',
77 );
78 37 my $alt = join '|', map { quotemeta $_ } @domains;
79 37 qr/^(?:$alt)/i;
80 };
81  
82 sub _sanitise_input;
83  
84 =head1 NAME
85  
86 CGI::Info - Information about the CGI environment
87  
88 =head1 VERSION
89  
90 Version 1.15
91  
92 =cut
93  
94 37 our $VERSION = '1.15';
95  
96 =head1 SYNOPSIS
97  
98 The C<CGI::Info> module is a Perl library designed to provide information about the environment in which a CGI script operates.
99 It aims to eliminate hard-coded script details,
100 enhancing code readability and portability.
101 Additionally, it offers a simple web application firewall to add a layer of security.
102  
103 All too often,
104 Perl programs have information such as the script's name
105 hard-coded into their source.
106 Generally speaking,
107 hard-coding is a bad style since it can make programs difficult to read and reduces readability and portability.
108 CGI::Info attempts to remove that.
109  
110 Furthermore, to aid script debugging, CGI::Info attempts to do sensible
111 things when you're not running the program in a CGI environment.
112  
113 Whilst you shouldn't rely on it alone to provide security to your website,
114 it is another layer and every little helps.
115  
116 use CGI::Info;
117  
118 my $info = CGI::Info->new(allow => { id => qr/^\d+$/ });
119 my $params = $info->params();
120  
121 if($info->is_mobile()) {
122 print "Mobile view\n";
123 } else {
124 print "Desktop view\n";
125 }
126  
127 my $id = $info->param('id'); # Validated against allow schema
128  
129 =head1 SUBROUTINES/METHODS
130  
131 =head2 new
132  
133 Creates a CGI::Info object.
134  
135 It takes four optional arguments: allow, logger, expect and upload_dir,
136 which are documented in the params() method.
137  
138 It takes other optional parameters:
139  
140 =over 4
141  
142 =item * C<auto_load>
143  
144 Enable/disable the AUTOLOAD feature.
145 The default is to have it enabled.
146  
147 =item * C<config_dirs>
148  
149 Where to look for C<config_file>
150  
151 =item * C<config_file>
152  
153 Points to a configuration file which contains the parameters to C<new()>.
154 The file can be in any common format,
155 including C<YAML>, C<XML>, and C<INI>.
156 This allows the parameters to be set at run time.
157  
158 On non-Windows system,
159 the class can be configured using environment variables starting with "CGI::Info::".
160 For example:
161  
162 export CGI::Info::max_upload_size=65536
163  
164 It doesn't work on Windows because of the case-insensitive nature of that system.
165  
166 If the configuration file has a section called C<CGI::Info>,
167 only that section,
168 and the C<global> section,
169 if any exists,
170 is used.
171  
172 =item * C<syslog>
173  
174 Takes an optional parameter syslog, to log messages to
175 L<Sys::Syslog>.
176 It can be a boolean to enable/disable logging to syslog, or a reference
177 to a hash to be given to Sys::Syslog::setlogsock.
178  
179 =item * C<cache>
180  
181 An object that is used to cache IP lookups.
182 This cache object is an object that understands get() and set() messages,
183 such as a L<CHI> object.
184  
185 =item * C<max_upload_size>
186  
187 The maximum file size in bytes you can upload.
188 Use C<-1> for no limit.
189 The default is 512 KB (524288 bytes).
190  
191 =back
192  
193 The class can be configured at runtime using environment variables and configuration
194 files; for example, setting C<$ENV{'CGI__INFO__carp_on_warn'}> causes warnings to
195 use L<Carp>. For more information see L<Object::Configure>.
196  
197 =head3 API SPECIFICATION
198  
199 =head4 INPUT
200  
201 {
202 allow => { type => 'hashref', optional => 1 },
203 auto_load => { type => 'boolean', optional => 1 },
204 cache => { type => 'object', optional => 1 },
205 carp_on_warn => { type => 'boolean', optional => 1 },
206 config_dirs => { type => 'arrayref', optional => 1 },
207 config_file => { type => 'string', optional => 1 },
208 logger => { type => 'object', optional => 1 },
209 max_upload_size=> { type => 'integer', optional => 1, min => -1 },
210 upload_dir => { type => 'string', optional => 1 },
211 }
212  
213 =head4 OUTPUT
214  
215 { type => 'object', isa => 'CGI::Info' }
216  
217 =head3 MESSAGES
218  
219 =over 4
220  
221 =item C<< use ->new() not ::new() to instantiate >>
222  
223 B<Level>: fatal (croak).
224 B<Cause>: called as C<CGI::Info::new()> (double-colon) instead of C<< CGI::Info->new() >>.
225 B<Action>: change the call-site to use the arrow notation.
226  
227 =item C<< Logger must be an object with info() and error() methods >>
228  
229 B<Level>: fatal (croak).
230 B<Cause>: the C<logger> argument is not a blessed object, or does not
231 implement C<info()>, C<warn()>, and C<error()> methods.
232 B<Action>: pass a compliant logger such as a L<Log::Abstraction>-based object.
233  
234 =item C<< expect has been deprecated, use allow instead >>
235  
236 B<Level>: fatal (croak).
237 B<Cause>: the removed C<expect> parameter was passed to C<new()>.
238 B<Action>: replace C<expect =E<gt> [...]> with C<allow =E<gt> { key =E<gt> qr/.../ }>.
239  
240 =back
241  
242 =cut
243  
244 37 our $stdin_data; # Class variable storing STDIN in case the class
245 # is instantiated more than once
246  
247 sub new
248 1009 ▶{
Subroutine new: called CC=23 SCAR=34.1
Pod documented
249 1009 my $class = shift;
250  
251 # Handle hash or hashref arguments
252 1009 my $params = Params::Get::get_params(undef, \@_);
253  
254 1007 ▶ if (defined($class)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $class) { } 1002 5 1007
255 1002 ▶ my $is_valid = Scalar::Util::blessed($class) || (eval { $class->isa(__PACKAGE__) });
Condition100%3/3
builtin::blessed($class) || eval {
l!l&&r!l&&!r
149871
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
256 1002 ▶ unless ($is_valid) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($is_valid) 1 1001 1002
257 # Called as CGI::Info::new(...) or similar wrong function call
258 1 croak(__PACKAGE__, ' use ->new() not ::new() to instantiate');
259 }
260 } else {
261 # If class is undef, but there are arguments/params passed
262 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
263 1 croak(__PACKAGE__, ' use ->new() not ::new() to instantiate');
264 }
265 # Called as CGI::Info::new() with 0 arguments (undef $class)
266 4 $class = __PACKAGE__;
267 }
268  
269 1005 ▶ if(Scalar::Util::blessed($class)) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($class)) 14 991 1005
270 # If $class is an object, clone it with new arguments
271 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
272  
273 # Validate any new logger passed to the clone
274 14 ▶ if(defined $params->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{"logger"}) 1 13 14
275 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
276 1 Carp::croak('Logger must be an object with info() and error() methods');
277 }
278 }
279  
280 # expect is deprecated even when cloning
281 13 ▶ if(defined($params->{'expect'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{"expect"}) 2 11 13
282 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
283 2 ▶ $logger->error(ref($class) . ': expect has been deprecated, use allow instead') if $logger;
Branch: 1 branch
BranchTrueFalseTotal
if $logger 2 0 2
284 2 Carp::croak(ref($class) . ': expect has been deprecated, use allow instead');
285 }
286  
287 # Drop cached params so a new allow schema is applied on next call
288 11 my %merged = (%{$class}, %{$params});
289 11 delete $merged{'paramref'};
290 11 return bless \%merged, ref($class);
291 }
292  
293 # Load the configuration from a config file, if provided
294 991 $params = Object::Configure::configure($class, $params);
295  
296 # Validate logger object has required methods
297 990 ▶ if(defined $params->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{"logger"}) 990 0 990
298 990 ▶ 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 990 990
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
00990
builtin::blessed($params->{"logger"}) and $params->{"logger"}->can("warn") and $params->{"logger"}->can("info")
!ll&&!rl&&r
00990
builtin::blessed($params->{"logger"}) and $params->{"logger"}->can("warn")
!ll&&!rl&&r
00990
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
299 0 Carp::croak("Logger must be an object with info() and error() methods");
300 }
301 }
302  
303 990 ▶ if(defined($params->{'expect'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{"expect"}) 5 985 990
304 # if(ref($params->{expect}) ne 'ARRAY') {
305 # Carp::croak(__PACKAGE__, ': expect must be a reference to an array');
306 # }
307 # # warn __PACKAGE__, ': expect is deprecated, use allow instead';
308 5 ▶ if(my $logger = $params->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $logger = $params->{"logger"}) 5 0 5
309 5 $logger->error("$class: expect has been deprecated, use allow instead");
310 }
311 5 Carp::croak("$class: expect has been deprecated, use allow instead");
312 }
313  
314 # Return the blessed object with sensible defaults
315 return bless {
316 max_upload_size => $MAX_UPLOAD_SIZE_DEFAULT,
317 allow => undef,
318 upload_dir => undef,
319 985 %{$params} # Caller-supplied args override the defaults above
320 }, $class;
321 }
322  
323 =head2 script_name
324  
325 Retrieves the name of the executing CGI script.
326 This is useful for POSTing,
327 thus avoiding hard-coded paths into forms.
328  
329 use CGI::Info;
330  
331 my $info = CGI::Info->new();
332 my $script_name = $info->script_name();
333 # ...
334 print "<form method=\"POST\" action=$script_name name=\"my_form\">\n";
335  
336 =head3 API SPECIFICATION
337  
338 =head4 INPUT
339  
340 None.
341  
342 =head4 OUTPUT
343  
344 {
345 type => 'string',
346 'min' => 1,
347 'nomatch' => qr/^[\/\\]/ # Does not return absolute path
348 }
349  
350 =cut
351  
352 sub script_name
353 32 ▶{
Subroutine script_name: called CC=2 SCAR=6.9
Pod documented
354 32 my $self = shift;
355  
356 32 ▶ unless($self->{script_name}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"script_name"}) 24 8 32
357 24 $self->_find_paths();
358 }
359 32 return $self->{script_name};
360 }
361  
362 46 ▶sub _find_paths :Protected {
Subroutine _find_paths: called CC=12 SCAR=25.9
363 46 my $self = shift;
364  
365 46 $self->_trace(__PACKAGE__ . ': entering _find_paths');
366  
367 46 ▶ require File::Basename && File::Basename->import() unless File::Basename->can('basename');
Branch: 1 branch
BranchTrueFalseTotal
unless "File::Basename"->can("basename") 0 46 46
Condition16%1/6
'File::Basename'->can('basename') || require File::Basename && 'File::Basename'->import
l!l&&r!l&&!r
4600
require File::Basename and "File::Basename"->import
!ll&&!rl&&r
000
MC/DC0%0/3
'File::Basename'->can('basename') || require File::Basename && 'File::Basename'->import
'File::Basename'->can('basename') require File::Basename "File::Basename"->import
Truth table0%0/4
A || B and C
A= 'File::Basename'->can('basename')B= require File::BasenameC= "File::Basename"->import
ABCresult
1XX1
0111
00X0
0100
368  
369 # Determine script name
370 46 ▶ my $script_name = $self->_get_env('SCRIPT_NAME') // $0;
Condition66%2/3
$self->_get_env("SCRIPT_NAME") // $0
l!l&&r!l&&!r
22240
MC/DC0%0/2
$self->_get_env("SCRIPT_NAME") // $0
$self->_get_env("SCRIPT_NAME") $0
Truth table66%2/3
A // B
A= $self->_get_env("SCRIPT_NAME")B= $0
ABresult
1X1
011
000
371 46 $self->{script_name} = $self->_untaint_filename({
372 filename => File::Basename::basename($script_name)
373 });
374  
375 # Determine script path
376 46 ▶ if(my $script_path = $self->_get_env('SCRIPT_FILENAME')) {
Branch: 3 branches
BranchTrueFalseTotal
if (my $script_path = $self->_get_env('SCRIPT_FILENAME')) { } 13 33 46
elsif ($script_name = $self->_get_env('SCRIPT_NAME')) { } 19 14 33
elsif ('File::Spec'->file_name_is_absolute($0)) { } 0 14 14
377 13 $self->{script_path} = $script_path;
378 } elsif($script_name = $self->_get_env('SCRIPT_NAME')) {
379 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
380 8 $script_name = $self->_get_env('SCRIPT_NAME');
381  
382 # It's usually the case, e.g. /cgi-bin/foo.pl
383 8 $script_name =~ s{^/}{};
384  
385 8 $self->{script_path} = File::Spec->catfile($document_root, $script_name);
386 } else {
387 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
388 # Called from a command line with a full path
389 1 $self->{script_path} = $script_name;
390 } else {
391 10 ▶ require Cwd unless Cwd->can('abs_path');
Branch: 1 branch
BranchTrueFalseTotal
unless "Cwd"->can("abs_path") 0 10 10
392  
393 10 ▶ if($script_name =~ /^\/(.+)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($script_name =~ m[^/(.+)]) 7 3 10
394 # It's usually the case, e.g. /cgi-bin/foo.pl
395 7 $script_name = $1;
396 }
397  
398 10 $self->{script_path} = File::Spec->catfile(Cwd::abs_path(), $script_name);
399 }
400 }
401 } elsif(File::Spec->file_name_is_absolute($0)) {
402 # Called from a command line with a full path
403 0 $self->{script_path} = $0;
404 } else {
405 14 $self->{script_path} = File::Spec->rel2abs($0);
406 }
407  
408 # Untaint and finalize script path
409 $self->{script_path} = $self->_untaint_filename({
410 filename => $self->{script_path}
411 46 });
412 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
413  
414 =head2 script_path
415  
416 Finds the full path name of the script.
417  
418 use CGI::Info;
419  
420 my $info = CGI::Info->new();
421 my $fullname = $info->script_path();
422 my @statb = stat($fullname);
423  
424 if(@statb) {
425 my $mtime = localtime $statb[9];
426 print "Last-Modified: $mtime\n";
427 # TODO: only for HTTP/1.1 connections
428 # $etag = Digest::MD5::md5_hex($html);
429 printf "ETag: \"%x\"\n", $statb[9];
430 }
431 =cut
432  
433 36 ▶sub script_path {
Subroutine script_path: called CC=2 SCAR=6.9
Pod documented
434 36 my $self = shift;
435  
436 36 ▶ unless($self->{script_path}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"script_path"}) 14 22 36
437 14 $self->_find_paths();
438 }
439 36 return $self->{script_path};
440 }
441  
442 =head2 script_dir
443  
444 Returns the file system directory containing the script.
445  
446 use CGI::Info;
447 use File::Spec;
448  
449 my $info = CGI::Info->new();
450  
451 print 'HTML files are normally stored in ', $info->script_dir(), '/', File::Spec->updir(), "\n";
452  
453 # or
454 use lib CGI::Info::script_dir() . '../lib';
455  
456 =cut
457  
458 sub script_dir
459 23 ▶{
Subroutine script_dir: called CC=5 SCAR=16.3
Pod documented
460 23 my $self = shift;
461  
462 # Ensure $self is an object
463 23 ▶ $self = __PACKAGE__->new() unless ref $self;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self 3 20 23
464  
465 # Set script path if it is not already defined
466 23 ▶ $self->_find_paths() unless $self->{script_path};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"script_path"} 8 15 23
467  
468 # Extract directory from script path based on OS
469 # Don't use File::Spec->splitpath() since that can leave the trailing slash
470 23 ▶ my $dir_regex = $^O eq 'MSWin32' ? qr{(.+)\\.+?$} : qr{(.+)/.+?$};
Branch: 1 branch
BranchTrueFalseTotal
$^O eq 'MSWin32' ? : 0 23 23
471  
472 23 ▶ return $self->{script_path} =~ $dir_regex ? $1 : $self->{script_path};
Branch: 1 branch
BranchTrueFalseTotal
$self->{'script_path'} =~ /$dir_regex/ ? : 23 0 23
473 }
474  
475 =head2 host_name
476  
477 Return the host-name of the current web server, according to CGI.
478 If the name can't be determined from the web server, the system's host-name
479 is used as a fall back.
480 This may not be the same as the machine that the CGI script is running on,
481 some ISPs and other sites run scripts on different machines from those
482 delivering static content.
483 There is a good chance that this will be domain_name() prepended with either
484 'www' or 'cgi'.
485  
486 use CGI::Info;
487  
488 my $info = CGI::Info->new();
489 my $host_name = $info->host_name();
490 my $protocol = $info->protocol();
491 # ...
492 print "Thank you for visiting our <A HREF=\"$protocol://$host_name\">Website!</A>";
493  
494 =cut
495  
496 131 ▶sub host_name {
Subroutine host_name: called CC=2 SCAR=6.9
Pod documented
497 131 my $self = shift;
498  
499 131 ▶ unless($self->{site}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"site"}) 23 108 131
500 23 $self->_find_site_details();
501 }
502  
503 131 return $self->{site};
504 }
505  
506 50 ▶sub _find_site_details :Protected {
Subroutine _find_site_details: called CC=17 SCAR=28.8
507 50 my $self = shift;
508  
509 # Log entry to the routine
510 50 $self->_trace('Entering _find_site_details');
511  
512 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
513  
514 # Determine cgi_site using environment variables or hostname
515 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
516 # Import necessary module
517 37 ▶ require URI::Heuristic unless URI::Heuristic->can('uf_uristr');
Branch: 1 branch
BranchTrueFalseTotal
unless "URI::Heuristic"->can("uf_uristr") 6 31 37
518  
519 37 $self->{cgi_site} = URI::Heuristic::uf_uristr($host);
520 # Remove trailing dots from the name. They are legal in URLs
521 # and some sites link using them to avoid spoofing (nice)
522 37 $self->{cgi_site} =~ s/\.+$//; # Trim trailing dots
523  
524 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
525 2 $self->{cgi_site} =~ s/^http/$protocol/;
526 }
527 } else {
528 # Import necessary module
529 7 ▶ require Sys::Hostname unless Sys::Hostname->can('hostname');
Branch: 1 branch
BranchTrueFalseTotal
unless "Sys::Hostname"->can("hostname") 0 7 7
530  
531 7 $self->_debug('Falling back to using hostname');
532 7 $self->{cgi_site} = Sys::Hostname::hostname();
533 }
534  
535 # Set site details if not already defined
536 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
537 44 $self->{site} =~ s/^https?:\/\/(.+)/$1/;
538 $self->{cgi_site} = ($self->protocol() || 'http') . '://' . $self->{cgi_site}
539 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
540  
541 # Warn if site details could not be determined
542 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
543  
544 # Log exit
545 44 $self->_trace('Leaving _find_site_details');
546 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
547  
548 =head2 domain_name
549  
550 Domain_name is the name of the controlling domain for this website.
551 Usually it will be similar to host_name, but will lack the http:// or www prefixes.
552  
553 Can be called as a class method.
554  
555 =cut
556  
557 20 ▶sub domain_name {
Subroutine domain_name: called CC=5 SCAR=16.1
Pod documented
558 20 my $self = shift;
559  
560 20 ▶ if(!ref($self)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $self) 4 16 20
561 4 $self = __PACKAGE__->new();
562 }
563 20 ▶ return $self->{domain} if $self->{domain};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"domain"} 3 17 20
564  
565 17 $self->_find_site_details();
566  
567 17 ▶ if(my $site = $self->{site}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $site = $self->{"site"}) 17 0 17
568 17 ▶ $self->{domain} = ($site =~ /^www\.(.+)/) ? $1 : $site;
Branch: 1 branch
BranchTrueFalseTotal
$site =~ /^www\.(.+)/ ? : 11 6 17
569 }
570  
571 17 return $self->{domain};
572 }
573  
574 =head2 cgi_host_url
575  
576 Return the URL of the machine running the CGI script.
577  
578 =cut
579  
580 16 ▶sub cgi_host_url {
Subroutine cgi_host_url: called CC=2 SCAR=6.9
Pod documented
581 16 my $self = shift;
582  
583 16 ▶ unless($self->{cgi_site}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"cgi_site"}) 10 6 16
584 10 $self->_find_site_details();
585 }
586  
587 16 return $self->{cgi_site};
588 }
589  
590 =head2 params
591  
592 Returns a reference to a hash list of the CGI arguments.
593  
594 CGI::Info helps you to test your script before deployment on a website:
595 if it is not in a CGI environment (e.g., the script is being tested from the
596 command line), the program's command line arguments (a list of key=value pairs)
597 are used, if there are no command line arguments,
598 then they are read from stdin as a list of key=value lines.
599 Also,
600 you can give one of --tablet, --search-engine,
601 --mobile and --robot to mimic those agents. For example:
602  
603 ./script.cgi --mobile name=Nigel
604  
605 Returns undef if the parameters can't be determined or if none were given.
606  
607 If an argument is given twice or more, then the values are put in a comma
608 separated string.
609  
610 The returned hash value can be passed into L<CGI::Untaint>.
611  
612 Takes four optional parameters: allow, logger and upload_dir.
613 The parameters are passed in a hash, or a reference to a hash.
614 The latter is more efficient since it puts less on the stack.
615  
616 Allow is a reference to a hash list of CGI parameters that you will allow.
617 The value for each entry is either a permitted value,
618 a regular expression of permitted values for
619 the key,
620 a code reference,
621 or a hash of L<Params::Validate::Strict> rules.
622 Subroutine exceptions propagate normally, allowing custom error handling.
623 This works alongside existing regex and Params::Validate::Strict patterns.
624 A undef value means that any value will be allowed.
625 Arguments not in the list are silently ignored.
626 This is useful to help to block attacks on your site.
627  
628 Upload_dir is a string containing a directory where files being uploaded are to
629 be stored.
630 It must be a writeable directory in the temporary area.
631  
632 Takes an optional parameter logger, which is used for warnings and traces.
633 It can be an object that understands warn() and trace() messages,
634 such as a L<Log::Log4perl> or L<Log::Any> object,
635 a reference to code,
636 a reference to an array,
637 or a filename.
638  
639 The allow, logger and upload_dir arguments can also be passed to the
640 constructor.
641  
642 use CGI::Info;
643 use CGI::Untaint;
644 # ...
645 my $info = CGI::Info->new();
646 my %params;
647 if($info->params()) {
648 %params = %{$info->params()};
649 }
650 # ...
651 foreach(keys %params) {
652 print "$_ => $params{$_}\n";
653 }
654 my $u = CGI::Untaint->new(%params);
655  
656 use CGI::Info;
657 use CGI::IDS;
658 # ...
659 my $info = CGI::Info->new();
660 my $allowed = {
661 foo => qr/^\d*$/, # foo must be a number, or empty
662 bar => undef, # bar can be given and be any value
663 xyzzy => qr/^[\w\s-]+$/, # must be alphanumeric
664 # to prevent XSS, and non-empty
665 # as a sanity check
666 };
667 # or
668 $allowed = {
669 email => { type => 'string', matches => qr/^[^@]+@[^@]+\.[^@]+$/ }, # String, basic email format check
670 age => { type => 'integer', min => 0, max => 150 }, # Integer between 0 and 150
671 bio => { type => 'string', optional => 1 }, # String, optional
672 ip_address => { type => 'string', matches => qr/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/ }, #Basic IPv4 validation
673 };
674 my $paramsref = $info->params(allow => $allowed);
675 if(defined($paramsref)) {
676 my $ids = CGI::IDS->new();
677 $ids->set_scan_keys(scan_keys => 1);
678 if($ids->detect_attacks(request => $paramsref) > 0) {
679 die 'horribly';
680 }
681 }
682  
683 If the request is an XML request (i.e. the content type of the POST is text/xml),
684 CGI::Info will put the request into the params element 'XML', thus:
685  
686 use CGI::Info;
687 # ...
688 my $info = CGI::Info->new();
689 my $paramsref = $info->params(); # See BUGS below
690 my $xml = $$paramsref{'XML'};
691 # ... parse and process the XML request in $xml
692  
693 Carp if logger is not set and we detect something serious.
694  
695 Blocks some attacks,
696 such as SQL and XSS injections,
697 mustleak and directory traversals,
698 thus creating a primitive web application firewall (WAF).
699 Warning - this is an extra layer, not a replacement for your other security layers.
700  
701 =head3 Validation Subroutine Support
702  
703 The C<allow> parameter accepts subroutine references for dynamic validation,
704 enabling complex parameter checks beyond static regex patterns.
705 These callbacks:
706  
707 =over 4
708  
709 =item * Receive three arguments: the parameter key, value and the C<CGI::Info> instance
710  
711 =item * Must return a true value to allow the parameter, false to reject
712  
713 =item * Can access other parameters through the instance for contextual validation
714  
715 =back
716  
717 Basic usage:
718  
719 CGI::Info->new(
720 allow => {
721 # Simple value check
722 even_number => sub { ($_[1] % 2) == 0 },
723  
724 # Context-aware validation
725 child_age => sub {
726 my ($key, $value, $info) = @_;
727 $info->param('is_parent') ? $value <= 18 : 0
728 }
729 }
730 );
731  
732 Advanced features:
733  
734 # Combine with regex validation
735 mixed_validation => {
736 email => qr/@/, # Regex check
737 promo_code => \&validate_promo_code # Subroutine check
738 }
739  
740 # Throw custom exceptions
741 dangerous_param => sub {
742 die 'Hacking attempt!' if $_[1] =~ /DROP TABLE/;
743 return 1;
744 }
745 =cut
746  
747 660 ▶sub params {
Subroutine params: called CC=130 SCAR=50.9
Pod documented
748 660 my $self = shift;
749  
750 660 my $params = Params::Get::get_params(undef, @_);
751  
752 660 ▶ if((defined($self->{paramref})) && ((!defined($params->{'allow'})) || defined($self->{allow}) && ($params->{'allow'} eq $self->{allow}))) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"paramref"} and !defined($params->{"allow"}) || defined $self->{"allow"} && $params->{"allow"} eq $self->{"allow"}) 190 470 660
Condition100%9/9
defined $self->{"paramref"} and !defined($params->{"allow"}) || defined $self->{"allow"} && $params->{"allow"} eq $self->{"allow"}
!ll&&!rl&&r
4682190
not defined $params->{"allow"} or defined $self->{"allow"} and $params->{"allow"} eq $self->{"allow"}
l!l&&r!l&&!r
18822
defined $self->{"allow"} and $params->{"allow"} eq $self->{"allow"}
!ll&&!rl&&r
112
MC/DC100%4/4
defined $self->{"paramref"} and !defined($params->{"allow"}) || defined $self->{"allow"} && $params->{"allow"} eq $self->{"allow"}
defined $self->{"paramref"} not defined $params->{"allow"} defined $self->{"allow"} $params->{"allow"} eq $self->{"allow"}
Truth table100%5/5
A and not(B) or C and D
A= defined $self->{"paramref"}B= not defined $params->{"allow"}C= defined $self->{"allow"}D= $params->{"allow"} eq $self->{"allow"}
ABCDresult
0XXX0
100X0
10100
11XX1
10111
753 190 return $self->{paramref};
754 }
755  
756 470 ▶ if(defined($params->{allow})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{"allow"}) 72 398 470
757 72 $self->{allow} = $params->{allow};
758 }
759 470 ▶ if(defined($params->{upload_dir})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{"upload_dir"}) 9 461 470
760 9 $self->{upload_dir} = $params->{upload_dir};
761 }
762 470 ▶ if(defined($params->{'logger'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{"logger"}) 2 468 470
763 2 $self->set_logger($params->{'logger'});
764 }
765 470 $self->_trace('Entering params');
766  
767 470 my @pairs;
768 470 my $content_type = $ENV{'CONTENT_TYPE'};
769 470 my %FORM;
770  
771 470 ▶ if((!$ENV{'GATEWAY_INTERFACE'}) || (!$ENV{'REQUEST_METHOD'})) {
Branch: 5 branches
BranchTrueFalseTotal
if (not $ENV{'GATEWAY_INTERFACE'} && $ENV{'REQUEST_METHOD'}) { } 51 419 470
elsif ($ENV{'REQUEST_METHOD'} eq 'GET' or $ENV{'REQUEST_METHOD'} eq 'HEAD') { } 319 100 419
elsif ($ENV{'REQUEST_METHOD'} eq 'POST') { } 79 21 100
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
510419
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
772 # require IO::Interactive;
773 # IO::Interactive->import();
774  
775 51 ▶ if(@ARGV) {
Branch: 2 branches
BranchTrueFalseTotal
if (@ARGV) { } 45 6 51
elsif ($CGI::Info::stdin_data) { } 0 6 6
776 45 @pairs = @ARGV;
777 45 ▶ if(defined($pairs[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $pairs[0]) 45 0 45
778 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
779 6 $self->{is_robot} = 1;
780 6 shift @pairs;
781 } elsif($pairs[0] eq '--mobile') {
782 7 $self->{is_mobile} = 1;
783 7 shift @pairs;
784 } elsif($pairs[0] eq '--search-engine') {
785 6 $self->{is_search_engine} = 1;
786 6 shift @pairs;
787 } elsif($pairs[0] eq '--tablet') {
788 6 $self->{is_tablet} = 1;
789 6 shift @pairs;
790 }
791 }
792 } elsif($stdin_data) {
793 # Re-use previously read STDIN (class variable shared across instances)
794 0 @pairs = split(/\n/, $stdin_data);
795 }
796 ▶ } 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
3154100
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
797 319 ▶ if(my $query = $ENV{'QUERY_STRING'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $query = $ENV{'QUERY_STRING'}) { } 310 9 319
798 310 ▶ 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 306 310
Condition66%2/3
defined $content_type and $content_type =~ m[multipart/form-data]i
!ll&&!rl&&r
30604
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
799 4 ▶ if($ENV{'REMOTE_ADDR'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{'REMOTE_ADDR'}) { } 2 2 4
800 2 $self->_warn({ warning => "$ENV{REMOTE_ADDR}: Multipart/form-data not supported for GET (query string = $query)" });
801 } else {
802 2 $self->_warn('Multipart/form-data not supported for GET');
803 }
804 3 $self->status(501); # Not implemented
805 3 return;
806 }
807 306 $query =~ s/\\u0026/\&/g;
808 306 @pairs = split(/&/, $query);
809 } else {
810 9 return;
811 }
812 } elsif($ENV{'REQUEST_METHOD'} eq 'POST') {
813 79 my $content_length = $self->_get_env('CONTENT_LENGTH');
814 79 ▶ if((!defined($content_length)) || ($content_length =~ /\D/)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $content_length or $content_length =~ /\D/) 12 67 79
Condition100%3/3
not defined $content_length or $content_length =~ /\D/
l!l&&r!l&&!r
9367
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
815 12 $self->{status} = 411;
816 12 return;
817 }
818 67 ▶ 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"}) 11 56 67
Condition100%3/3
$self->{"max_upload_size"} >= 0 and $content_length > $self->{"max_upload_size"}
!ll&&!rl&&r
15511
MC/DC100%2/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 table100%3/3
A and B
A= $self->{"max_upload_size"} >= 0B= $content_length > $self->{"max_upload_size"}
ABresult
0X0
100
111
819 # TODO: Design a way to tell the caller to send HTTP
820 # status 413
821 11 $self->{status} = 413;
822 11 $self->_warn('Large upload prohibited');
823 11 return;
824 }
825  
826 56 ▶ 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]) { } 16 40 56
elsif ($content_type =~ m[multipart/form-data]i) { } 25 15 40
elsif ($content_type =~ m[text/xml]i) { } 8 7 15
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
31340
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
827 16 my $buffer;
828 16 ▶ if($stdin_data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($CGI::Info::stdin_data) { } 12 4 16
829 12 $buffer = $stdin_data;
830 } else {
831 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
832 1 $self->_warn('POST failed: something else may have read STDIN');
833 }
834 4 $stdin_data = $buffer;
835 }
836 16 @pairs = split(/&/, $buffer);
837  
838 # if($ENV{'QUERY_STRING'}) {
839 # my @getpairs = split(/&/, $ENV{'QUERY_STRING'});
840 # push(@pairs, @getpairs);
841 # }
842 } elsif($content_type =~ /multipart\/form-data/i) {
843 25 ▶ if(!defined($self->{upload_dir})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"upload_dir"}) 3 22 25
844 3 ▶ if($ENV{'REMOTE_ADDR'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{'REMOTE_ADDR'}) { } 1 2 3
845 # This could be an attack
846 1 $self->_warn({ warning => "$ENV{REMOTE_ADDR}: Attempt to upload a file of $content_length bytes when upload_dir has not been set" });
847 } else {
848 2 $self->_warn({ warning => 'Attempt to upload a file when upload_dir has not been set' });
849 }
850 2 $self->status(501); # Not implemented
851 2 return;
852 }
853  
854 # Validate 'upload_dir'
855 # Ensure the upload directory is safe and accessible
856 # - Check permissions
857 # - Validate path to prevent directory traversal attacks
858 # TODO: Consider using a temporary directory for uploads and moving them later
859 22 ▶ 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 17 22
860 5 $self->_warn({
861 warning => "upload_dir $self->{upload_dir} isn't a full pathname"
862 });
863 4 $self->status(500);
864 4 delete $self->{upload_dir};
865 4 return;
866 }
867 17 ▶ if(!-d $self->{upload_dir}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $self->{"upload_dir"}) 7 10 17
868 7 $self->_warn({
869 warning => "upload_dir $self->{upload_dir} isn't a directory"
870 });
871 5 $self->status(500);
872 5 delete $self->{upload_dir};
873 5 return;
874 }
875 10 ▶ if(!-w $self->{upload_dir}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-w $self->{"upload_dir"}) 2 8 10
876 2 delete $self->{paramref};
877 2 $self->_warn({
878 warning => "upload_dir $self->{upload_dir} isn't writeable"
879 });
880 1 $self->status(500);
881 1 delete $self->{upload_dir};
882 1 return;
883 }
884 8 my $tmpdir = $self->tmpdir();
885 8 ▶ if($self->{'upload_dir'} !~ /^\Q$tmpdir\E/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"upload_dir"} =~ /^\Q$tmpdir\E/) 1 7 8
886 $self->_warn({
887 1 warning => 'upload_dir ' . $self->{'upload_dir'} . " isn't somewhere in the temporary area $tmpdir"
888 });
889 1 $self->status(500);
890 1 delete $self->{upload_dir};
891 1 return;
892 }
893 7 ▶ if($content_type =~ /boundary=(\S+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($content_type =~ /boundary=(\S+)$/) 7 0 7
894 7 @pairs = $self->_multipart_data({
895 length => $content_length,
896 boundary => $1
897 });
898 }
899 } elsif($content_type =~ /text\/xml/i) {
900 8 my $buffer;
901 8 ▶ if($stdin_data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($CGI::Info::stdin_data) { } 6 2 8
902 6 $buffer = $stdin_data;
903 } else {
904 2 ▶ if(read(STDIN, $buffer, $content_length) != $content_length) {
Branch: 1 branch
BranchTrueFalseTotal
if (&CGI::Info::read("STDIN", \$buffer, $content_length) != $content_length) 0 2 2
905 0 $self->_warn({
906 warning => 'XML failed: something else may have read STDIN'
907 });
908 }
909 2 $stdin_data = $buffer;
910 }
911  
912 8 $FORM{XML} = $buffer;
913  
914 8 $self->{paramref} = \%FORM;
915  
916 8 return \%FORM;
917 } elsif($content_type =~ /application\/json/i) {
918 5 ▶ require JSON::MaybeXS && JSON::MaybeXS->import() unless JSON::MaybeXS->can('parse_json');
Branch: 1 branch
BranchTrueFalseTotal
unless "JSON::MaybeXS"->can("parse_json") 5 0 5
Condition33%2/6
'JSON::MaybeXS'->can('parse_json') || require JSON::MaybeXS && 'JSON::MaybeXS'->import
l!l&&r!l&&!r
050
require JSON::MaybeXS and "JSON::MaybeXS"->import
!ll&&!rl&&r
050
MC/DC0%0/3
'JSON::MaybeXS'->can('parse_json') || require JSON::MaybeXS && 'JSON::MaybeXS'->import
'JSON::MaybeXS'->can('parse_json') require JSON::MaybeXS "JSON::MaybeXS"->import
Truth table0%0/4
A || B and C
A= 'JSON::MaybeXS'->can('parse_json')B= require JSON::MaybeXSC= "JSON::MaybeXS"->import
ABCresult
1XX1
0111
00X0
0100
919 # require JSON::MaybeXS;
920 # JSON::MaybeXS->import();
921  
922 5 my $buffer;
923  
924 5 ▶ if($stdin_data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($CGI::Info::stdin_data) { } 4 1 5
925 4 $buffer = $stdin_data;
926 } else {
927 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
928 0 $self->_warn({
929 warning => 'read failed: something else may have read STDIN'
930 });
931 }
932 1 $stdin_data = $buffer;
933 }
934 # JSON::Parse::assert_valid_json($buffer);
935 # my $paramref = JSON::Parse::parse_json($buffer);
936 5 my $paramref = decode_json($buffer);
937 4 foreach my $key(keys(%{$paramref})) {
938 8 push @pairs, "$key=" . $paramref->{$key};
939 }
940 } else {
941 2 my $buffer;
942 2 ▶ if($stdin_data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($CGI::Info::stdin_data) { } 1 1 2
943 1 $buffer = $stdin_data;
944 } else {
945 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
946 0 $self->_warn({
947 warning => 'read failed: something else may have read STDIN'
948 });
949 }
950 1 $stdin_data = $buffer;
951 }
952  
953 2 $self->_warn({
954 warning => "POST: Invalid or unsupported content type: $content_type: $buffer",
955 });
956 }
957 } elsif($ENV{'REQUEST_METHOD'} eq 'OPTIONS') {
958 7 $self->{status} = 405;
959 7 return;
960 } elsif($ENV{'REQUEST_METHOD'} eq 'DELETE') {
961 8 $self->{status} = 405;
962 8 return;
963 } else {
964 # TODO: Design a way to tell the caller to send HTTP
965 # status 501
966 6 $self->{status} = 501;
967 $self->_warn({
968 warning => 'Use POST, GET or HEAD, not ' . $ENV{REQUEST_METHOD}
969 6 });
970 }
971  
972 388 ▶ unless(scalar @pairs) {
Branch: 1 branch
BranchTrueFalseTotal
unless (scalar @pairs) 20 368 388
973 20 return;
974 }
975  
976 368 require String::Clean::XSS;
977 368 String::Clean::XSS->import();
978 # require String::EscapeCage;
979 # String::EscapeCage->import();
980  
981 368 foreach my $arg (@pairs) {
982 2063 my($key, $value) = split(/=/, $arg, 2);
983  
984 2063 ▶ next unless($key);
Branch: 1 branch
BranchTrueFalseTotal
unless $key 10 2053 2063
985  
986 2053 $key =~ s/\0//g; # Strip encoded NUL byte poison
987 2053 $key =~ s/%00//g; # Strip NUL byte poison
988 2053 $key =~ s/%([a-fA-F\d][a-fA-F\d])/pack("C", hex($1))/eg;
989 2053 $key =~ tr/+/ /;
990 2053 ▶ if(defined($value)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $value) { } 2051 2 2053
991 2051 $value =~ s/%00//g; # Strip encoded NUL byte poison
992 2051 $value =~ s/%([a-fA-F\d][a-fA-F\d])/pack("C", hex($1))/eg; # URL-decode (1st pass)
993 2051 $value =~ s/%([a-fA-F\d][a-fA-F\d])/pack("C", hex($1))/eg; # URL-decode (2nd pass: catches %252F -> %2F -> /)
994 2051 $value =~ tr/+/ /;
995 2051 $value =~ s/\0//g; # Strip NUL: %2500 -> %00 -> NUL
996 2051 $value =~ s/%00//g; # Strip literal %00
997 } else {
998 2 $value = '';
999 }
1000  
1001 2053 $key = _sanitise_input($key);
1002  
1003 2053 ▶ if($self->{allow}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"allow"}) 183 1870 2053
1004 # Is this a permitted argument?
1005 183 ▶ if(!exists($self->{allow}->{$key})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $self->{"allow"}{$key}) 31 152 183
1006 31 $self->_info("Discard unallowed argument '$key'");
1007 31 $self->status(422);
1008 31 next; # Skip to the next parameter
1009 }
1010  
1011 # Do we allow any value, or must it be validated?
1012 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
1013 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
1014 # Can only contain one value
1015 11 ▶ if($value ne $schema) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value ne $schema) 5 6 11
1016 5 $self->_info("Block $key = $value");
1017 5 $self->status(422);
1018 5 next; # Skip to the next parameter
1019 }
1020 } elsif(ref($schema) eq 'Regexp') {
1021 59 ▶ if($value !~ $schema) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($value =~ /$schema/) 30 29 59
1022 # Simple regex
1023 30 $self->_info("Block $key = $value");
1024 30 $self->status(422);
1025 30 next; # Skip to the next parameter
1026 }
1027 } elsif(ref($schema) eq 'CODE') {
1028 28 ▶ unless($schema->($key, $value, $self)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&$schema($key, $value, $self)) 11 15 26
1029 11 $self->_info("Block $key = $value");
1030 11 next;
1031 }
1032 } else {
1033 # Set of rules
1034 35 eval {
1035 $value = Params::Validate::Strict::validate_strict({
1036 schema => { $key => $schema },
1037 args => { $key => $value },
1038 unknown_parameter_handler => 'die',
1039 35 logger => $self->{'logger'}
1040 });
1041 };
1042 35 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 9 26 35
1043 9 $self->_info("Block $key = $value: $@");
1044 9 $self->status(422);
1045 9 next; # Skip to the next parameter
1046 }
1047 26 ▶ if(scalar keys %{$value}) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %{$value;}) { } 26 0 26
1048 26 $value = $value->{$key};
1049 } else {
1050 0 $self->_info("Block $key = $value");
1051 0 $self->status(422);
1052 0 next; # Skip to the next parameter
1053 }
1054 }
1055 }
1056 }
1057  
1058 # if($self->{expect} && (List::Util::none { $_ eq $key } @{$self->{expect}})) {
1059 # next;
1060 # }
1061 1965 my $orig_value = $value;
1062 1965 $value = _sanitise_input($value);
1063  
1064 # WAF: inspect all methods (GET and POST) for injection patterns.
1065 # Previously gated on GET only, which allowed POST to bypass all checks.
1066 {
1067 # ($value =~ /\/AND\/.++\(SELECT\//) || # United/**/States)/**/AND/**/(SELECT/**/6734/**/FROM/**/(SELECT(SLEEP(5)))lRNi)/**/AND/**/(8984=8984
1068 # From http://www.symantec.com/connect/articles/detection-sql-injection-and-cross-site-scripting-attacks
1069 # Facebook FBCLID can have "--"
1070  
1071 # Pre-filter: only run quote-based regexes if value contains injection chars.
1072  
1073 # Compute pre-filter flags from orig_value so quotes stripped by
1074 # convert_XSS don't cause injection patterns to be missed
1075  
1076 1965 ▶ 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
2001945
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
1077 1965 ▶ 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
001965
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
1078 1965 ▶ 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
3601929
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
1079 1965 ▶ 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
601959
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
1080 1965 my $has_dash = index($orig_value, '--') >= 0;
1081  
1082 # All WAF patterns run on $orig_value (pre-XSS-sanitisation)
1083 # convert_XSS encodes ', =, < etc. as HTML entities, which would hide
1084 # injection patterns from the WAF if we checked $value instead.
1085 1965 ▶ 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 1941 1965
Condition88%8/9
$has_quote or $has_hash or $has_equals and $has_dash
l!l&&r!l&&!r
2041941
$has_quote or $has_hash
l!l&&r!l&&!r
2001945
$has_equals and $has_dash
!ll&&!rl&&r
1925164
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
1086 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
1087 (($has_equals && ($has_quote || $has_semi || $has_dash)) &&
1088 $orig_value =~ /(?:%3D|=)[^-]*+(?:%27|'|--|%3B|;)/i) ||
1089 ($has_quote &&
1090 # Detect 'or'-style injection: word + quote + url-encoded or literal 'or' + SQL keyword.
1091 # (?:%6F|o|%4F) = 'o', (?:%72|r|%52) = 'r', both case-folded via /i.
1092 $orig_value =~ /\w*(?:%27|')(?:%6F|o|%4F)(?:%72|r|%52)\s*(?:OR|AND|UNION|SELECT|--)/ix) ||
1093 ($has_quote &&
1094 $orig_value =~ /(?:%27|')union/ix)) {
1095 24 $self->status(403);
1096 24 ▶ if($ENV{'REMOTE_ADDR'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{'REMOTE_ADDR'}) { } 5 19 24
1097 5 $self->_warn($ENV{'REMOTE_ADDR'} . ": SQL injection attempt blocked for '$key=$orig_value'");
1098 } else {
1099 19 $self->_warn("SQL injection attempt blocked for '$key=$orig_value'");
1100 }
1101 24 return;
1102 }
1103 }
1104  
1105 1941 ▶ 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
801933
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
1106 1941 my $has_dump = index($orig_value, 'var_dump') >= 0;
1107 1941 my $has_exec = index($orig_value, 'exec') >= 0;
1108 1941 my $has_or = index($orig_value, ' OR ') >= 0;
1109 1941 my $has_and = index($orig_value, ' AND ') >= 0;
1110 1941 ▶ 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
201939
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
1111  
1112 1941 ▶ 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 1923 1941
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
1441923
$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
1401927
$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
1311927
$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
1211928
$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
931929
$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
721932
$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
521934
$has_select and $orig_value =~ /\bselect\b.{1,500}?\bfrom\b/is
!ll&&!rl&&r
193335
$has_and and $orig_value =~ /\sAND\s1=1/xi
!ll&&!rl&&r
193042
$has_or and $orig_value =~ /\bOR\s+\d+\s*=\s*\d+/i
!ll&&!rl&&r
192932
$has_or and $has_and and $orig_value =~ /\sOR\s.{1,500}?\sAND\s/
!ll&&!rl&&r
192903
$has_or and $has_and
!ll&&!rl&&r
192903
$has_slash and $orig_value =~ m[/\*\*/ORDER/\*\*/BY/\*\*]xi
!ll&&!rl&&r
192801
$has_dump and $orig_value =~ /var_dump[^m]*+md5/
!ll&&!rl&&r
192701
$has_slash and $has_select and $orig_value =~ m[/AND/[^(]*+\(SELECT/]
!ll&&!rl&&r
192700
$has_slash and $has_select
!ll&&!rl&&r
192700
$has_exec and $orig_value =~ /exec[\s+]++[sx]p\w+/xi
!ll&&!rl&&r
192304
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
1113 # {1,500}? is lazy+bounded: avoids catastrophic backtracking on
1114 # "SELECT aaaa...aaaa" (no FROM) while still catching real queries.
1115 ($has_select && $orig_value =~ /\bselect\b.{1,500}?\bfrom\b/is) ||
1116 ($has_and && $orig_value =~ /\sAND\s1=1/ix) ||
1117 # Numeric tautology without quotes: OR 1=1, OR 2=2, etc.
1118 ($has_or && $orig_value =~ /\bOR\s+\d+\s*=\s*\d+/i) ||
1119 # Bounded lazy .{1,500}? avoids backtracking on "OR aaaa..." with no AND.
1120 ($has_or && $has_and && $orig_value =~ /\sOR\s.{1,500}?\sAND\s/) ||
1121 ($has_slash && $orig_value =~ /\/\*\*\/ORDER\/\*\*\/BY\/\*\*/ix) ||
1122 ($has_dump && $orig_value =~ /var_dump[^m]*+md5/) ||
1123 ($has_slash && $has_select && $orig_value =~ /\/AND\/[^(]*+\(SELECT\//) ||
1124 ($has_exec && $orig_value =~ /exec[\s+]++[sx]p\w+/ix)) {
1125 18 $self->status(403);
1126 18 ▶ if($ENV{'REMOTE_ADDR'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{'REMOTE_ADDR'}) { } 6 12 18
1127 6 $self->_warn($ENV{'REMOTE_ADDR'} . ": SQL injection attempt blocked for '$key=$orig_value'");
1128 } else {
1129 12 $self->_warn("SQL injection attempt blocked for '$key=$orig_value'");
1130 }
1131 18 return;
1132 }
1133  
1134 1923 ▶ if(my $agent = $ENV{'HTTP_USER_AGENT'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $agent = $ENV{"HTTP_USER_AGENT"}) 36 1887 1923
1135 # Bounded lazy .{1,500}? separates SQL keyword pairs without catastrophic backtracking.
1136 # Possessive .++ would consume the trailing anchor — never match. Unbounded .+ risks ReDoS.
1137 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
1138 3 $self->status(403);
1139 3 ▶ if($ENV{'REMOTE_ADDR'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{'REMOTE_ADDR'}) { } 2 1 3
1140 2 $self->_warn($ENV{'REMOTE_ADDR'} . ": SQL injection attempt blocked for '$agent'");
1141 } else {
1142 1 $self->_warn("SQL injection attempt blocked for '$agent'");
1143 }
1144 3 return;
1145 }
1146 }
1147  
1148 # XSS detection using [^>]+ instead of .+ or .++ :
1149 # - [^>]+ stops naturally at '>' — no backtracking, no ReDoS.
1150 # - [^>] also matches '\n', so multi-line payloads like
1151 # "<img\nsrc=x\nonerror=alert(1)>" are caught without /s.
1152 # - Replaces both the old [^\n]+ (stopped at newline — bypass)
1153 # and the broken .++ (possessive consumed '>' — never matched).
1154 1920 ▶ 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 1898 1920
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
1751898
$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
0171903
$value =~ m[(?:%3C|<)(?:%2F|/)*[a-z0-9%]+(?:%3E|>)]xi or $value =~ /(?:%3C|<)[^>]+(?:%3E|>)/i
l!l&&r!l&&!r
001920
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
1155 ($value =~ /(?:%3C|<)[^>]+(?:%3E|>)/i) ||
1156 ($orig_value =~ /(?:%3C|<)(?:%2F|\/)*[a-z0-9%]+(?:%3E|>)/ix) ||
1157 ($orig_value =~ /(?:%3C|<)[^>]+(?:%3E|>)/i)) {
1158 22 $self->status(403);
1159 22 $self->_warn("XSS injection attempt blocked for '$value'");
1160 22 return;
1161 }
1162  
1163 # Block javascript: URI scheme — no angle brackets, but still executes
1164 # script when used in href or src attributes.
1165 1898 ▶ if($orig_value =~ /\bjavascript\s*:/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($orig_value =~ /\bjavascript\s*:/i) 2 1896 1898
1166 2 $self->status(403);
1167 2 $self->_warn("XSS injection attempt blocked for '$value'");
1168 2 return;
1169 }
1170  
1171 1896 ▶ if($value =~ /mustleak\.com\//) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value =~ m[mustleak\.com/]) 7 1889 1896
1172 7 $self->status(403);
1173 7 $self->_warn("Blocked mustleak attack for '$key'");
1174 7 return;
1175 }
1176  
1177 1889 ▶ if($value =~ /\.\.\//) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value =~ m[\.\./]) 15 1874 1889
1178 15 $self->status(403);
1179 15 $self->_warn("Blocked directory traversal attack for '$key'");
1180 14 return;
1181 }
1182 }
1183 1874 ▶ if(length($value) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $value > 0) 1862 12 1874
1184 # Don't add if it's already there
1185 1862 ▶ if($FORM{$key} && ($FORM{$key} ne $value)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($FORM{$key} and $FORM{$key} ne $value) { } 9 1853 1862
Condition100%3/3
$FORM{$key} and $FORM{$key} ne $value
!ll&&!rl&&r
185219
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
1186 9 $FORM{$key} .= ",$value";
1187 } else {
1188 1853 $FORM{$key} = $value;
1189 }
1190 }
1191 }
1192  
1193 275 ▶ unless(%FORM) {
Branch: 1 branch
BranchTrueFalseTotal
unless (%FORM) 41 234 275
1194 41 return;
1195 }
1196  
1197 234 ▶ if($self->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 234 0 234
1198 234 ▶ while(my ($key,$value) = each %FORM) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %FORM) 1843 234 2077
1199 1843 $self->_debug("$key=$value");
1200 }
1201 }
1202  
1203 234 $self->{paramref} = \%FORM;
1204  
1205 234 return Return::Set::set_return(\%FORM, { type => 'hashref', min => 1 });
1206 }
1207  
1208 =head2 param($field)
1209  
1210 Get a single CGI parameter value by name.
1211 When called without arguments it delegates to C<params()> and returns all parameters.
1212 When called with a field name it returns that parameter's (sanitised) value,
1213 or C<undef> if the parameter was not supplied or is not in the allow list.
1214  
1215 use CGI::Info;
1216 my $info = CGI::Info->new();
1217 my $bar = $info->param('foo');
1218  
1219 # With an allow list:
1220 my $info2 = CGI::Info->new();
1221 my $allowed = { foo => qr/\d+/ };
1222 $info2->params(allow => $allowed);
1223 my $bar2 = $info2->param('bar'); # logs a warning; returns undef
1224  
1225 =over 4
1226  
1227 =item $field
1228  
1229 Optional. The name of the CGI parameter to retrieve.
1230 If omitted, all parameters (as a hash-ref) are returned via C<params()>.
1231  
1232 =back
1233  
1234 =head3 API SPECIFICATION
1235  
1236 =head4 Input
1237  
1238 {
1239 field => { type => 'scalar', optional => 1 },
1240 }
1241  
1242 =head4 Output
1243  
1244 # When $field is supplied
1245 { type => 'scalar', optional => 1 }
1246 # When $field is omitted (delegates to params())
1247 { type => 'hashref', optional => 1 }
1248  
1249 =head3 MESSAGES
1250  
1251 | Level | Message | Meaning | Action |
1252 |-------|------------------------------------------|--------------------------------------|-----------------------------------------|
1253 | warn | param: <field> isn't in the allow list | Caller requested a parameter outside | Review the allow list passed to new() |
1254 | | | the schema set by params(allow=>\%h) | or params(); add the key if legitimate |
1255  
1256 =cut
1257  
1258 87 ▶sub param {
Subroutine param: called CC=8 SCAR=20.8
Pod documented
1259 87 my ($self, $field) = @_;
1260  
1261 87 ▶ if(!defined($field)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $field) 6 81 87
1262 6 return $self->params();
1263 }
1264 # Is this a permitted argument?
1265 81 ▶ if($self->{allow} && !exists($self->{allow}->{$field})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"allow"} and not exists $self->{"allow"}{$field}) 11 70 81
Condition100%3/3
$self->{"allow"} and not exists $self->{"allow"}{$field}
!ll&&!rl&&r
502011
MC/DC100%2/2
$self->{"allow"} and not exists $self->{"allow"}{$field}
$self->{"allow"} not exists $self->{"allow"}{$field}
Truth table100%3/3
A and not(B)
A= $self->{"allow"}B= not exists $self->{"allow"}{$field}
ABresult
0X0
100
111
1266 11 $self->_warn({
1267 warning => "param: $field isn't in the allow list"
1268 });
1269 7 return;
1270 }
1271  
1272 # Prevent deep recursion which can happen when a validation routine calls param()
1273 70 my $allow;
1274 70 ▶ if($self->{in_param} && $self->{allow}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"in_param"} and $self->{"allow"}) 4 66 70
Condition66%2/3
$self->{"in_param"} and $self->{"allow"}
!ll&&!rl&&r
6604
MC/DC50%1/2
$self->{"in_param"} and $self->{"allow"}
$self->{"in_param"} $self->{"allow"}
Truth table66%2/3
A and B
A= $self->{"in_param"}B= $self->{"allow"}
ABresult
0X0
100
111
1275 4 $allow = delete $self->{allow};
1276 }
1277 70 $self->{in_param} = 1;
1278  
1279 70 my $params = $self->params();
1280  
1281 70 $self->{in_param} = 0;
1282 70 ▶ $self->{allow} = $allow if($allow);
Branch: 1 branch
BranchTrueFalseTotal
if $allow 4 66 70
1283  
1284 70 ▶ if($params) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params) 63 7 70
1285 63 return Return::Set::set_return($params->{$field}, { type => 'string' });
1286 }
1287 }
1288  
1289 4024 ▶sub _sanitise_input :Protected {
Subroutine _sanitise_input: called CC=6 SCAR=18.9
1290 4024 my $arg = shift;
1291  
1292 # Protected function: inline check because the ($) prototype means no $self,
1293 4024 ▶ unless($ENV{HARNESS_ACTIVE}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ENV{"HARNESS_ACTIVE"}) 2300 1724 4024
1294 2300 my $calling_pkg = (caller)[0];
1295 2300 ▶ 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 2300 2300
Condition33%2/6
$calling_pkg and $calling_pkg eq __PACKAGE__ || $calling_pkg->isa(__PACKAGE__)
!ll&&!rl&&r
002300
$calling_pkg eq __PACKAGE__ or $calling_pkg->isa(__PACKAGE__)
l!l&&r!l&&!r
230000
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
1296 0 Carp::croak('_sanitise_input() is a protected function and cannot be called from outside ' . __PACKAGE__);
1297 }
1298 }
1299  
1300 4024 ▶ return if(!defined($arg));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $arg 1 4023 4024
1301  
1302 # Remove hacking attempts and spaces
1303 4023 $arg =~ s/[\r\n]//g;
1304 4023 $arg =~ s/\s+$//;
1305 4023 $arg =~ s/^\s+//;
1306  
1307 # Possessive quantifier prevents catastrophic backtracking when input
1308 # contains '<!--' with no matching closing '-->'.
1309 4023 $arg =~ s/<!--[^-]*+(?:-(?!->)[^-]*+)*+-->//g;
1310 # Allow :
1311 # $arg =~ s/[;<>\*|`&\$!?#\(\)\[\]\{\}'"\\\r]//g;
1312  
1313 # return $arg;
1314 # return String::EscapeCage->new(convert_XSS($arg))->escapecstring();
1315 4023 return convert_XSS($arg);
1316 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1317  
1318 7 ▶sub _multipart_data :Protected {
Subroutine _multipart_data: called CC=20 SCAR=30.5
1319 7 my ($self, $args) = @_;
1320  
1321 7 $self->_trace('Entering _multipart_data');
1322  
1323 7 my $total_bytes = $$args{length};
1324  
1325 7 $self->_debug("_multipart_data: total_bytes = $total_bytes");
1326  
1327 7 ▶ if($total_bytes == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($total_bytes == 0) 0 7 7
1328 0 return;
1329 }
1330  
1331 7 ▶ unless($stdin_data) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($CGI::Info::stdin_data) 6 1 7
1332 6 ▶ while(<STDIN>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline STDIN)) 54 6 60
1333 54 chop(my $line = $_);
1334 54 $line =~ s/[\r\n]//g;
1335 54 $stdin_data .= "$line\n";
1336 }
1337 6 ▶ if(!$stdin_data) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($CGI::Info::stdin_data) 0 6 6
1338 0 return;
1339 }
1340 }
1341  
1342 7 my $boundary = $$args{boundary};
1343  
1344 7 my @pairs;
1345 7 my $writing_file = 0;
1346 7 my $key;
1347 my $value;
1348 7 my $in_header = 0;
1349 7 my $fout;
1350  
1351 7 foreach my $line(split(/\n/, $stdin_data)) {
1352 45 ▶ if($line =~ /^--\Q$boundary\E--$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^--\Q$boundary\E--$/) 2 43 45
1353 2 last;
1354 }
1355 43 ▶ if($line =~ /^--\Q$boundary\E$/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($line =~ /^--\Q$boundary\E$/) { } 10 33 43
elsif ($in_header) { } 20 13 33
1356 10 ▶ if($writing_file) {
Branch: 2 branches
BranchTrueFalseTotal
if ($writing_file) { } 0 10 10
elsif (defined $key) { } 4 6 10
1357 0 close $fout;
1358 0 $writing_file = 0;
1359 } elsif(defined($key)) {
1360 4 push(@pairs, "$key=$value");
1361 4 $value = undef;
1362 }
1363 10 $in_header = 1;
1364 } elsif($in_header) {
1365 20 ▶ if(length($line) == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (length $line == 0) { } 8 12 20
elsif ($line =~ /^Content-Disposition: (.+)/i) { } 10 2 12
1366 8 $in_header = 0;
1367 } elsif($line =~ /^Content-Disposition: (.+)/i) {
1368 10 my $field = $1;
1369 10 ▶ if($field =~ /name="(.+?)"/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($field =~ /name="(.+?)"/) 10 0 10
1370 10 $key = $1;
1371 }
1372 # [^"]+ instead of .+ : stops at first '"' without backtracking,
1373 # and cannot accidentally capture across the closing delimiter.
1374 10 ▶ if($field =~ /filename="([^"]+)?"/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($field =~ /filename="([^"]+)?"/) 6 4 10
1375 6 my $filename = $1;
1376 6 ▶ unless(defined($filename)) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $filename) { } 6 0 6
if (do { $filename =~ m[[\\/\|]] }) { } 2 4 6
1377 0 $self->_warn('No upload filename given');
1378 } elsif($filename =~ /[\\\/\|]/) {
1379 2 $self->_warn("Disallowing invalid filename: $filename");
1380 } else {
1381 4 $filename = $self->_create_file_name({
1382 filename => $filename
1383 });
1384  
1385 # Don't do this since it taints the string and I can't work out how to untaint it
1386 # my $full_path = Cwd::realpath(File::Spec->catfile($self->{upload_dir}, $filename));
1387 # $full_path =~ m/^(\/[\w\.]+)$/;
1388 4 my $full_path = File::Spec->catfile($self->{upload_dir}, $filename);
1389 4 ▶ unless(open($fout, '>', $full_path)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&CGI::Info::open($fout, ">", $full_path)) 0 4 4
1390 0 $self->_warn("Can't open $full_path");
1391 }
1392 4 $writing_file = 1;
1393 4 push(@pairs, "$key=$filename");
1394 }
1395 }
1396 }
1397 # TODO: handle Content-Type: text/plain, etc.
1398 } else {
1399 13 ▶ if($writing_file) {
Branch: 1 branch
BranchTrueFalseTotal
if ($writing_file) { } 8 5 13
1400 8 print $fout "$line\n";
1401 } else {
1402 5 $value .= $line;
1403 }
1404 }
1405 }
1406  
1407 5 ▶ if($writing_file) {
Branch: 1 branch
BranchTrueFalseTotal
if ($writing_file) 4 1 5
1408 4 close $fout;
1409 }
1410  
1411 5 $self->_trace('Leaving _multipart_data');
1412  
1413 5 return @pairs;
1414 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1415  
1416 # Robust filename generation (preventing overwriting).
1417 # Previously used "! -e $rc" which checked existence in the CURRENT WORKING
1418 # DIRECTORY, not the upload directory — a logic bug and a TOCTOU race.
1419 # Now checks in the actual upload directory and caps iterations to avoid
1420 # an infinite loop if the directory fills up.
1421 7 ▶sub _create_file_name :Protected {
Subroutine _create_file_name: called CC=6 SCAR=18.1
1422 7 my ($self, $args) = @_;
1423  
1424 7 my $upload_dir = $self->{upload_dir};
1425 7 my $filename = $$args{filename} . '_' . time;
1426  
1427 7 my $counter = 0;
1428 7 my $rc;
1429 7 ▶ 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 } } 7 1 8
$upload_dir ? : 4 4 8
Condition66%2/3
not -e ($upload_dir ? "File::Spec"->catfile($upload_dir, $rc) : $rc) or $counter > 1000
l!l&&r!l&&!r
701
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
1430 8 ▶ $rc = $filename . ($counter ? "_$counter" : '');
Branch: 1 branch
BranchTrueFalseTotal
$counter ? : 1 7 8
1431 8 $counter++;
1432 # Check in upload_dir when set; otherwise check relative to CWD.
1433 # File::Spec->catfile('', ...) produces an absolute path, so we
1434 # must not pass an empty string as the directory component.
1435 } until(
1436 ! -e ($upload_dir ? File::Spec->catfile($upload_dir, $rc) : $rc)
1437 || $counter > 1000
1438 );
1439 7 ▶ if($counter > 1000) {
Branch: 1 branch
BranchTrueFalseTotal
if ($counter > 1000) 0 7 7
1440 0 Carp::croak('_create_file_name: unable to find a unique filename after 1000 attempts');
1441 }
1442  
1443 7 return $rc;
1444 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1445  
1446 # Untaint a filename. Regex from CGI::Untaint::Filenames
1447 105 ▶sub _untaint_filename :Protected {
Subroutine _untaint_filename: called CC=2 SCAR=6.9
1448 105 my ($self, $args) = @_;
1449  
1450 105 ▶ if($$args{filename} =~ /(^[\w\+_\040\#\(\)\{\}\[\]\/\-\^,\.:;&%@\\~]+\$?$)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"filename"} =~ m<(^[\w\+_\040\#\(\)\{\}\[\]/\-\^,\.:;&%\@\\~]+\$?$)>) 103 2 105
1451 103 return $1;
1452 }
1453 2 return;
1454 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1455  
1456 =head2 is_mobile
1457  
1458 Returns a boolean if the website is being viewed on a mobile
1459 device such as a smartphone.
1460 All tablets are mobile, but not all mobile devices are tablets.
1461  
1462 Can be overridden by the IS_MOBILE environment setting
1463  
1464 =cut
1465  
1466 225 ▶sub is_mobile {
Subroutine is_mobile: called CC=21 SCAR=30.7
Pod documented
1467 225 my $self = shift;
1468  
1469 225 ▶ if(defined($self->{is_mobile})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"is_mobile"}) 126 99 225
1470 126 return $self->{is_mobile};
1471 }
1472  
1473 99 ▶ if($ENV{'IS_MOBILE'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{"IS_MOBILE"}) 4 95 99
1474 4 return $ENV{'IS_MOBILE'}
1475 }
1476  
1477 # Support Sec-CH-UA-Mobile
1478 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
1479 12 ▶ if($ch_ua_mobile eq '?1') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ch_ua_mobile eq "?1") 5 7 12
1480 5 $self->{is_mobile} = 1;
1481 5 return 1;
1482 }
1483 }
1484  
1485 90 ▶ if($ENV{'HTTP_X_WAP_PROFILE'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{"HTTP_X_WAP_PROFILE"}) 3 87 90
1486 # E.g. Blackberry
1487 # TODO: Check the sanity of this variable
1488 3 $self->{is_mobile} = 1;
1489 3 return 1;
1490 }
1491  
1492 87 ▶ if(my $agent = $ENV{'HTTP_USER_AGENT'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $agent = $ENV{"HTTP_USER_AGENT"}) 69 18 87
1493 # Was '.+(Android|iPhone).+' — .+ before and after adds no useful
1494 # constraint but causes ReDoS on long UAs without those tokens.
1495 69 ▶ if($agent =~ /\b(?:Android|iPhone)\b/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($agent =~ /\b(?:Android|iPhone)\b/) 20 49 69
1496 20 $self->{is_mobile} = 1;
1497 20 return 1;
1498 }
1499  
1500 # From http://detectmobilebrowsers.com/
1501 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
1502 1 $self->{is_mobile} = 1;
1503 1 return 1;
1504 }
1505  
1506 # Save loading and calling HTTP::BrowserDetect
1507 48 my $remote = $ENV{'REMOTE_ADDR'};
1508 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
1509 4 ▶ if(my $type = $self->{cache}->get("$remote/$agent")) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $type = $self->{"cache"}->get("$remote/$agent")) 3 1 4
1510 3 return $self->{is_mobile} = ($type eq 'mobile');
1511 }
1512 }
1513  
1514 45 ▶ unless($self->{browser_detect}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"browser_detect"}) 37 8 45
1515 37 ▶ if(eval { require HTTP::BrowserDetect; }) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { require HTTP::BrowserDetect } }) 37 0 37
1516 37 HTTP::BrowserDetect->import();
1517 37 $self->{browser_detect} = HTTP::BrowserDetect->new($agent);
1518 }
1519 }
1520  
1521 45 ▶ if($self->{browser_detect}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"browser_detect"}) 45 0 45
1522 45 my $device = $self->{browser_detect}->device();
1523 # Without the ?1:0 it will set to the empty string not 0
1524 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
1525 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
1526 0 $self->{cache}->set("$remote/$agent", 'mobile', $CACHE_TTL_SEARCH);
1527 }
1528 45 return $self->{is_mobile} = $is_mobile;
1529 }
1530 }
1531  
1532 18 return 0;
1533 }
1534  
1535 =head2 is_tablet
1536  
1537 Returns a boolean if the website is being viewed on a tablet such as an iPad.
1538  
1539 =cut
1540  
1541 19 ▶sub is_tablet {
Subroutine is_tablet: called CC=4 SCAR=13.9
Pod documented
1542 19 my $self = shift;
1543  
1544 19 ▶ if(defined($self->{is_tablet})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"is_tablet"}) 4 15 19
1545 4 return $self->{is_tablet};
1546 }
1547  
1548 # Was '.+(iPad|TabletPC).+' — same ReDoS risk as the mobile pattern above.
1549 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
1550 # TODO: add others when I see some nice user_agents
1551 5 $self->{is_tablet} = 1;
1552 } else {
1553 10 $self->{is_tablet} = 0;
1554 }
1555  
1556 15 return $self->{is_tablet};
1557 }
1558  
1559 =head2 as_string
1560  
1561 Converts CGI parameters into a formatted string representation with optional raw mode (no escaping of special characters).
1562 Useful for debugging or generating keys for a cache.
1563  
1564 my $string_representation = $info->as_string();
1565 my $raw_string = $info->as_string({ raw => 1 });
1566  
1567 =head3 API SPECIFICATION
1568  
1569 =head4 INPUT
1570  
1571 {
1572 raw => {
1573 'type' => 'boolean',
1574 'optional' => 1,
1575 }
1576 }
1577  
1578 =head4 OUTPUT
1579  
1580 {
1581 type => 'string',
1582 optional => 1,
1583 }
1584  
1585 =cut
1586  
1587 sub as_string
1588 60 ▶{
Subroutine as_string: called CC=5 SCAR=16.1
Pod documented
1589 60 my $self = shift;
1590  
1591 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
1592 args => Params::Get::get_params(undef, @_) || {},
1593 schema => {
1594 raw => {
1595 'type' => 'boolean',
1596 'optional' => 1
1597 }
1598 }
1599 });
1600  
1601 # Retrieve object parameters
1602 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
1603  
1604 47 my $rc;
1605  
1606 47 ▶ if($args->{'raw'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{'raw'}) { } 7 40 47
1607 # Raw mode: return key=value pairs without escaping
1608 $rc = join '; ', map {
1609 10 "$_=" . $params->{$_}
1610 7 } sort keys %{$params};
1611 } else {
1612 # Escaped mode: escape special characters
1613 $rc = join '; ', map {
1614 62 my $value = $params->{$_};
1615  
1616 62 $value =~ s/\\/\\\\/g; # Escape backslashes
1617 62 $value =~ s/(;|=)/\\$1/g; # Escape semicolons and equals signs
1618 62 "$_=$value"
1619 40 } sort keys %{$params};
1620 }
1621  
1622 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
1623  
1624 47 $self->_trace("as_string: returning '$rc'");
1625  
1626 47 return $rc;
1627 }
1628  
1629 =head2 protocol
1630  
1631 Returns the connection protocol, presumably 'http' or 'https', or undef if
1632 it can't be determined.
1633  
1634 =cut
1635  
1636 63 ▶sub protocol {
Subroutine protocol: called CC=16 SCAR=28.4
Pod documented
1637 63 my $self = shift;
1638  
1639 # Cached: ENV is read-only during a CGI request, so the result never changes.
1640 # Use exists (not defined) so we cache undef for the "unknown" case too.
1641 # Guard with ref() because protocol() may be called as a class method.
1642 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
1643  
1644 # RFC 3986 §3.1: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
1645 # Character-class [^:]+ avoids the O(n) backtracking of the former (.+)://
1646 57 my $result;
1647 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
1648 9 $result = $1;
1649 ▶ } 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
1650 7 $result = 'http';
1651 } elsif(my $port = $ENV{'SERVER_PORT'}) {
1652 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
1653 0 ▶ if($name =~ /^https?$/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($name =~ /^https?$/) { } 0 0 0
elsif ($name eq 'www') { } 0 0 0
1654 0 $result = $name;
1655 } elsif($name eq 'www') {
1656 # e.g. NetBSD and OpenBSD
1657 0 $result = 'http';
1658 }
1659 # else: unrecognised service name — $result stays undef
1660 } elsif($port == 80) {
1661 # e.g. Solaris
1662 7 $result = 'http';
1663 } elsif($port == 443) {
1664 6 $result = 'https';
1665 }
1666 }
1667  
1668 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
1669 2 $self->_warn("Can't determine the calling protocol");
1670 }
1671 57 ▶ $self->{'protocol'} = $result if ref($self);
Branch: 1 branch
BranchTrueFalseTotal
if ref $self 53 4 57
1672 57 return $result;
1673 }
1674  
1675 =head2 tmpdir
1676  
1677 Returns the name of a directory that you can use to create temporary files
1678 in.
1679  
1680 The routine is preferable to L<File::Spec/tmpdir> since CGI programs are
1681 often running on shared servers. Having said that, tmpdir will fall back
1682 to File::Spec->tmpdir() if it can't find somewhere better.
1683  
1684 If the parameter 'default' is given, then use that directory as a
1685 fall-back rather than the value in File::Spec->tmpdir().
1686 No sanity tests are done, so if you give the default value of
1687 '/non-existant', that will be returned.
1688  
1689 Tmpdir allows a reference of the options to be passed.
1690  
1691 use CGI::Info;
1692  
1693 my $info = CGI::Info->new();
1694 my $dir = $info->tmpdir(default => '/var/tmp');
1695 $dir = $info->tmpdir({ default => '/var/tmp' });
1696  
1697 # or
1698  
1699 my $dir = CGI::Info->tmpdir();
1700 =cut
1701  
1702 47 ▶sub tmpdir {
Subroutine tmpdir: called CC=16 SCAR=28.0
Pod documented
1703 47 my $self = shift;
1704  
1705 47 my $name = 'tmp';
1706 47 ▶ if($^O eq 'MSWin32') {
Branch: 1 branch
BranchTrueFalseTotal
if ($^O eq "MSWin32") 0 47 47
1707 0 $name = 'temp';
1708 }
1709  
1710 47 my $dir;
1711  
1712 47 ▶ if(!ref($self)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $self) 5 42 47
1713 5 $self = __PACKAGE__->new();
1714 }
1715 47 my $params = Params::Get::get_params(undef, @_);
1716  
1717 47 ▶ 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"}) 9 38 47
Condition100%3/3
$ENV{"C_DOCUMENT_ROOT"} and -d $ENV{"C_DOCUMENT_ROOT"}
!ll&&!rl&&r
3269
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
1718 9 $dir = File::Spec->catdir($ENV{'C_DOCUMENT_ROOT'}, $name);
1719 9 ▶ if((-d $dir) && (-w $dir)) {
Branch: 1 branch
BranchTrueFalseTotal
if (-d $dir and -w $dir) 3 6 9
Condition66%2/3
-d $dir and -w $dir
!ll&&!rl&&r
603
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
1720 3 return $self->_untaint_filename({ filename => $dir });
1721 }
1722 6 $dir = $ENV{'C_DOCUMENT_ROOT'};
1723 6 ▶ if((-d $dir) && (-w $dir)) {
Branch: 1 branch
BranchTrueFalseTotal
if (-d $dir and -w $dir) 6 0 6
Condition33%1/3
-d $dir and -w $dir
!ll&&!rl&&r
006
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
1724 6 return $self->_untaint_filename({ filename => $dir });
1725 }
1726 }
1727 38 ▶ if($ENV{'DOCUMENT_ROOT'} && (-d $ENV{'DOCUMENT_ROOT'})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{"DOCUMENT_ROOT"} and -d $ENV{"DOCUMENT_ROOT"}) 2 36 38
Condition100%3/3
$ENV{"DOCUMENT_ROOT"} and -d $ENV{"DOCUMENT_ROOT"}
!ll&&!rl&&r
3152
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
1728 2 $dir = File::Spec->catdir($ENV{'DOCUMENT_ROOT'}, File::Spec->updir(), $name);
1729 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
1730 1 return $self->_untaint_filename({ filename => $dir });
1731 }
1732 }
1733 37 ▶ if($params->{'default'} && ref($params->{'default'})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{"default"} and ref $params->{"default"}) 2 35 37
Condition100%3/3
$params->{"default"} and ref $params->{"default"}
!ll&&!rl&&r
2872
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
1734 2 croak(ref($self), ': tmpdir must be given a scalar');
1735 }
1736 35 ▶ return $params->{default} ? $params->{default} : File::Spec->tmpdir();
Branch: 1 branch
BranchTrueFalseTotal
$params->{'default'} ? : 7 28 35
1737 }
1738  
1739 =head2 rootdir
1740  
1741 Returns the document root. This is preferable to looking at DOCUMENT_ROOT
1742 in the environment because it will also work when we're not running as a CGI
1743 script, which is useful for script debugging.
1744  
1745 This can be run as a class or object method.
1746  
1747 use CGI::Info;
1748  
1749 print CGI::Info->rootdir();
1750  
1751 =cut
1752  
1753 36 ▶sub rootdir {
Subroutine rootdir: called CC=12 SCAR=27.7
Pod documented
1754 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
1755 15 return $ENV{'C_DOCUMENT_ROOT'};
1756 ▶ } 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
1757 9 return $ENV{'DOCUMENT_ROOT'};
1758 }
1759 # $0 is tainted under -T; untaint with a permissive but defined capture.
1760 # The leading . before cgi-bin was also a regex bug (matched any char);
1761 # corrected to match a path separator so the kludge fires only on real paths.
1762 12 my ($script_name) = $0 =~ /^(.+)$/;
1763 12 ▶ return '' unless defined $script_name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $script_name 0 12 12
1764  
1765 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
1766 12 $script_name = File::Spec->rel2abs($script_name);
1767 }
1768 12 ▶ if($script_name =~ /[\/\\]cgi-bin/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($script_name =~ m([/\\]cgi-bin)) 0 12 12
1769 0 $script_name =~ s/[\/\\]cgi-bin.*//;
1770 }
1771 12 ▶ if(-f $script_name) { # More kludge
Branch: 1 branch
BranchTrueFalseTotal
if (-f $script_name) 12 0 12
1772 12 ▶ if($^O eq 'MSWin32') {
Branch: 1 branch
BranchTrueFalseTotal
if ($^O eq 'MSWin32') { } 0 12 12
1773 0 ▶ if($script_name =~ /(.+)\\.+?$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($script_name =~ /(.+)\\.+?$/) 0 0 0
1774 0 return $1;
1775 }
1776 } else {
1777 12 ▶ if($script_name =~ /(.+)\/.+?$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($script_name =~ m[(.+)/.+?$]) 12 0 12
1778 12 return $1;
1779 }
1780 }
1781 }
1782 0 return $script_name;
1783 }
1784  
1785 =head2 root_dir
1786  
1787 Synonym of rootdir(), for compatibility with L<CHI>.
1788  
1789 =cut
1790  
1791 sub root_dir
1792 9 ▶{
Subroutine root_dir: called CC=3 SCAR=11.0
Pod documented
1793 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
1794 4 my $self = shift;
1795  
1796 4 return $self->rootdir(@_);
1797 }
1798 5 return __PACKAGE__->rootdir(@_);
1799 }
1800  
1801 =head2 documentroot
1802  
1803 Synonym of rootdir(), for compatibility with Apache.
1804  
1805 =cut
1806  
1807 sub documentroot
1808 8 ▶{
Subroutine documentroot: called CC=3 SCAR=11.0
Pod documented
1809 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
1810 3 my $self = shift;
1811  
1812 3 return $self->rootdir(@_);
1813 }
1814 5 return __PACKAGE__->rootdir(@_);
1815 }
1816  
1817 =head2 logdir($dir)
1818  
1819 Gets and sets the name of a directory where you can store logs.
1820  
1821 =over 4
1822  
1823 =item $dir
1824  
1825 Path to the directory where logs will be stored.
1826  
1827 =back
1828  
1829 =cut
1830  
1831 21 ▶sub logdir {
Subroutine logdir: called CC=14 SCAR=26.8
Pod documented
1832 21 my $self = shift;
1833 21 my $dir = shift;
1834  
1835 21 ▶ if(!ref($self)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $self) 1 20 21
1836 1 $self = __PACKAGE__->new();
1837 }
1838  
1839 21 ▶ if($dir) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dir) 11 10 21
1840 11 ▶ if(length($dir) && (-d $dir) && (-w $dir)) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $dir and -d $dir and -w $dir) 5 6 11
Condition83%5/6
length $dir and -d $dir and -w $dir
!ll&&!rl&&r
425
length $dir and -d $dir
!ll&&!rl&&r
047
MC/DC66%2/3
length $dir and -d $dir and -w $dir
length $dir -d $dir -w $dir
Truth table75%3/4
A and B and C
A= length $dirB= -d $dirC= -w $dir
ABCresult
0XX0
10X0
1100
1111
1841 5 return $self->{'logdir'} = $dir;
1842 }
1843 6 $self->_warn("Invalid logdir: $dir");
1844 6 Carp::croak("Invalid logdir: $dir");
1845 }
1846  
1847 10 foreach my $rc($self->{logdir}, $ENV{'LOGDIR'}, Sys::Path->logdir(), $self->tmpdir()) {
1848 26 ▶ if(defined($rc) && length($rc) && (-d $rc) && (-w $rc)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rc and length $rc and -d $rc and -w $rc) 10 16 26
Condition77%7/9
defined $rc and length $rc and -d $rc and -w $rc
!ll&&!rl&&r
16010
defined $rc and length $rc and -d $rc
!ll&&!rl&&r
11510
defined $rc and length $rc
!ll&&!rl&&r
11015
MC/DC50%2/4
defined $rc and length $rc and -d $rc and -w $rc
defined $rc length $rc -d $rc -w $rc
Truth table60%3/5
A and B and C and D
A= defined $rcB= length $rcC= -d $rcD= -w $rc
ABCDresult
0XXX0
10XX0
110X0
11100
11111
1849 10 $dir = $rc;
1850 10 last;
1851 }
1852 }
1853 10 ▶ $self->_warn("Can't determine logdir") if((!defined($dir)) || (length($dir) == 0));
Branch: 1 branch
BranchTrueFalseTotal
if not defined $dir or length $dir == 0 0 10 10
Condition33%1/3
not defined $dir or length $dir == 0
l!l&&r!l&&!r
0010
MC/DC0%0/2
not defined $dir or length $dir == 0
not defined $dir length $dir == 0
Truth table33%1/3
not(A) or B
A= not defined $dirB= length $dir == 0
ABresult
1X1
011
000
1854 10 ▶ $self->{logdir} ||= $dir;
Condition66%2/3
$self->{"logdir"} ||= $dir
l!l&&r!l&&!r
460
MC/DC0%0/2
$self->{"logdir"} ||= $dir
$self->{"logdir"} $dir
Truth table66%2/3
A ||= B
A= $self->{"logdir"}B= $dir
ABresult
1X1
011
000
1855  
1856 10 return $dir;
1857 }
1858  
1859 =head2 is_robot
1860  
1861 Is the visitor a real person or a robot?
1862  
1863 use CGI::Info;
1864  
1865 my $info = CGI::Info->new();
1866 unless($info->is_robot()) {
1867 # update site visitor statistics
1868 }
1869  
1870 If the client is seen to be attempting an SQL injection,
1871 set the HTTP status to 403,
1872 and return 1.
1873  
1874 =cut
1875  
1876 101 ▶sub is_robot {
Subroutine is_robot: called CC=31 SCAR=34.6
Pod documented
1877 101 my $self = shift;
1878  
1879 101 ▶ if(defined($self->{is_robot})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"is_robot"}) 31 70 101
1880 31 return $self->{is_robot};
1881 }
1882  
1883 70 my $agent = $ENV{'HTTP_USER_AGENT'};
1884 70 my $remote = $ENV{'REMOTE_ADDR'};
1885  
1886 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
1887 # Probably not running in CGI - assume real person
1888 10 return 0;
1889 }
1890  
1891 # SQL injection check MUST run before is_ai(): a WAF block must never be
1892 # bypassed just because the UA also identifies itself as an AI crawler.
1893 # See also params() — patterns here MUST stay in sync with those in params().
1894 # Bounded-lazy .{1,N}? replaces unbounded .+ to prevent O(n²/n³) backtracking
1895 # on long UAs that contain SQL keywords but not the complete injection sequence.
1896 # \b word boundaries prevent false positives on tokens like "SELECTFOO".
1897 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
1898 ($agent =~ /\bORDER\s+BY\b/i) ||
1899 ($agent =~ /\bOR\s+NOT\b/i) ||
1900 ($agent =~ /\bAND\b\s+\d+=\d+/) ||
1901 ($agent =~ /\bTHEN\b.{1,300}?\bELSE\b.{1,300}?\bEND\b/i) ||
1902 ($agent =~ /\bAND\b.{1,500}?\bSELECT\b/i) ||
1903 ($agent =~ /\sAND\s.{1,500}?\sAND\s/)) {
1904 11 $self->status(403);
1905 11 $self->{is_robot} = 1;
1906 11 ▶ if($ENV{'REMOTE_ADDR'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{'REMOTE_ADDR'}) { } 11 0 11
1907 11 $self->_warn($ENV{'REMOTE_ADDR'} . ": SQL injection attempt blocked for '$agent'");
1908 } else {
1909 0 $self->_warn("SQL injection attempt blocked for '$agent'");
1910 }
1911 11 return 1;
1912 }
1913  
1914 # is_ai implies is_robot: check AI crawlers before the generic bot regex so
1915 # that UAs like ChatGPT-User or Google-Extended (no "bot"/"spider" token)
1916 # are still caught here.
1917 49 ▶ if($self->is_ai()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_ai) 8 41 49
1918 8 return $self->{is_robot} = 1;
1919 }
1920 # '.+bot' was replaced with '\bbot\b' — the leading .+ caused catastrophic
1921 # backtracking on long UAs that contain no 'bot' substring.
1922 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
1923 8 $self->{is_robot} = 1;
1924 8 return 1;
1925 }
1926  
1927 # TODO:
1928 # Download and use list from
1929 # https://raw.githubusercontent.com/mitchellkrogza/apache-ultimate-bad-bot-blocker/refs/heads/master/_generator_lists/bad-user-agents.list
1930  
1931 33 my $key = "$remote/$agent";
1932  
1933 # Check the shared cache BEFORE the referrer scan: the 29-domain referrer
1934 # check is the most expensive path in is_robot() and is unnecessary when a
1935 # prior request already classified this remote/agent pair.
1936 # The SQL injection check above MUST remain before this (security gate).
1937 33 ▶ if($self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"}) 6 27 33
1938 6 ▶ if(my $type = $self->{cache}->get($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $type = $self->{"cache"}->get($key)) 3 3 6
1939 3 return $self->{is_robot} = ($type eq 'robot');
1940 }
1941 }
1942  
1943 30 ▶ if(my $referrer = $ENV{'HTTP_REFERER'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $referrer = $ENV{"HTTP_REFERER"}) 9 21 30
1944 # $CRAWLER_REFERER_RE is compiled once at module load (see top of file):
1945 # replaces List::Util::any { /^\Q$_\E/i } @crawler_lists (29 per-call
1946 # regex compilations + array allocation eliminated).
1947 9 $referrer =~ s/\\/_/g;
1948 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
1949 8 $self->_debug("is_robot: blocked trawler $referrer");
1950 8 ▶ if($self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"}) 1 7 8
1951 1 $self->{cache}->set($key, 'robot', $CACHE_TTL_ROBOT);
1952 }
1953 8 $self->{is_robot} = 1;
1954 8 return 1;
1955 }
1956 }
1957  
1958 # Don't use HTTP_USER_AGENT to detect more than we really have to since
1959 # that is easily spoofed
1960 22 ▶ if($agent =~ /www\.majestic12\.co\.uk|facebookexternal/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($agent =~ /www\.majestic12\.co\.uk|facebookexternal/) 1 21 22
1961 # Mark Facebook as a search engine, not a robot
1962 1 ▶ if($self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"}) 0 1 1
1963 0 $self->{cache}->set($key, 'search', $CACHE_TTL_SEARCH);
1964 }
1965 1 return 0;
1966 }
1967  
1968 21 ▶ unless($self->{browser_detect}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"browser_detect"}) 10 11 21
1969 10 ▶ if(eval { require HTTP::BrowserDetect; }) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { require HTTP::BrowserDetect } }) 10 0 10
1970 10 HTTP::BrowserDetect->import();
1971 10 $self->{browser_detect} = HTTP::BrowserDetect->new($agent);
1972 }
1973 }
1974 21 ▶ if($self->{browser_detect}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"browser_detect"}) 21 0 21
1975 21 my $is_robot = $self->{browser_detect}->robot();
1976 21 ▶ if(defined($is_robot)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $is_robot) 5 16 21
1977 5 $self->_debug("HTTP::BrowserDetect '$ENV{HTTP_USER_AGENT}' returns $is_robot");
1978 }
1979 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
1980 21 $self->_debug("is_robot: $is_robot");
1981  
1982 21 ▶ if($is_robot) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_robot) 5 16 21
1983 5 ▶ if($self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"}) 1 4 5
1984 1 $self->{cache}->set($key, 'robot', $CACHE_TTL_ROBOT);
1985 }
1986 5 $self->{is_robot} = $is_robot;
1987 5 return $is_robot;
1988 }
1989 }
1990  
1991 16 ▶ if($self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"}) 1 15 16
1992 1 $self->{cache}->set($key, 'unknown', $CACHE_TTL_ROBOT);
1993 }
1994 16 $self->{is_robot} = 0;
1995 16 return 0;
1996 }
1997  
1998 =head2 is_search_engine
1999  
2000 Is the visitor a search engine?
2001  
2002 if(CGI::Info->new()->is_search_engine()) {
2003 # display generic information about yourself
2004 } else {
2005 # allow the user to pick and choose something to display
2006 }
2007  
2008 Can be overridden by the IS_SEARCH_ENGINE environment setting
2009  
2010 =cut
2011  
2012 sub is_search_engine
2013 67 ▶{
Subroutine is_search_engine: called CC=30 SCAR=41.9
Pod documented
2014 67 my $self = shift;
2015  
2016 67 ▶ if(defined($self->{is_search_engine})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"is_search_engine"}) 11 56 67
2017 11 return $self->{is_search_engine};
2018 }
2019  
2020 56 ▶ if($ENV{'IS_SEARCH_ENGINE'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{"IS_SEARCH_ENGINE"}) 5 51 56
2021 5 return $ENV{'IS_SEARCH_ENGINE'}
2022 }
2023  
2024 51 my $remote = $ENV{'REMOTE_ADDR'};
2025 51 my $agent = $ENV{'HTTP_USER_AGENT'};
2026  
2027 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
2028 # Probably not running in CGI - assume not a search engine
2029 13 return 0;
2030 }
2031  
2032 # Build the cache key once; reuse $key for every subsequent set() call.
2033 38 my $key = "$remote/$agent";
2034  
2035 38 ▶ if($self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"}) 3 35 38
2036 3 ▶ if(my $type = $self->{cache}->get($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $type = $self->{"cache"}->get($key)) 1 2 3
2037 # Write to is_search_engine (not the old is_search typo) so the
2038 # instance-level guard at the top of this method actually fires on
2039 # the next call, avoiding a redundant shared-cache round-trip.
2040 1 return $self->{is_search_engine} = ($type eq 'search');
2041 }
2042 }
2043  
2044 # Don't use HTTP_USER_AGENT to detect more than we really have to since
2045 # that is easily spoofed
2046 37 ▶ if($agent =~ /www\.majestic12\.co\.uk|facebookexternal/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($agent =~ /www\.majestic12\.co\.uk|facebookexternal/) 3 34 37
2047 # Mark Facebook as a search engine, not a robot
2048 3 ▶ if($self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"}) 0 3 3
2049 0 $self->{cache}->set($key, 'search', $CACHE_TTL_SEARCH);
2050 }
2051 3 return 1;
2052 }
2053  
2054 34 ▶ unless($self->{browser_detect}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"browser_detect"}) 16 18 34
2055 16 ▶ if(eval { require HTTP::BrowserDetect; }) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { require HTTP::BrowserDetect } }) 16 0 16
2056 16 HTTP::BrowserDetect->import();
2057 16 $self->{browser_detect} = HTTP::BrowserDetect->new($agent);
2058 }
2059 }
2060 34 ▶ if(my $browser = $self->{browser_detect}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $browser = $self->{"browser_detect"}) 34 0 34
2061 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
2062 34 ▶ if(!$is_search) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($is_search) 24 10 34
2063 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
2064 ($agent =~ /Google-InspectionTool\//) ||
2065 ($agent =~ /Googlebot\//)) {
2066 3 $is_search = 1;
2067 }
2068 }
2069 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
2070 1 $self->{cache}->set($key, 'search', $CACHE_TTL_SEARCH);
2071 }
2072 34 return $self->{is_search_engine} = $is_search;
2073 }
2074  
2075 # Untaint $remote before passing to inet_aton: under -T, tainted data
2076 # causes a fatal "Insecure dependency" in inet_aton. The strict IPv4
2077 # regex also rejects any non-address garbage that could reach this path.
2078 0 my ($safe_remote) = $remote =~ /^(\d{1,3}(?:\.\d{1,3}){3})$/;
2079 0 ▶ unless(defined $safe_remote) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $safe_remote) 0 0 0
2080 0 $self->{is_search_engine} = 0;
2081 0 return 0;
2082 }
2083 # TODO: DNS lookup, not gethostbyaddr - though that will be slow
2084 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
2085  
2086 0 my @cidr_blocks = ('47.235.0.0/12'); # Alibaba
2087  
2088 # \b word boundaries prevent false positives like "notgoogle.example.com".
2089 # /i because DNS hostnames are case-insensitive.
2090 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
2091 (Net::CIDR::cidrlookup($remote, @cidr_blocks))) {
2092 0 ▶ if($self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"}) 0 0 0
2093 0 $self->{cache}->set($key, 'search', $CACHE_TTL_SEARCH);
2094 }
2095 0 $self->{is_search_engine} = 1;
2096 0 return 1;
2097 }
2098  
2099 0 $self->{is_search_engine} = 0;
2100 0 return 0;
2101 }
2102  
2103 =head2 is_ai
2104  
2105 Returns a boolean indicating whether the visitor is a known AI training or
2106 inference crawler (e.g. GPTBot, ClaudeBot, PerplexityBot).
2107  
2108 Use this to withhold training data, serve an opt-out notice, or log AI traffic
2109 separately from regular robot traffic.
2110  
2111 B<Invariant>: when C<is_ai()> returns true, C<is_robot()> also returns true,
2112 regardless of the order in which the two methods are called.
2113  
2114 Can be overridden by the C<IS_AI> environment variable.
2115  
2116 =head3 EXAMPLE
2117  
2118 use CGI::Info;
2119  
2120 my $info = CGI::Info->new();
2121 if ($info->is_ai()) {
2122 # Decline to serve training data to AI scrapers
2123 print "Status: 403 Forbidden\r\n\r\n";
2124 exit;
2125 }
2126  
2127 # Route AI crawlers to a lightweight page instead of blocking them
2128 if ($info->is_ai()) {
2129 serve_ai_summary();
2130 } else {
2131 serve_full_page();
2132 }
2133  
2134 =head3 API SPECIFICATION
2135  
2136 =head4 Input
2137  
2138 No arguments beyond the implicit object reference (C<$self>).
2139  
2140 # Params::Validate::Strict schema -- no parameters
2141 {}
2142  
2143 =head4 Output
2144  
2145 # Return::Set schema
2146 {
2147 type => SCALAR,
2148 values => [ 0, 1 ],
2149 }
2150  
2151 Returns C<1> if the visiting client is identified as an AI training or
2152 inference crawler; C<0> otherwise.
2153  
2154 =head3 MESSAGES
2155  
2156 This method produces no log messages of its own. Upstream callers such as
2157 C<is_robot()> may emit WAF warnings; see L</is_robot> for that table.
2158  
2159 =head3 PSEUDOCODE
2160  
2161 function is_ai(self):
2162 if self.{is_ai} is defined:
2163 return self.{is_ai} # instance-level cache
2164  
2165 if IS_AI environment variable is set:
2166 return self.{is_ai} = IS_AI ? 1 : 0 # override; no robot sync needed
2167 # because is_robot() calls is_ai()
2168  
2169 ua = HTTP_USER_AGENT
2170 remote = REMOTE_ADDR
2171  
2172 if not (remote and ua):
2173 return 0 # not a CGI request; assume human
2174  
2175 if ua matches any AI_PAT token (case-insensitive):
2176 self.{is_robot} = 1 # enforce is_ai => is_robot
2177 return self.{is_ai} = 1
2178  
2179 return self.{is_ai} = 0
2180  
2181 =cut
2182  
2183 164 ▶sub is_ai {
Subroutine is_ai: called CC=7 SCAR=19.5
Pod documented
2184 164 my $self = shift;
2185  
2186 # Return cached result if already determined
2187 164 ▶ if(defined($self->{is_ai})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"is_ai"}) 40 124 164
2188 40 return $self->{is_ai};
2189 }
2190  
2191 # Allow environment variable override for testing or manual classification
2192 124 ▶ if(defined(my $override = $ENV{'IS_AI'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $override = $ENV{"IS_AI"})) 14 110 124
2193 14 ▶ return $self->{is_ai} = $override ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$override ? : 9 5 14
2194 }
2195  
2196 110 my $agent = $ENV{'HTTP_USER_AGENT'};
2197 110 my $remote = $ENV{'REMOTE_ADDR'};
2198  
2199 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
2200 # Probably not running in CGI - assume not an AI crawler
2201 15 return 0;
2202 }
2203  
2204 # Known AI training and inference crawlers, matched against the User-Agent.
2205 # We intentionally do not consult the shared IP/agent cache here: is_robot()
2206 # stores 'robot' for many of the same UAs, and reading 'robot' != 'ai' would
2207 # produce a false negative. Instance-level caching ($self->{is_ai}) above is
2208 # sufficient to avoid redundant regex evaluation within a single request.
2209 # Sources: vendor documentation and public bot lists.
2210 # Anthropic: ClaudeBot, Claude-Web, anthropic-ai
2211 # OpenAI: GPTBot, ChatGPT-User, OAI-SearchBot
2212 # Google: Google-Extended (AI training opt-out token)
2213 # Meta: meta-externalagent, FacebookBot (AI training)
2214 # Apple: Applebot-Extended (AI training subset)
2215 # Perplexity: PerplexityBot
2216 # Amazon: Amazonbot (Amazon AI / Alexa AI)
2217 # You.com: YouBot
2218 # Diffbot: Diffbot
2219 # Cohere: cohere-ai
2220 # Common Crawl: CCBot (primary data source for many LLM trainers)
2221 # ByteDance: Bytespider (TikTok / AI training)
2222 # Allen AI: AI2Bot
2223 # Timpi: TimpiBot
2224 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
2225 # Enforce is_ai => is_robot so callers need not check both
2226 45 $self->{is_robot} = 1;
2227 45 return $self->{is_ai} = 1;
2228 }
2229  
2230 50 $self->{is_ai} = 0;
2231 50 return 0;
2232 }
2233  
2234 =head2 browser_type
2235  
2236 Returns a string classifying the visitor's client. The possible values are:
2237  
2238 =over 4
2239  
2240 =item * C<'mobile'> -- smartphone or tablet (checked first)
2241  
2242 =item * C<'ai'> -- known AI training or inference crawler (see L</is_ai>)
2243  
2244 =item * C<'search'> -- search-engine crawler
2245  
2246 =item * C<'robot'> -- other automated client
2247  
2248 =item * C<'web'> -- ordinary desktop or laptop browser
2249  
2250 =back
2251  
2252 use Carp;
2253 use Template;
2254 use CGI::Info;
2255  
2256 my $info = CGI::Info->new();
2257 my $dir = $info->rootdir() . '/templates/' . $info->browser_type();
2258  
2259 my $filename = ref($info);
2260 $filename =~ s/::/\//g;
2261 $filename = "$dir/$filename.tmpl";
2262  
2263 (-f $filename && -r $filename)
2264 or croak "Cannot open template '$filename'";
2265  
2266 my $template = Template->new();
2267 $template->process($filename, {}) or croak $template->error();
2268  
2269 =cut
2270  
2271 56 ▶sub browser_type {
Subroutine browser_type: called CC=5 SCAR=16.1
Pod documented
2272 56 my $self = shift;
2273  
2274 56 ▶ if($self->is_mobile()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_mobile) 16 40 56
2275 16 return 'mobile';
2276 }
2277 40 ▶ if($self->is_ai()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_ai) 11 29 40
2278 11 return 'ai';
2279 }
2280 29 ▶ if($self->is_search_engine()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_search_engine) 9 20 29
2281 9 return 'search';
2282 }
2283 20 ▶ if($self->is_robot()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_robot) 7 13 20
2284 7 return 'robot';
2285 }
2286 13 return 'web';
2287 }
2288  
2289 =head2 get_cookie
2290  
2291 Returns a cookie's value, or undef if no name is given, or the requested
2292 cookie isn't in the jar.
2293  
2294 Deprecated - use cookie() instead.
2295  
2296 use CGI::Info;
2297  
2298 my $i = CGI::Info->new();
2299 my $name = $i->get_cookie(cookie_name => 'name');
2300 print "Your name is $name\n";
2301 my $address = $i->get_cookie('address');
2302 print "Your address is $address\n";
2303  
2304 =cut
2305  
2306 17 ▶sub get_cookie {
Subroutine get_cookie: called CC=1 SCAR=0.0
Pod documented
2307 17 my $self = shift;
2308  
2309 17 return $self->cookie(\@_);
2310 }
2311  
2312 =head2 cookie
2313  
2314 Returns a cookie's value, or undef if no name is given, or the requested
2315 cookie isn't in the jar.
2316 API is the same as "param",
2317 it will replace the "get_cookie" method in the future.
2318  
2319 use CGI::Info;
2320  
2321 my $name = CGI::Info->new()->cookie('name');
2322 print "Your name is $name\n";
2323  
2324  
2325 =head3 API SPECIFICATION
2326  
2327 =head4 INPUT
2328  
2329 {
2330 cookie_name => {
2331 'type' => 'string',
2332 'min' => 1,
2333 'matches' => qr/^[!#-'*+\-.\^_`|~0-9A-Za-z]+$/ # RFC6265
2334 }
2335 }
2336  
2337 =head4 OUTPUT
2338  
2339 Cookie not set: C<undef>
2340  
2341 Cookie set:
2342  
2343 {
2344 type => 'string',
2345 optional => 1,
2346 matches => qr/ # RFC6265
2347 ^
2348 (?:
2349 "[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*" # quoted
2350 | [\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]* # unquoted
2351 )
2352 $
2353 /x
2354 }
2355  
2356 =cut
2357  
2358 sub cookie
2359 72 ▶{
Subroutine cookie: called CC=5 SCAR=17.5
Pod documented
2360 72 my $self = shift;
2361 72 my $params = Params::Validate::Strict::validate_strict({
2362 args => Params::Get::get_params('cookie_name', @_),
2363 schema => {
2364 cookie_name => {
2365 'type' => 'string',
2366 'min' => 1,
2367 'matches' => qr/^[!#-'*+\-.\^_`|~0-9A-Za-z]+$/ # RFC6265
2368 }
2369 }
2370 });
2371  
2372 66 my $field = $params->{'cookie_name'};
2373  
2374 # TODO: Unreachable code detected during path analysis. Investigate for removal.
2375 # validate_strict() above enforces type=>string, min=>1 and croaks for undef/ref
2376 # inputs before control ever reaches these two guards.
2377 66 ▶ if(!defined($field)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $field) 0 66 66
2378 0 $self->_error('what cookie do you want?');
2379 0 Carp::croak('what cookie do you want?');
2380 0 return; # TODO: Unreachable code detected during path analysis. Investigate for removal.
2381 }
2382 66 ▶ if(ref($field)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $field) 0 66 66
2383 0 $self->_error('Cookie name should be a string');
2384 0 Carp::croak('Cookie name should be a string');
2385 0 return; # TODO: Unreachable code detected during path analysis. Investigate for removal.
2386 }
2387  
2388 # Load cookies if not already loaded
2389 66 ▶ unless($self->{jar}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"jar"}) 41 25 66
2390 41 ▶ if(defined $ENV{'HTTP_COOKIE'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ENV{"HTTP_COOKIE"}) 36 5 41
2391 # Truncate at the first CR or LF before parsing.
2392 # HTTP header values cannot span lines; anything after a newline is
2393 # injected content (e.g. "session=abc\r\nSet-Cookie: admin=1").
2394 # Stripping rather than truncating would leave the injected text
2395 # concatenated onto a legitimate value, so we discard from \r/\n onward.
2396 36 (my $raw_cookie = $ENV{'HTTP_COOKIE'}) =~ s/[\r\n].*$//s;
2397  
2398 # grep { /=/ } filters out malformed tokens (empty strings, bare
2399 # semicolons, entries with no name=value separator) that would
2400 # otherwise cause split(/=/, $_, 2) to return a single-element list
2401 # and make the flattened list odd-length, corrupting the hash.
2402 $self->{jar} = {
2403 62 map { split(/=/, $_, 2) }
2404 36 grep { /=/ }
2405 split(/; /, $raw_cookie)
2406 };
2407 }
2408 }
2409  
2410 # Return the cookie value if it exists, otherwise return undef
2411 66 return $self->{jar}{$field};
2412 }
2413  
2414 =head2 status($status)
2415  
2416 Sets or returns the status of the object,
2417 200 for OK,
2418 otherwise an HTTP error code
2419  
2420 =over 4
2421  
2422 =item $status
2423  
2424 Optional integer value to be set or retrieved.
2425 If omitted, the value is retrieved.
2426  
2427 =back
2428  
2429 =cut
2430  
2431 sub status
2432 395 ▶{
Subroutine status: called CC=10 SCAR=23.0
Pod documented
2433 395 my $self = shift;
2434 395 my $status = shift;
2435  
2436 # Set status if provided
2437 395 ▶ return $self->{status} = $status if(defined($status));
Branch: 1 branch
BranchTrueFalseTotal
if defined $status 202 193 395
2438  
2439 # Determine status based on request method if status is not set
2440 193 ▶ unless (defined $self->{status}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"status"}) 45 148 193
2441 45 my $method = $ENV{'REQUEST_METHOD'};
2442  
2443 45 ▶ return 405 if $method && ($method eq 'OPTIONS' || $method eq 'DELETE');
Branch: 1 branch
BranchTrueFalseTotal
if $method and $method eq "OPTIONS" || $method eq "DELETE" 6 39 45
Condition100%6/6
$method and $method eq "OPTIONS" || $method eq "DELETE"
!ll&&!rl&&r
8316
$method eq "OPTIONS" or $method eq "DELETE"
l!l&&r!l&&!r
3331
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
2444 39 ▶ 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 35 39
Condition100%6/6
$method and ($method eq "POST" and not defined $ENV{"CONTENT_LENGTH"})
!ll&&!rl&&r
8274
$method eq "POST" and not defined $ENV{"CONTENT_LENGTH"}
!ll&&!rl&&r
2344
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
2445  
2446 35 return 200;
2447 }
2448  
2449 # Return current status or 200 by default
2450 148 ▶ return $self->{status} || 200;
Condition100%2/2
$self->{'status'} || 200
l!l
1453
MC/DC100%1/1
$self->{'status'} || 200
$self->{'status'}
Truth table100%2/2
A
A= $self->{'status'}
Aresult
11
00
2451 }
2452  
2453 =head2 messages
2454  
2455 Returns the messages that the object has generated as a ref to an array of hashes.
2456  
2457 my @messages;
2458 if(my $w = $info->messages()) {
2459 @messages = map { $_->{'message'} } @{$w};
2460 } else {
2461 @messages = ();
2462 }
2463 print STDERR join(';', @messages), "\n";
2464  
2465 =cut
2466  
2467 sub messages
2468 48 ▶{
Subroutine messages: called CC=1 SCAR=0.0
Pod documented
2469 48 my $self = shift;
2470  
2471 48 return $self->{'messages'};
2472 }
2473  
2474 =head2 messages_as_string
2475  
2476 Returns the messages of that the object has generated as a string.
2477  
2478 =cut
2479  
2480 sub messages_as_string
2481 9 ▶{
Subroutine messages_as_string: called CC=2 SCAR=6.9
Pod documented
2482 9 my $self = shift;
2483  
2484 9 ▶ if(scalar($self->{'messages'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar $self->{"messages"}) 5 4 9
2485 5 my @messages = map { $_->{'message'} } @{$self->{'messages'}};
2486 5 return join('; ', @messages);
2487 }
2488 4 return '';
2489 }
2490  
2491 =head2 cache($cache)
2492  
2493 Get/set the internal cache system.
2494  
2495 Use this rather than pass the cache argument to C<new()> if you see these error messages,
2496 "(in cleanup) Failed to get MD5_CTX pointer".
2497 It's some obscure problem that I can't work out,
2498 but calling this after C<new()> works.
2499  
2500 =over 4
2501  
2502 =item $cache
2503  
2504 Optional cache object.
2505 When not given,
2506 returns the current cache object.
2507  
2508 =back
2509  
2510 =cut
2511  
2512 sub cache
2513 29 ▶{
Subroutine cache: called CC=5 SCAR=16.1
Pod documented
2514 29 my $self = shift;
2515 29 my $cache = shift;
2516  
2517 29 ▶ if($cache) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cache) 19 10 29
2518 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
2519 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
2520 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
2521 10 $self->{'cache'} = $cache;
2522 }
2523 20 return $self->{'cache'};
2524 }
2525  
2526 =head2 set_logger
2527  
2528 Sets the class, array, code reference, or file that will be used for logging.
2529  
2530 Sometimes you don't know what the logger is until you've instantiated the class.
2531 This function fixes the catch-22 situation.
2532  
2533 =cut
2534  
2535 sub set_logger
2536 17 ▶{
Subroutine set_logger: called CC=3 SCAR=11.0
Pod documented
2537 17 my $self = shift;
2538 17 my $params = Params::Get::get_params('logger', @_);
2539  
2540 17 ▶ if(my $logger = $params->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $logger = $params->{'logger'}) { } 15 2 17
2541 15 ▶ if(Scalar::Util::blessed($logger)) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($logger)) { } 10 5 15
2542 10 $self->{'logger'} = $logger;
2543 } else {
2544 5 $self->{'logger'} = Log::Abstraction->new($logger);
2545 }
2546 } else {
2547 2 $self->{'logger'} = Log::Abstraction->new();
2548 }
2549 17 return $self;
2550 }
2551  
2552 # Log and remember a message
2553 2838 ▶sub _log :Protected {
Subroutine _log: called CC=3 SCAR=11.0
2554 2838 my ($self, $level, @messages) = @_;
2555  
2556 # Filter once; reuse for both the in-memory store and the logger call.
2557 # The former inner scalar(@messages) guard was always true inside this block.
2558 2838 my @defined_msgs = grep { defined } @messages;
2559 2838 ▶ return unless @defined_msgs;
Branch: 1 branch
BranchTrueFalseTotal
unless @defined_msgs 2 2836 2838
2560  
2561 # Note: consider adding caller's function name to log messages in a future release
2562 2836 push @{$self->{'messages'}}, { level => $level, message => join(' ', @defined_msgs) };
2563  
2564 2836 ▶ if(my $logger = $self->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $logger = $self->{"logger"}) 2830 6 2836
2565 2830 $logger->$level(join('', @defined_msgs));
2566 }
2567 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2568  
2569 1893 ▶sub _debug :Protected {
Subroutine _debug: called CC=1 SCAR=0.0
2570 1893 my $self = shift;
2571 1893 $self->_log('debug', @_);
2572 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2573  
2574 87 ▶sub _info :Protected {
Subroutine _info: called CC=1 SCAR=0.0
2575 87 my $self = shift;
2576 87 $self->_log('info', @_);
2577 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2578  
2579 1 ▶sub _notice :Protected {
Subroutine _notice: called CC=1 SCAR=0.0
2580 1 my $self = shift;
2581 1 $self->_log('notice', @_);
2582 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2583  
2584 671 ▶sub _trace :Protected {
Subroutine _trace: called CC=1 SCAR=0.0
2585 671 my $self = shift;
2586 671 $self->_log('trace', @_);
2587 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2588  
2589 # Emit a warning message somewhere
2590 175 ▶sub _warn :Protected {
Subroutine _warn: called CC=2 SCAR=6.9
2591 175 my $self = shift;
2592 175 my $params = Params::Get::get_params('warning', @_);
2593  
2594 175 $self->_log('warn', $params->{'warning'});
2595 160 ▶ if(!defined($self->{'logger'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $self->{"logger"}) 3 157 160
2596 3 Carp::carp($params->{'warning'});
2597 }
2598 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2599  
2600 # Emit an error message somewhere
2601 4 ▶sub _error :Protected {
Subroutine _error: called CC=2 SCAR=6.9
2602 4 my $self = shift;
2603 4 my $params = Params::Get::get_params('warning', @_);
2604  
2605 4 $self->_log('error', $params->{'warning'});
2606 4 ▶ if(!defined($self->{'logger'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $self->{"logger"}) 2 2 4
2607 2 Carp::croak($params->{'warning'});
2608 }
2609 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2610  
2611 # Ensure all environment variables are sanitized and validated before use.
2612 # Use regular expressions to enforce strict input formats.
2613 237 ▶sub _get_env :Protected {
Subroutine _get_env: called CC=3 SCAR=11.0
2614 237 my ($self, $var) = @_;
2615  
2616 237 ▶ return unless defined $ENV{$var};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ENV{$var} 89 148 237
2617  
2618 # Strict sanitization: allow alphanumeric and limited special characters
2619 148 ▶ if($ENV{$var} =~ /^[\w\.\-\/:\\]+$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{$var} =~ m(^[\w\.\-/:\\]+$)) 142 6 148
2620 142 return $ENV{$var};
2621 }
2622 6 $self->_warn("Invalid value in environment variable: $var");
2623  
2624 6 return;
2625 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2626  
2627 =head2 reset
2628  
2629 Class method to reset the class.
2630 You should do this in an FCGI environment before instantiating,
2631 but nowhere else.
2632  
2633 =cut
2634  
2635 664 ▶sub reset {
Subroutine reset: called CC=2 SCAR=6.9
Pod documented
2636 664 my $class = shift;
2637  
2638 664 ▶ unless($class eq __PACKAGE__) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($class eq __PACKAGE__) 4 660 664
2639 4 carp('Reset is a class method');
2640 3 return;
2641 }
2642  
2643 660 $stdin_data = undef;
2644 }
2645  
2646 sub AUTOLOAD
2647 1021 ▶{
Subroutine AUTOLOAD: called CC=10 SCAR=24.2
2648 1021 our $AUTOLOAD;
2649  
2650 1021 ▶ my $self = shift or return;
Branch: 1 branch
BranchTrueFalseTotal
my $self = shift() or return 1021 0 1021
2651  
2652 1021 ▶ return if(!defined($AUTOLOAD));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $CGI::Info::AUTOLOAD 0 1021 1021
2653  
2654 # Extract the method name from the AUTOLOAD variable
2655 1021 my ($method) = $AUTOLOAD =~ /::(\w+)$/;
2656  
2657 # Skip if called on destruction
2658 1021 ▶ return if($method eq 'DESTROY');
Branch: 1 branch
BranchTrueFalseTotal
if $method eq "DESTROY" 996 25 1021
2659  
2660 25 ▶ Carp::croak(__PACKAGE__, ": Unknown method $method") if(!ref($self));
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self 1 24 25
2661  
2662 # Allow the AUTOLOAD feature to be disabled
2663 24 ▶ Carp::croak(__PACKAGE__, ": Unknown method $method") if(exists($self->{'auto_load'}) && boolean($self->{'auto_load'})->isFalse());
Branch: 1 branch
BranchTrueFalseTotal
if exists $self->{"auto_load"} and &boolean($self->{"auto_load"})->isFalse 5 19 24
Condition66%2/3
exists $self->{"auto_load"} and &boolean($self->{"auto_load"})->isFalse
!ll&&!rl&&r
1905
MC/DC50%1/2
exists $self->{"auto_load"} and &boolean($self->{"auto_load"})->isFalse
exists $self->{"auto_load"} &boolean($self->{"auto_load"})->isFalse
Truth table66%2/3
A and B
A= exists $self->{"auto_load"}B= &boolean($self->{"auto_load"})->isFalse
ABresult
0X0
100
111
2664  
2665 # Ensure the method is called on the correct package object or a subclass
2666 19 ▶ return unless((ref($self) eq __PACKAGE__) || (UNIVERSAL::isa((caller)[0], __PACKAGE__)));
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self eq __PACKAGE__ or UNIVERSAL::isa((&CORE::GLOBAL::caller())[0], __PACKAGE__) 0 19 19
Condition33%1/3
ref $self eq __PACKAGE__ or UNIVERSAL::isa((&CORE::GLOBAL::caller())[0], __PACKAGE__)
l!l&&r!l&&!r
1900
MC/DC0%0/2
ref $self eq __PACKAGE__ or UNIVERSAL::isa((&CORE::GLOBAL::caller())[0], __PACKAGE__)
ref $self eq __PACKAGE__ UNIVERSAL::isa((&CORE::GLOBAL::caller())[0], __PACKAGE__)
Truth table33%1/3
A or B
A= ref $self eq __PACKAGE__B= UNIVERSAL::isa((&CORE::GLOBAL::caller())[0], __PACKAGE__)
ABresult
1X1
011
000
2667  
2668 # TODO: Unreachable code detected during path analysis. Investigate for removal.
2669 # $method is captured via /::(\w+)$/ which only yields \w+ chars; a digit-leading
2670 # name is possible in theory but Perl's method dispatch never generates one.
2671 19 ▶ Carp::croak(__PACKAGE__, ": Invalid method name: $method") unless $method =~ /^[a-zA-Z_][a-zA-Z0-9_]*$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $method =~ /^[a-zA-Z_][a-zA-Z0-9_]*$/ 0 19 19
2672  
2673 # Delegate to the param method
2674 19 return $self->param($method);
2675 }
2676  
2677 =head1 BUGS
2678  
2679 is_tablet() only currently detects the iPad and Windows PCs. Android strings
2680 don't differ between tablets and smartphones.
2681  
2682 params() returns a ref which means that calling routines can change the hash
2683 for other routines.
2684 Take a local copy before making amendments to the table if you don't want unexpected
2685 things to happen.
2686  
2687 =head1 SEE ALSO
2688  
2689 =over 4
2690  
2691 =item * L<Configure an Object at Runtime|Object::Configure>
2692  
2693 =item * L<Test Dashboard|https://nigelhorne.github.io/CGI-Info/coverage/>
2694  
2695 =item * L<HTTP::BrowserDetect>
2696  
2697 =item * L<https://github.com/mitchellkrogza/apache-ultimate-bad-bot-blocker>
2698  
2699 =back
2700  
2701 =head1 REPOSITORY
2702  
2703 L<https://github.com/nigelhorne/CGI-Info>
2704  
2705 =head1 SUPPORT
2706  
2707 This module is provided as-is without any warranty.
2708  
2709 Please report any bugs or feature requests to C<bug-cgi-info at rt.cpan.org>,
2710 or through the web interface at
2711 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=CGI-Info>.
2712 I will be notified, and then you'll
2713 automatically be notified of progress on your bug as I make changes.
2714  
2715 You can find documentation for this module with the perldoc command.
2716  
2717 perldoc CGI::Info
2718  
2719 You can also look for information at:
2720  
2721 =over 4
2722  
2723 =item * MetaCPAN
2724  
2725 L<https://metacpan.org/dist/CGI-Info>
2726  
2727 =item * RT: CPAN's request tracker
2728  
2729 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=CGI-Info>
2730  
2731 =item * CPAN Testers' Matrix
2732  
2733 L<http://matrix.cpantesters.org/?dist=CGI-Info>
2734  
2735 =item * CPAN Testers Dependencies
2736  
2737 L<http://deps.cpantesters.org/?module=CGI::Info>
2738  
2739 =back
2740  
2741 =encoding utf-8
2742  
2743 =head2 FORMAL SPECIFICATION
2744  
2745 =head3 new
2746  
2747 -- CGI::Info construction
2748 new : ClassName x Params --> CGIInfo
2749  
2750 -- Normal (non-clone) path
2751 new(class, params) ^=
2752 let configured == Object::Configure::configure(class, params)
2753 in CGIInfo {
2754 max_upload_size |-> configured.max_upload_size ?? MAX_UPLOAD_SIZE_DEFAULT,
2755 allow |-> configured.allow ?? null,
2756 upload_dir |-> configured.upload_dir ?? null,
2757 ...configured
2758 }
2759  
2760 -- Pre-conditions
2761 pre new(class, params) ^=
2762 params.logger = null
2763 v (blessed(params.logger)
2764 ^ params.logger.can('warn')
2765 ^ params.logger.can('info')
2766 ^ params.logger.can('error'))
2767 ^ params.expect = null
2768  
2769 -- Clone path (invocant is an existing object)
2770 clone : CGIInfo x Params --> CGIInfo
2771 clone(self, params) ^=
2772 let merged == (self (+) params) \ {paramref}
2773 in CGIInfo { ...merged }
2774  
2775 =head3 param
2776  
2777 Let F be the set of all possible CGI field names, V be the set of all
2778 possible (sanitised) scalar values, and allow : F -> Regex | undef be the
2779 current allow-list schema (undef means all fields are permitted).
2780  
2781 param : F? -> V | HashRef | undef
2782  
2783 param() = params()
2784  
2785 param(f) =
2786 f not in dom(allow) /\ allow /= undef => warn; undef
2787 f in params() => params()(f)
2788 otherwise => undef
2789  
2790 Safety invariant: for all f, param(f) /= undef => f in dom(allow) \/ allow = undef.
2791  
2792 =head2 is_ai
2793  
2794 -- is_ai ---------------------------------------------------------
2795 -- Given CGIInfo state i, returns a boolean result.
2796 --
2797 -- AI_PAT is the set of known AI crawler token strings.
2798 --
2799 -- ENV denotes the process environment (a partial function from
2800 -- name to value).
2801 --
2802 AI_PAT == {ClaudeBot, Claude-Web, anthropic-ai, GPTBot,
2803 ChatGPT-User, OAI-SearchBot, Google-Extended,
2804 meta-externalagent, FacebookBot, Applebot-Extended,
2805 PerplexityBot, Amazonbot, YouBot, Diffbot,
2806 cohere-ai, CCBot, Bytespider, AI2Bot, TimpiBot}
2807  
2808 is_ai ≜ λ i : CGIInfo •
2809 -- Environment override takes absolute priority
2810 IS_AI ∈ dom ENV ⟹
2811 (ENV IS_AI ≠ '0' ∧ ENV IS_AI ≠ '')
2812  
2813 -- Without both IP and UA we cannot classify
2814 ∧ IS_AI ∉ dom ENV ∧
2815 (REMOTE_ADDR ∉ dom ENV ∨ HTTP_USER_AGENT ∉ dom ENV)
2816 ⟹ false
2817  
2818 -- UA-pattern match (case-insensitive substring)
2819 ∧ IS_AI ∉ dom ENV ∧
2820 REMOTE_ADDR ∈ dom ENV ∧ HTTP_USER_AGENT ∈ dom ENV
2821 ⟹ (∃ p : AI_PAT • p ⊑ᵢ ENV HTTP_USER_AGENT)
2822  
2823 -- Invariant: is_ai ⟹ is_robot
2824 ∧ is_ai i = true ⟹ is_robot i = true
2825 -- ---------------------------------------------------------------
2826  
2827 =head1 AUTHOR
2828  
2829 Nigel Horne, C<< <njh at nigelhorne.com> >>
2830  
2831 =head1 LICENCE AND COPYRIGHT
2832  
2833 Copyright 2010-2026 Nigel Horne.
2834  
2835 Usage is subject to the GPL2 licence terms.
2836 If you use it,
2837 please let me know.
2838  
2839 =cut
2840  
2841 37 1;
↑ Summary bin/info.pl »