blib/lib/FCGI/Buffer.pm

filter: Statementstmt 95.0% 1050 / 1105 Branchbran 84.5% 553 / 654 Conditioncond 77.8% 345 / 443 MC/DCmcdc 61.1% 156 / 255 Subroutinesub 100% 78 / 78 Podpod 100% 5 / 5 totaltotal 86.1% 2187 / 2540 CC 497 SCAR 40.6
CC
497
Cov
88%
_send_output
185.4
_rewrite_links
41.2
is_cached
33.0
CRAP 58.2
↑ Summary
1 package FCGI::Buffer;
2  
3 15 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 15 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 # FIXME: save_to treats /cgi-bin/foo.fcgi and /cgi-bin2/foo.fcgi as the same
7  
8 # TODO: Features
9 # TODO: Plack::Middleware::Buffer, to bring this pipeline to PSGI. That's a
10 # better next step than async or Mojolicious routes, neither of which
11 # fit a CGI output filter
12 # TODO: Explicit invalidation: purge(uri), cache tags, and a purge_expired()
13 # for cron so that cleaning up doesn't depend upon page traffic
14 # TODO: A "cacheable" callback so that callers can decide for each response
15 # TODO: Compress more types: JSON, SVG, JS and XML are skipped since only text/*
16 # qualifies. Honour q= priorities, and write precompressed .gz and .br
17 # static copies
18 # TODO: Honour Range requests when a cache is in use, and several ranges
19 # TODO: Honour the Expires header given by the script when caching
20 # TODO: stale-while-revalidate and stale-if-error, to serve an old copy if the
21 # script fails
22 # TODO: Document web server rules so that an expired static link falls back to
23 # the script rather than giving a 404
24 # TODO: save_to: include the full path of the script, which closes the FIXME above
25 # TODO: A metrics hook: hit ratio, bytes saved and the time taken by each stage
26 # TODO: save_to: max_bytes and a parameter allowlist, to go with max_pages
27 # TODO: Detect that a script died part way through its output for all content
28 # types. Only unterminated HTML is detected, see "How the output is sent"
29 #
30 # TODO: Technical debt
31 # TODO: Split up _send_output() with an explicit finish() and named stages:
32 # parse, optimise, validate, cache, encode and emit
33 # TODO: A real header object instead of regular expressions on strings
34 # TODO: An HTML tokenizer instead of the regular expressions in
35 # _optimise_content()
36 # TODO: HTML::Packer takes quadratic time on many unterminated <script> tags,
37 # 2.7 seconds for 400KB. Report it upstream, or replace it with the above
38 # TODO: Harden the SQLite layer: schema versioning and WAL
39 # TODO: Write static pages atomically: write to a temporary file and rename it.
40 # At the moment readers can see a partial page, and neither print nor
41 # close is checked
42 # TODO: Move the RFC references from 7233 to 9110 and 9111, and record deliberate
43 # deviations in the POD
44 # TODO: Remove the version from the X-FCGI-Buffer header's name. It advertises
45 # the exact version to every client, and changes with each release
46  
47 15 ▶use Digest::MD5;
Subroutine BEGIN: called CC=1 SCAR=0.0
48 15 ▶use File::Path;
Subroutine BEGIN: called CC=1 SCAR=0.0
49 15 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
50 15 ▶use IO::String;
Subroutine BEGIN: called CC=1 SCAR=0.0
51 15 ▶use CGI::Info;
Subroutine BEGIN: called CC=1 SCAR=0.0
52 15 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
53 15 ▶use HTTP::Date;
Subroutine BEGIN: called CC=1 SCAR=0.0
54 15 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
55 15 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
56 15 ▶use Scalar::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
57  
58 15 Readonly my $DEFAULT_GENERATE_304 => 1;
59 15 Readonly my $FORM_TOKEN_COOKIE => 'csrf_token';
60 15 Readonly my $DEFAULT_GENERATE_LAST_MODIFIED => 1;
61 15 Readonly my $DEFAULT_COMPRESS_CONTENT => 1;
62 15 Readonly my $DEFAULT_OPTIMISE_CONTENT => 0;
63 15 Readonly my $DEFAULT_LINT_CONTENT => 0;
64 15 Readonly my $MIN_GZIP_LEN => 32;
65 15 Readonly my $DEFAULT_PROTOCOL => 'http';
66 15 Readonly my $DEFAULT_CACHE_DURATION => '10 minutes';
67 15 Readonly my $DEFAULT_SAVE_TO_TTL => 600;
68 15 Readonly my $DEFAULT_SAVE_TO_MAX_PAGES => 10000;
69 15 Readonly my $SAVE_TO_DATABASE => 'fcgi.buffer.sql';
70  
71 # A client's max-age can change how long a page is kept, but not by more than this
72 15 Readonly my $MAX_CLIENT_CACHE_SECONDS => 600;
73  
74 # The protocols that understand ETag, If-None-Match and If-Modified-Since
75 15 Readonly my $CONDITIONAL_PROTOCOL => qr/^HTTP\/(?:1\.1|[23](?:\.0)?)$/;
76  
77 # Cache-Control directives, in a request or a response, which forbid using the
78 # server cache
79 15 Readonly my %NO_CACHE_DIRECTIVES => map { $_ => 1 } qw(no-store no-cache private);
80  
81 # Request methods that are safe to answer from a cache or with a 304
82 15 Readonly my %SAFE_METHODS => map { $_ => 1 } qw(GET HEAD);
83  
84 # The methods that FCGI::Buffer calls on the logger
85 15 Readonly my @LOGGER_METHODS => qw(trace debug info warn error);
86  
87 # An ETag sent with compressed content ends in the name of the encoding
88 15 Readonly my $ENCODED_ETAG_SUFFIX => qr/-(?:gzip|br|zstd)"$/;
89  
90 # Content encodings that we can produce, and the module needed for each
91 15 Readonly my %ENCODING_MODULE => (
92 'gzip' => 'Compress::Zlib',
93 'x-gzip' => 'Compress::Zlib',
94 'br' => 'IO::Compress::Brotli',
95 'zstd' => 'Compress::Zstd',
96 );
97  
98 # Options to init() which can be changed at any time, and are only changed
99 # when a defined value is given
100 15 Readonly my @SAFE_OPTIONS => qw(
101 generate_etag generate_last_modified compress_content optimise_content
102 lint_content logger lingua generate_304
103 );
104  
105 =head1 NAME
106  
107 FCGI::Buffer - Verify, Cache and Optimise FCGI Output
108  
109 =head1 VERSION
110  
111 Version 0.23
112  
113 =cut
114  
115 15 our $VERSION = '0.23';
116  
117 =head1 SYNOPSIS
118  
119 FCGI::Buffer verifies the HTML that you produce by passing it through
120 C<HTML::Lint>.
121  
122 FCGI::Buffer optimises FCGI programs by reducing, filtering and compressing
123 output to speed up the transmission and by nearly seamlessly making use of
124 client and server caches.
125  
126 To make use of client caches, that is to say to reduce needless calls
127 to your server asking for the same data:
128  
129 use FCGI;
130 use FCGI::Buffer;
131 # ...
132 my $request = FCGI::Request();
133 while($request->FCGI::Accept() >= 0) {
134 my $buffer = FCGI::Buffer->new();
135 $buffer->init(
136 optimise_content => 1,
137 lint_content => 0,
138 );
139 # ...
140 }
141  
142 To also make use of server caches, that is to say,
143 to save regenerating output when different clients ask you for the same data,
144 you will need to create a cache.
145 But that's simple:
146  
147 use FCGI;
148 use CHI;
149 use FCGI::Buffer;
150  
151 # ...
152 my $request = FCGI::Request();
153 while($request->FCGI::Accept() >= 0) {
154 my $buffer = FCGI::Buffer->new();
155 $buffer->init(
156 optimise_content => 1,
157 lint_content => 0,
158 cache => CHI->new(driver => 'File')
159 );
160 if($buffer->is_cached()) {
161 # Nothing has changed - use the version in the cache
162 $request->Finish();
163 next;
164 # ...
165 }
166 }
167  
168 To temporarily prevent the use of server-side caches, for example, whilst
169 debugging before publishing a code change, set the NO_CACHE environment variable
170 to any value.
171  
172 =head1 SUBROUTINES/METHODS
173  
174 =cut
175  
176 =head2 new
177  
178 Create an FCGI::Buffer object.
179 Do one of these for each FCGI::Accept.
180  
181 Takes the same options as init(), as a hash or a reference to a hash.
182  
183 =head3 API SPECIFICATION
184  
185 =head4 INPUT
186  
187 {
188 generate_etag => { type => 'boolean', optional => 1 },
189 generate_last_modified => { type => 'boolean', optional => 1 },
190 generate_304 => { type => 'boolean', optional => 1 },
191 compress_content => { type => 'boolean', optional => 1 },
192 optimise_content => { type => 'integer', min => 0, max => 2, optional => 1 },
193 lint_content => { type => 'boolean', optional => 1 },
194 cache => { type => 'object', can => [ 'get_object', 'set', 'remove' ], optional => 1 },
195 cache_key => { type => 'string', optional => 1 },
196 cache_duration => { type => 'string', optional => 1 },
197 save_to => { type => 'hashref', optional => 1 },
198 info => { type => 'object', optional => 1 },
199 lingua => { type => 'object', can => 'language', optional => 1 },
200 logger => { type => 'object', can => [ 'trace', 'debug', 'info', 'warn', 'error' ], optional => 1 },
201 }
202  
203 =head4 OUTPUT
204  
205 { type => 'object', isa => 'FCGI::Buffer' }
206  
207 Returns undef, with a warning, if it's called as a function or is given an odd
208 number of arguments.
209  
210 =head3 FORMAL SPECIFICATION
211  
212 new
213 args? : OPTION -+-> VALUE
214 self! : BUFFER
215 selected : FILEHANDLE
216 ---
217 self!.old_buf = selected
218 selected' = self!.buf
219 self!.generate_etag = args?.generate_etag
220 if generate_etag is in dom args?,
221 otherwise it is true exactly when the protocol is conditional
222  
223 =cut
224  
225 sub new
226 336 ▶{
Subroutine new: called CC=12 SCAR=24.9
Pod documented
227 336 my $proto = shift;
228 336 ▶ my $class = ref($proto) || $proto;
Condition66%2/3
ref $proto || $proto
l!l&&r!l&&!r
03342
MC/DC50%1/2
ref $proto || $proto
ref $proto $proto
Truth table66%2/3
A || B
A= ref $protoB= $proto
ABresult
1X1
011
000
229  
230 # Use FCGI::Buffer->new(), not FCGI::Buffer::new()
231 336 ▶ if(!defined($class)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $class) 2 334 336
232 2 carp(__PACKAGE__, ': use ->new() not ::new() to instantiate');
233 2 return;
234 }
235  
236 # Handle hash or hashref arguments
237 334 my %args;
238 334 ▶ if((@_ == 1) && (ref $_[0] eq 'HASH')) {
Branch: 2 branches
BranchTrueFalseTotal
if (@_ == 1 and ref $_[0] eq 'HASH') { } 1 333 334
elsif (@_ % 2 == 0) { } 332 1 333
Condition100%3/3
@_ == 1 and ref $_[0] eq "HASH"
!ll&&!rl&&r
33211
MC/DC100%2/2
@_ == 1 and ref $_[0] eq "HASH"
@_ == 1 ref $_[0] eq "HASH"
Truth table100%3/3
A and B
A= @_ == 1B= ref $_[0] eq "HASH"
ABresult
0X0
100
111
239 1 %args = %{$_[0]};
240 } elsif((@_ % 2) == 0) {
241 332 %args = @_;
242 } else {
243 1 carp(__PACKAGE__, ': Invalid arguments passed to new()');
244 1 return;
245 }
246  
247 # These need checking, which init() does
248 333 my %checked;
249 333 foreach my $option('cache', 'logger', 'save_to') {
250 999 ▶ $checked{$option} = delete $args{$option} if(exists($args{$option}));
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{$option} 4 995 999
251 }
252  
253 # Initialize buffer and object properties
254 333 ▶ my $buf = IO::String->new() or croak(__PACKAGE__, ': Failed to initialize IO::String');
Branch: 1 branch
BranchTrueFalseTotal
my $buf = "IO::String"->new or croak(__PACKAGE__, ": Failed to initialize IO::String") 333 0 333
255 333 my $rc = {
256 buf => $buf,
257 old_buf => select($buf),
258 generate_304 => $DEFAULT_GENERATE_304,
259 generate_last_modified => $DEFAULT_GENERATE_LAST_MODIFIED,
260 compress_content => $DEFAULT_COMPRESS_CONTENT,
261 optimise_content => $DEFAULT_OPTIMISE_CONTENT,
262 lint_content => $DEFAULT_LINT_CONTENT,
263 %args,
264 };
265 # $rc->{o} = ();
266  
267 # Premise 1: an ETag is only useful if the protocol supports If-None-Match
268 # Premise 2: an explicit generate_etag argument is the caller's decision
269 # Conclusion: default it from the protocol, but only when it isn't given
270 333 ▶ if(!defined($rc->{generate_etag})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $rc->{"generate_etag"}) 332 1 333
271 332 ▶ $rc->{generate_etag} = _is_conditional_protocol() ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
_is_conditional_protocol() ? : 185 147 332
272 }
273  
274 # Return the blessed object
275 333 my $self = bless $rc, $class;
276 333 ▶ $self->init(\%checked) if(%checked);
Branch: 1 branch
BranchTrueFalseTotal
if %checked 4 329 333
277 333 return $self;
278 }
279  
280 sub DESTROY
281 332 ▶{
Subroutine DESTROY: called CC=8 SCAR=21.4
282 332 ▶ if(defined($^V) && ($^V ge 'v5.14.0')) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $^V and $^V ge "v5.14.0") 332 0 332
Condition33%1/3
defined $^V and $^V ge "v5.14.0"
!ll&&!rl&&r
00332
MC/DC0%0/2
defined $^V and $^V ge "v5.14.0"
defined $^V $^V ge "v5.14.0"
Truth table33%1/3
A and B
A= defined $^VB= $^V ge "v5.14.0"
ABresult
0X0
100
111
283 332 ▶ return if ${^GLOBAL_PHASE} eq 'DESTRUCT'; # >= 5.14.0 only
Branch: 1 branch
BranchTrueFalseTotal
if ${^GLOBAL_PHASE} eq "DESTRUCT" 0 332 332
284 }
285 332 my $self = shift;
286  
287 # Premise 1: anything from here on can fail, e.g. a logger or a cache
288 # Premise 2: until this is done, all that the process prints goes into
289 # this buffer, which is about to disappear
290 # Conclusion: this must be the first thing that is done
291 332 select($self->{old_buf});
292  
293 # This can run while the caller's eval is unwinding
294 332 local($@, $!, $?);
295  
296 # Premise 1: Perl only gives a warning for an exception in a destructor
297 # Premise 2: the client would be given an empty response
298 # Conclusion: catch it, and send the output as the script printed it
299 332 ▶ return if(eval { $self->_send_output(); 1 });
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { $self->_send_output; 1 } } 329 3 332
300  
301 3 $self->_problem(__PACKAGE__ . ": $@");
302 3 ▶ return if($self->{_sent});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_sent"} 0 3 3
303 3 $self->{_sent} = 1;
304 3 ▶ if(defined($self->{_raw}) && length($self->{_raw})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{'_raw'} and length $self->{'_raw'}) { } 2 1 3
Condition66%2/3
defined $self->{"_raw"} and length $self->{"_raw"}
!ll&&!rl&&r
012
MC/DC50%1/2
defined $self->{"_raw"} and length $self->{"_raw"}
defined $self->{"_raw"} length $self->{"_raw"}
Truth table66%2/3
A and B
A= defined $self->{"_raw"}B= length $self->{"_raw"}
ABresult
0X0
100
111
305 2 print _to_bytes($self->{_raw});
306 } else {
307 # The script relied upon a cache that has now failed
308 1 print "Status: 500 Internal Server Error\r\n\r\n";
309 }
310 }
311  
312 # Everything that the script printed has been buffered, process and send it
313 sub _send_output
314 332 ▶{
Subroutine _send_output: called CC=150 SCAR=52.2
315 332 my $self = shift;
316  
317 332 ▶ if((!defined($self->{buf})) || (!defined($self->{buf}->getpos()))) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"buf"} and defined $self->{"buf"}->getpos) 62 270 332
Condition66%2/3
defined $self->{"buf"} and defined $self->{"buf"}->getpos
!ll&&!rl&&r
620270
MC/DC50%1/2
defined $self->{"buf"} and defined $self->{"buf"}->getpos
defined $self->{"buf"} defined $self->{"buf"}->getpos
Truth table66%2/3
A and B
A= defined $self->{"buf"}B= defined $self->{"buf"}->getpos
ABresult
0X0
100
111
318 # Unlikely
319 62 ▶ if($self->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 0 62 62
320 0 $self->{'logger'}->info('Nothing to send');
321 }
322 62 return;
323 }
324 270 my $pos = $self->{buf}->getpos();
325 270 $self->{buf}->setpos(0);
326 270 my $buf;
327 270 read($self->{buf}, $buf, $pos);
328  
329 # Keep this before anything else that can fail, it's what will be sent if
330 # something does
331 270 $self->{_raw} = $buf;
332  
333 270 ▶ if($self->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 24 246 270
334 24 $self->{'logger'}->trace('>In ' . __PACKAGE__ . ' _send_output');
335 }
336 267 my $headers;
337 267 ($headers, $self->{body}) = split /\r?\n\r?\n/, $buf, 2;
338  
339 267 ▶ if($self->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 21 246 267
340 21 ▶ if($ENV{'HTTP_IF_NONE_MATCH'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{"HTTP_IF_NONE_MATCH"}) 1 20 21
341 1 $self->{logger}->debug("HTTP_IF_NONE_MATCH: $ENV{HTTP_IF_NONE_MATCH}");
342 }
343 21 ▶ if($ENV{'HTTP_IF_MODIFIED_SINCE'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{"HTTP_IF_MODIFIED_SINCE"}) 3 18 21
344 3 $self->{logger}->debug("HTTP_IF_MODIFIED_SINCE: $ENV{HTTP_IF_MODIFIED_SINCE}");
345 }
346 21 $self->{logger}->debug("Generate_etag = $self->{generate_etag}, ",
347 "Generate_304 = $self->{generate_304}, ",
348 "Generate_last_modified = $self->{generate_last_modified}");
349 }
350  
351 267 ▶ unless($headers || $self->is_cached()) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($headers or $self->is_cached) 12 255 267
Condition100%3/3
$headers or $self->is_cached
l!l&&r!l&&!r
2302512
MC/DC100%2/2
$headers or $self->is_cached
$headers $self->is_cached
Truth table100%3/3
A or B
A= $headersB= $self->is_cached
ABresult
1X1
011
000
352 12 ▶ if($self->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 0 12 12
353 0 $self->{'logger'}->debug('There was no output');
354 }
355 12 ▶ if(!defined($headers)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $headers) 12 0 12
356 12 require HTTP::Status;
357 12 HTTP::Status->import();
358  
359 12 ▶ if(!defined($self->{'status'})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"status"}) 12 0 12
360 12 ▶ if($self->{'info'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'info'}) { } 1 11 12
361 1 $self->{'status'} = $self->{'info'}->status();
362 } else {
363 11 $self->{'status'} = 200;
364 }
365 }
366 12 $self->{_sent} = 1;
367 print 'Status: ', $self->{status}, ' ',
368 12 HTTP::Status::status_message($self->{status}),
369 "\n\n";
370 }
371 12 return;
372 }
373 255 ▶ $self->{send_body} = (defined($ENV{'REQUEST_METHOD'}) && ($ENV{'REQUEST_METHOD'} eq 'HEAD')) ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'REQUEST_METHOD'} && $ENV{'REQUEST_METHOD'} eq 'HEAD' ? : 2 253 255
Condition100%3/3
defined $ENV{"REQUEST_METHOD"} and $ENV{"REQUEST_METHOD"} eq "HEAD"
!ll&&!rl&&r
112422
MC/DC100%2/2
defined $ENV{"REQUEST_METHOD"} and $ENV{"REQUEST_METHOD"} eq "HEAD"
defined $ENV{"REQUEST_METHOD"} $ENV{"REQUEST_METHOD"} eq "HEAD"
Truth table100%3/3
A and B
A= defined $ENV{"REQUEST_METHOD"}B= $ENV{"REQUEST_METHOD"} eq "HEAD"
ABresult
0X0
100
111
374  
375 255 ▶ if($headers) {
Branch: 1 branch
BranchTrueFalseTotal
if ($headers) 230 25 255
376 230 $self->_set_content_type($headers);
377 }
378  
379 255 ▶ if(defined($self->{body}) && ($self->{body} eq '')) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $self->{'body'} and $self->{'body'} eq '') { } 3 252 255
elsif (defined $self->{'content_type'}) { } 224 28 252
Condition100%3/3
defined $self->{"body"} and $self->{"body"} eq ""
!ll&&!rl&&r
252273
MC/DC100%2/2
defined $self->{"body"} and $self->{"body"} eq ""
defined $self->{"body"} $self->{"body"} eq ""
Truth table100%3/3
A and B
A= defined $self->{"body"}B= $self->{"body"} eq ""
ABresult
0X0
100
111
380 # E.g. if header of Location is given with no body, for
381 # redirection
382 3 delete $self->{body};
383 3 ▶ if($self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"}) 0 3 3
384 # Don't try to retrieve it below from the cache
385 0 $self->{send_body} = 0;
386 }
387 } elsif(defined($self->{content_type})) {
388 224 my @content_type = @{$self->{content_type}};
389 224 ▶ if(defined($content_type[0]) && (lc($content_type[0]) eq 'text') && (lc($content_type[1]) =~ /^html/) && defined($self->{body}) && !$self->{_script_encoded}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $content_type[0] and lc $content_type[0] eq "text" and lc($content_type[1]) =~ /^html/ and defined $self->{"body"} and not $self->{"_script_encoded"}) 201 23 224
Condition83%10/12
defined $content_type[0] and lc $content_type[0] eq "text" and lc($content_type[1]) =~ /^html/ and defined $self->{"body"} and not $self->{"_script_encoded"}
!ll&&!rl&&r
221201
defined $content_type[0] and lc $content_type[0] eq "text" and lc($content_type[1]) =~ /^html/ and defined $self->{"body"}
!ll&&!rl&&r
220202
defined $content_type[0] and lc $content_type[0] eq "text" and lc($content_type[1]) =~ /^html/
!ll&&!rl&&r
319202
defined $content_type[0] and lc $content_type[0] eq "text"
!ll&&!rl&&r
03221
MC/DC60%3/5
defined $content_type[0] and lc $content_type[0] eq "text" and lc($content_type[1]) =~ /^html/ and defined $self->{"body"} and not $self->{"_script_encoded"}
defined $content_type[0] lc $content_type[0] eq "text" lc($content_type[1]) =~ /^html/ defined $self->{"body"} not $self->{"_script_encoded"}
Truth table66%4/6
A and B and C and D and not(E)
A= defined $content_type[0]B= lc $content_type[0] eq "text"C= lc($content_type[1]) =~ /^html/D= defined $self->{"body"}E= not $self->{"_script_encoded"}
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
390 201 ▶ if($self->{optimise_content}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"optimise_content"}) 38 163 201
391 # require HTML::Clean;
392 38 require HTML::Packer; # Overkill using HTML::Clean and HTML::Packer...
393  
394 38 ▶ if($self->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 0 38 38
395 0 $self->{'logger'}->trace('Packer');
396 }
397  
398 # Whitespace is significant in these, in a <textarea>
399 # it's the user's data
400 38 my $preformatted = $self->_protect_preformatted();
401  
402 # Level 1 is one pass, higher levels repeat until
403 # the body stops shrinking
404 38 my $oldlength = length($self->{body});
405 38 $self->_optimise_content();
406 38 ▶ if($self->{optimise_content} >= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"optimise_content"} >= 2) 6 32 38
407 6 ▶ while(length($self->{body}) < $oldlength) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $self->{"body"} < $oldlength) 4 6 10
408 4 $oldlength = length($self->{body});
409 4 $self->_optimise_content();
410 }
411 }
412  
413 # If we're on http://www.example.com and have a link
414 # to http://www.example.com/foo/bar.htm, change the
415 # link to /foo/bar.htm - there's no need to include
416 # the site name in the link
417 38 my $info = $self->_info();
418 38 my $href = $info->host_name();
419 38 ▶ my $protocol = $info->protocol() || $DEFAULT_PROTOCOL;
Condition66%2/3
$info->protocol || $DEFAULT_PROTOCOL
l!l&&r!l&&!r
19190
MC/DC0%0/2
$info->protocol || $DEFAULT_PROTOCOL
$info->protocol $DEFAULT_PROTOCOL
Truth table66%2/3
A || B
A= $info->protocolB= $DEFAULT_PROTOCOL
ABresult
1X1
011
000
420  
421 38 $self->{body} =~ s/<a\s+href="\Q$protocol\E:\/\/\Q$href\E"/<a href="\/"/gi;
422 38 $self->{body} =~ s/<a\s+href="\Q$protocol\E:\/\/\Q$href\E(?=[\/?#])/<a href="/gi;
423 38 $self->{body} =~ s/<a\s+href="\Q$protocol\E:\/\//<a href="\/\//gi;
424  
425 # If we're in "/cgi-bin/foo.cgi?arg1=a" replace
426 # "/cgi-bin/foo.cgi?arg2=b" with "?arg2=b"
427 # A link to "/cgi-bin/foo.cgi" with no arguments is
428 # left alone, since href="" would mean the current
429 # page, arguments and all
430  
431 38 my $script_name = $ENV{'SCRIPT_NAME'};
432 38 ▶ if(defined($script_name) && ($script_name =~ /^\//)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $script_name and $script_name =~ m[^/]) 30 8 38
Condition66%2/3
defined $script_name and $script_name =~ m[^/]
!ll&&!rl&&r
8030
MC/DC50%1/2
defined $script_name and $script_name =~ m[^/]
defined $script_name $script_name =~ m[^/]
Truth table66%2/3
A and B
A= defined $script_nameB= $script_name =~ m[^/]
ABresult
0X0
100
111
433 30 $self->{body} =~ s/<a\s+href="\Q$script_name\E(\?[^"]+)"/<a href="$1"/gi;
434 }
435  
436 # TODO use URI->path_segments to change links in
437 # /aa/bb/cc/dd.htm which point to /aa/bb/ff.htm to
438 # ../ff.htm
439  
440 # TODO: <img border=0 src=...>
441 38 $self->{body} =~ s/<img\s+src="\Q$protocol\E:\/\/\Q$href\E"/<img src="\/"/gi;
442 38 $self->{body} =~ s/<img\s+src="\Q$protocol\E:\/\/\Q$href\E(?=[\/?#])/<img src="/gi;
443  
444 # Don't use HTML::Clean because of RT402
445 # my $h = new HTML::Clean(\$self->{body});
446 # # $h->compat();
447 # $h->strip();
448 # my $ref = $h->data();
449  
450 # Don't always do javascript 'best' since it's confused
451 # by the common <!-- HIDE technique.
452 38 my $options = {
453 remove_comments => 1,
454 remove_newlines => 0,
455 do_stylesheet => 'minify'
456 };
457 38 ▶ if($self->{optimise_content} >= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"optimise_content"} >= 2) 6 32 38
458 6 $options->{do_javascript} = 'best';
459 # [^>] stops the tag running on into the
460 # rest of the page
461 6 $self->{body} =~ s/(<script[^>]*+>)\s*+<!--/$1/gi;
462 6 $self->{body} =~ s/\/\/-->\s*+<\/script>/<\/script>/gi;
463 6 $self->{body} =~ s/(<script[^>]*+>)\s++/$1/gi;
464 }
465 38 $self->{body} = HTML::Packer->init()->minify(\$self->{body}, $options);
466 38 ▶ if($self->{optimise_content} >= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"optimise_content"} >= 2) 6 32 38
467 # Change document.write("a"); document.write("b")
468 # into document.write("a"+"b");
469 # Premise 1: every substitution removes
470 # ");document.write(" and adds "+"
471 # Premise 2: so every substitution shortens the body
472 # Conclusion: looping until nothing is substituted
473 # is the same as looping until it stops
474 # shrinking, and always terminates
475 # Nothing may cross a </script>, otherwise
476 # writes in different scripts get merged
477 6 ▶ 1 while($self->{body} =~ s{
Branch: 1 branch
BranchTrueFalseTotal
$self->{"body"} =~ s[ (<script\s+type\s*=\s*"text/javascript"\s*>) # $1: opening tag, kept as written ((?:(?!</script>).)*?) # $2: code before the writes, within this script document\.write\(((?:(?!</script>)[^;])*?)\);\s*+ # $3: first argument document\.write\(((?:(?!</script>)[^;])*?)\) # $4: second argument ][$1$2document.write($3+$4)]gisx and do { '???' } 22 6 28
478 (<script\s+type\s*=\s*"text/javascript"\s*>) # $1: opening tag, kept as written
479 ((?:(?!</script>).)*?) # $2: code before the writes, within this script
480 document\.write\(((?:(?!</script>)[^;])*?)\);\s*+ # $3: first argument
481 document\.write\(((?:(?!</script>)[^;])*?)\) # $4: second argument
482 }{$1${2}document.write($3+$4)}gisx);
483 }
484 38 $self->_restore_preformatted($preformatted);
485 }
486 201 ▶ if($self->{lint_content}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"lint_content"}) 3 198 201
487 3 require HTML::Lint;
488 3 HTML::Lint->import;
489  
490 3 ▶ if($self->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 0 3 3
491 0 $self->{'logger'}->trace('Lint');
492 }
493 3 my $lint = HTML::Lint->new();
494 3 $lint->parse($self->{body});
495 3 $lint->eof();
496  
497 3 ▶ if($lint->errors) {
Branch: 1 branch
BranchTrueFalseTotal
if ($lint->errors) 1 2 3
498 1 $headers = 'Status: 500 Internal Server Error';
499 1 @{$self->{o}} = ('Content-type: text/plain');
500 1 $self->{body} = '';
501 1 foreach my $error ($lint->errors) {
502 3 my $errtext = $error->where() . ': ' . $error->errtext() . "\n";
503 3 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'logger'}) { } 0 3 3
504 0 $self->{logger}->warn($errtext);
505 } else {
506 3 warn($errtext);
507 }
508 3 $self->{body} .= $errtext;
509 }
510 }
511 }
512 }
513 }
514  
515 255 ▶ if(defined($headers) && ($headers =~ /^Status:\s*(\d+)/mi)) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $headers and $headers =~ /^Status:\s*(\d+)/im) { } 8 247 255
elsif (defined $self->{'info'}) { } 221 26 247
Condition100%3/3
defined $headers and $headers =~ /^Status:\s*(\d+)/im
!ll&&!rl&&r
252228
MC/DC100%2/2
defined $headers and $headers =~ /^Status:\s*(\d+)/im
defined $headers $headers =~ /^Status:\s*(\d+)/im
Truth table100%3/3
A and B
A= defined $headersB= $headers =~ /^Status:\s*(\d+)/im
ABresult
0X0
100
111
516 8 $self->{status} = $1;
517 } elsif(defined($self->{info})) {
518 221 $self->{status} = $self->{info}->status();
519 } else {
520 26 $self->{status} = 200;
521 }
522  
523 255 ▶ if($self->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 21 234 255
524 21 $self->{'logger'}->debug("Initial status = $self->{status}");
525 }
526  
527 # Range, Content-Length, compression and static pages all work in bytes.
528 # A script which printed bytes is left alone: encoding those would
529 # encode any UTF-8 in them a second time
530 255 ▶ if(defined($self->{body})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"body"}) 227 28 255
531 227 $self->{body} = _to_bytes($self->{body});
532 }
533  
534 255 ▶ my $dbh = $self->_try('save_to database', sub { $self->_save_to_dbh() });
Subroutine __ANON__: called CC=1 SCAR=0.0
535  
536 255 my $encoding = $self->_should_gzip();
537  
538 # The cache and the static page hold the page with its links as the script
539 # wrote them, since the links are looked at again for each request
540 255 my $unzipped_body = $self->{body};
541  
542 # Premise 1: the ETag says which version of the page the client has
543 # Premise 2: changing a link gives a different version
544 # Conclusion: change the links first, otherwise a client with the old links
545 # is told by a 304 that they're still current
546 255 ▶ if(defined($unzipped_body) && ($self->{status} == 200)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $unzipped_body and $self->{"status"} == 200) 222 33 255
Condition100%3/3
defined $unzipped_body and $self->{"status"} == 200
!ll&&!rl&&r
285222
MC/DC100%2/2
defined $unzipped_body and $self->{"status"} == 200
defined $unzipped_body $self->{"status"} == 200
Truth table100%3/3
A and B
A= defined $unzipped_bodyB= $self->{"status"} == 200
ABresult
0X0
100
111
547 222 $self->_save_to($unzipped_body, $dbh);
548 }
549  
550 # Generate the eTag before compressing, since the compressed data
551 # includes the mtime field which changes thus causing a different
552 # Etag to be generated
553 255 ▶ if($self->{generate_etag} && defined($self->{body}) && _is_conditional_protocol()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"generate_etag"} and defined $self->{"body"} and _is_conditional_protocol()) 136 119 255
Condition83%5/6
$self->{"generate_etag"} and defined $self->{"body"} and _is_conditional_protocol()
!ll&&!rl&&r
1190136
$self->{"generate_etag"} and defined $self->{"body"}
!ll&&!rl&&r
9623136
MC/DC66%2/3
$self->{"generate_etag"} and defined $self->{"body"} and _is_conditional_protocol()
$self->{"generate_etag"} defined $self->{"body"} _is_conditional_protocol()
Truth table75%3/4
A and B and C
A= $self->{"generate_etag"}B= defined $self->{"body"}C= _is_conditional_protocol()
ABCresult
0XX0
10X0
1100
1111
554 136 $self->_generate_etag();
555  
556 136 ▶ if($ENV{'HTTP_IF_NONE_MATCH'} && $self->{generate_304} && ($self->{status} == 200)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{"HTTP_IF_NONE_MATCH"} and $self->{"generate_304"} and $self->{"status"} == 200) 10 126 136
Condition83%5/6
$ENV{"HTTP_IF_NONE_MATCH"} and $self->{"generate_304"} and $self->{"status"} == 200
!ll&&!rl&&r
126010
$ENV{"HTTP_IF_NONE_MATCH"} and $self->{"generate_304"}
!ll&&!rl&&r
124210
MC/DC66%2/3
$ENV{"HTTP_IF_NONE_MATCH"} and $self->{"generate_304"} and $self->{"status"} == 200
$ENV{"HTTP_IF_NONE_MATCH"} $self->{"generate_304"} $self->{"status"} == 200
Truth table75%3/4
A and B and C
A= $ENV{"HTTP_IF_NONE_MATCH"}B= $self->{"generate_304"}C= $self->{"status"} == 200
ABCresult
0XX0
10X0
1100
1111
557 10 $self->_check_if_none_match();
558 }
559 }
560  
561 255 ▶ if(defined($unzipped_body)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $unzipped_body) 227 28 255
562 # Conditions are looked at before Range, and If-Modified-Since
563 # isn't looked at if If-None-Match was checked and failed.
564 # _check_modified_since() checks generate_304 itself
565 227 ▶ if((!$self->{cache}) && $self->{info} && $ENV{'HTTP_IF_MODIFIED_SINCE'} && ($self->{status} == 200) &&
Branch: 1 branch
BranchTrueFalseTotal
if (not $self->{"cache"} and $self->{"info"} and $ENV{"HTTP_IF_MODIFIED_SINCE"} and $self->{"status"} == 200 and not $ENV{"HTTP_IF_NONE_MATCH"} && defined $self->{"etag"}) 5 222 227
Condition93%14/15
not $self->{"cache"} and $self->{"info"} and $ENV{"HTTP_IF_MODIFIED_SINCE"} and $self->{"status"} == 200 and not $ENV{"HTTP_IF_NONE_MATCH"} && defined $self->{"etag"}
!ll&&!rl&&r
22115
not $self->{"cache"} and $self->{"info"} and $ENV{"HTTP_IF_MODIFIED_SINCE"} and $self->{"status"} == 200
!ll&&!rl&&r
22016
not $self->{"cache"} and $self->{"info"} and $ENV{"HTTP_IF_MODIFIED_SINCE"}
!ll&&!rl&&r
145757
not $self->{"cache"} and $self->{"info"}
!ll&&!rl&&r
1232282
$ENV{'HTTP_IF_NONE_MATCH'} && defined $self->{'etag'}
!ll&&!rl&&r
501
MC/DC83%5/6
not $self->{"cache"} and $self->{"info"} and $ENV{"HTTP_IF_MODIFIED_SINCE"} and $self->{"status"} == 200 and not $ENV{"HTTP_IF_NONE_MATCH"} && defined $self->{"etag"}
not $self->{"cache"} $self->{"info"} $ENV{"HTTP_IF_MODIFIED_SINCE"} $self->{"status"} == 200 $ENV{'HTTP_IF_NONE_MATCH'} defined $self->{'etag'}
Truth table85%6/7
not(A) and B and C and D and not(E && F)
A= not $self->{"cache"}B= $self->{"info"}C= $ENV{"HTTP_IF_MODIFIED_SINCE"}D= $self->{"status"} == 200E= $ENV{'HTTP_IF_NONE_MATCH'}F= defined $self->{'etag'}
ABCDEFresult
0XXXXX0
10XXXX0
110XXX0
1110XX0
1111110
11110X1
1111101
566 !($ENV{'HTTP_IF_NONE_MATCH'} && defined($self->{etag}))) {
567 $self->_check_modified_since({
568 5 since => $ENV{'HTTP_IF_MODIFIED_SINCE'},
569 modified => $self->_my_age()
570 });
571 }
572  
573 227 ▶ my $range = $ENV{'Range'} || $ENV{'HTTP_RANGE'};
Condition66%2/3
$ENV{'Range'} || $ENV{'HTTP_RANGE'}
l!l&&r!l&&!r
021206
MC/DC50%1/2
$ENV{'Range'} || $ENV{'HTTP_RANGE'}
$ENV{'Range'} $ENV{'HTTP_RANGE'}
Truth table66%2/3
A || B
A= $ENV{'Range'}B= $ENV{'HTTP_RANGE'}
ABresult
1X1
011
000
574  
575 # Only a successful GET can be cut up, and only if the client's
576 # copy, if it has given one, is still the current one
577 227 ▶ if($range && !$self->{cache} && ($self->{status} == 200) && _is_get() && $self->_if_range_matches() &&
Branch: 1 branch
BranchTrueFalseTotal
if ($range and not $self->{"cache"} and $self->{"status"} == 200 and _is_get() and $self->_if_range_matches and defined(my $partial = _apply_range($self->{"body"}, $range))) 13 214 227
Condition100%15/15
$range and not $self->{"cache"} and $self->{"status"} == 200 and _is_get() and $self->_if_range_matches and defined(my $partial = _apply_range($self->{"body"}, $range))
!ll&&!rl&&r
212213
$range and not $self->{"cache"} and $self->{"status"} == 200 and _is_get() and $self->_if_range_matches
!ll&&!rl&&r
209315
$range and not $self->{"cache"} and $self->{"status"} == 200 and _is_get()
!ll&&!rl&&r
208118
$range and not $self->{"cache"} and $self->{"status"} == 200
!ll&&!rl&&r
207119
$range and not $self->{"cache"}
!ll&&!rl&&r
206120
MC/DC100%6/6
$range and not $self->{"cache"} and $self->{"status"} == 200 and _is_get() and $self->_if_range_matches and defined(my $partial = _apply_range($self->{"body"}, $range))
$range not $self->{"cache"} $self->{"status"} == 200 _is_get() $self->_if_range_matches defined(my $partial = _apply_range($self->{"body"}, $range))
Truth table100%7/7
A and not(B) and C and D and E and F
A= $rangeB= not $self->{"cache"}C= $self->{"status"} == 200D= _is_get()E= $self->_if_range_matchesF= defined(my $partial = _apply_range($self->{"body"}, $range))
ABCDEFresult
0XXXXX0
10XXXX0
110XXX0
1110XX0
11110X0
1111100
1111111
578 defined(my $partial = _apply_range($self->{body}, $range))) {
579 # Premise 1: Content-Range counts the bytes of what is sent
580 # Premise 2: the offsets the client gave are in the page,
581 # not in a compressed copy which isn't the same each time
582 # Conclusion: a part of a page is never compressed
583 13 $encoding = '';
584 13 $self->{_partial} = 1;
585 13 $self->_set_status($partial->{status});
586 13 push @{$self->{o}}, "Content-Range: $partial->{content_range}";
587 13 ▶ if($partial->{status} == 416) {
Branch: 1 branch
BranchTrueFalseTotal
if ($partial->{'status'} == 416) { } 1 12 13
588 # Range Not Satisfiable has no body
589 1 delete $self->{body};
590 1 undef $unzipped_body;
591 1 $self->{send_body} = 0;
592 } else {
593 12 $self->{body} = $unzipped_body = $partial->{body};
594 }
595 }
596 # A 304 or 412 has no body to compress, and mustn't say that it has
597 227 ▶ if($self->{send_body} || ($self->{status} == 200)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"send_body"} or $self->{"status"} == 200) 218 9 227
Condition100%3/3
$self->{"send_body"} or $self->{"status"} == 200
l!l&&r!l&&!r
21719
MC/DC100%2/2
$self->{"send_body"} or $self->{"status"} == 200
$self->{"send_body"} $self->{"status"} == 200
Truth table100%3/3
A or B
A= $self->{"send_body"}B= $self->{"status"} == 200
ABresult
1X1
011
000
598 218 $self->_compress({ encoding => $encoding });
599 }
600 }
601  
602 255 ▶ if($self->{cache}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'cache'}) { } 148 107 255
elsif ($self->{'info'}) { } 83 24 107
603 148 require Storable;
604  
605 148 ▶ if($self->{'cache_age'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache_age"}) 0 148 148
606 # Legacy
607 0 $self->{'cache_duration'} = $self->{'cache_age'};
608 }
609  
610 148 my $cache_hash;
611 148 my $key = $self->_generate_key();
612  
613 # Cache unzipped version
614 148 ▶ if(!defined($self->{body})) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $self->{'body'}) { } 25 123 148
615 25 ▶ if($self->{send_body}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"send_body"}) 25 0 25
616 # is_cached() has already looked, and it mustn't
617 # have expired since then
618 25 ▶ $self->{cobject} ||= $self->_cache_lookup($key);
Condition33%1/3
$self->{"cobject"} ||= $self->_cache_lookup($key)
l!l&&r!l&&!r
2500
MC/DC0%0/2
$self->{"cobject"} ||= $self->_cache_lookup($key)
$self->{"cobject"} $self->_cache_lookup($key)
Truth table33%1/3
A ||= B
A= $self->{"cobject"}B= $self->_cache_lookup($key)
ABresult
1X1
011
000
619 25 ▶ if(defined($self->{cobject})) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $self->{'cobject'}) { } 25 0 25
elsif ($self->{'logger'}) { } 0 0 0
620 25 $cache_hash = Storable::thaw($self->{cobject}->value());
621 25 $headers = $cache_hash->{'headers'};
622 25 $self->_set_content_type($headers);
623 25 @{$self->{o}} = ("X-FCGI-Buffer-$VERSION: Hit", @{$self->_x_cache_headers('HIT', 'HIT')});
624 } elsif($self->{logger}) {
625 0 $self->{logger}->warn(ref($self), ": Error retrieving data for key $key");
626 } else {
627 0 carp(ref($self), ": error retrieving data for key $key");
628 }
629 }
630  
631 25 ▶ if($self->{send_body} && ($self->{status} == 200) && defined($cache_hash)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"send_body"} and $self->{"status"} == 200 and defined $cache_hash) 25 0 25
Condition33%2/6
$self->{"send_body"} and $self->{"status"} == 200 and defined $cache_hash
!ll&&!rl&&r
0025
$self->{"send_body"} and $self->{"status"} == 200
!ll&&!rl&&r
0025
MC/DC0%0/3
$self->{"send_body"} and $self->{"status"} == 200 and defined $cache_hash
$self->{"send_body"} $self->{"status"} == 200 defined $cache_hash
Truth table25%1/4
A and B and C
A= $self->{"send_body"}B= $self->{"status"} == 200C= defined $cache_hash
ABCresult
0XX0
10X0
1100
1111
632 25 $self->{body} = _to_bytes($cache_hash->{'body'});
633 25 ▶ if($dbh) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dbh) 9 16 25
634 9 $self->_save_to($self->{body}, $dbh);
635 }
636 25 ▶ if(!defined($self->{body})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"body"}) 1 24 25
637 # Panic
638 1 $headers = 'Status: 500 Internal Server Error';
639 1 @{$self->{o}} = ('Content-type: text/plain');
640 1 $self->{body} = "Can't retrieve body for key $key, cache_hash contains:\n";
641 1 foreach my $k (keys %{$cache_hash}) {
642 1 $self->{body} .= "\t$k\n";
643 }
644  
645 1 ▶ $self->_try('removing a bad entry', sub {
Subroutine __ANON__: called CC=7 SCAR=20.7
646 1 ▶ if($dbh) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dbh) 1 0 1
647 1 my $query = 'SELECT DISTINCT path FROM fcgi_buffer WHERE key = ?';
648 1 my $sth = $dbh->prepare($query);
649 1 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 1 0 1
650 1 $self->{logger}->debug("$query: $key");
651 }
652 1 ▶ if($sth->execute($key) && (my $href = $sth->fetchrow_hashref())) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sth->execute($key) and my $href = $sth->fetchrow_hashref) 1 0 1
Condition33%1/3
$sth->execute($key) and my $href = $sth->fetchrow_hashref
!ll&&!rl&&r
001
MC/DC0%0/2
$sth->execute($key) and my $href = $sth->fetchrow_hashref
$sth->execute($key) my $href = $sth->fetchrow_hashref
Truth table33%1/3
A and B
A= $sth->execute($key)B= my $href = $sth->fetchrow_hashref
ABresult
0X0
100
111
653 1 ▶ if(my $path = $href->{'path'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $path = $href->{"path"}) 1 0 1
654 1 unlink($path);
655 }
656 }
657 1 $query = 'DELETE FROM fcgi_buffer WHERE key = ?';
658 1 $dbh->do($query, undef, $key);
659 1 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 1 0 1
660 1 $self->{logger}->debug("$query: $key");
661 }
662 }
663  
664 1 $self->{cache}->remove($key);
665 1 });
666  
667 1 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'logger'}) { } 1 0 1
668 1 $self->{logger}->error("Can't retrieve body for key $key");
669 1 $self->{logger}->warn($self->{body});
670 } else {
671 0 carp("Can't retrieve body for key $key");
672 0 warn($self->{body});
673 }
674 1 $self->{send_body} = 0;
675 1 $self->_set_status(500);
676 }
677 }
678 25 ▶ if($self->{send_body} && ($self->{status} == 200) && $self->{generate_etag} && ((!defined($headers)) || ($headers !~ /^ETag: /m))) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"send_body"} and $self->{"status"} == 200 and $self->{"generate_etag"} and not defined $headers && $headers =~ /^ETag: /m) 21 4 25
Condition66%8/12
$self->{"send_body"} and $self->{"status"} == 200 and $self->{"generate_etag"} and not defined $headers && $headers =~ /^ETag: /m
!ll&&!rl&&r
4021
$self->{"send_body"} and $self->{"status"} == 200 and $self->{"generate_etag"}
!ll&&!rl&&r
1321
$self->{"send_body"} and $self->{"status"} == 200
!ll&&!rl&&r
1024
defined $headers && $headers =~ /^ETag: /m
!ll&&!rl&&r
0210
MC/DC40%2/5
$self->{"send_body"} and $self->{"status"} == 200 and $self->{"generate_etag"} and not defined $headers && $headers =~ /^ETag: /m
$self->{"send_body"} $self->{"status"} == 200 $self->{"generate_etag"} defined $headers $headers =~ /^ETag: /m
Truth table50%3/6
A and B and C and not(D && E)
A= $self->{"send_body"}B= $self->{"status"} == 200C= $self->{"generate_etag"}D= defined $headersE= $headers =~ /^ETag: /m
ABCDEresult
0XXXX0
10XXX0
110XX0
111110
1110X1
111101
679 21 $self->_generate_etag();
680 }
681 25 ▶ unless($self->{etag}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"etag"}) 4 21 25
682 # Keep the quotes, they're part of the ETag and
683 # If-None-Match includes them
684 4 ▶ if(defined($headers) && ($headers =~ /^ETag:\s*("[a-f0-9]{32}")/mi)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $headers and $headers =~ /^ETag:\s*("[a-f0-9]{32}")/im) { } 1 3 4
Condition66%2/3
defined $headers and $headers =~ /^ETag:\s*("[a-f0-9]{32}")/im
!ll&&!rl&&r
031
MC/DC50%1/2
defined $headers and $headers =~ /^ETag:\s*("[a-f0-9]{32}")/im
defined $headers $headers =~ /^ETag:\s*("[a-f0-9]{32}")/im
Truth table66%2/3
A and B
A= defined $headersB= $headers =~ /^ETag:\s*("[a-f0-9]{32}")/im
ABresult
0X0
100
111
685 1 $self->{etag} = $1;
686 } else {
687 3 $self->{etag} = $cache_hash->{'etag'};
688 }
689 }
690 # Nothing has been output yet, so we can check if it's OK to
691 # send 304 if possible.
692 # Premise 1: the ETag includes any changes to the links, the
693 # date doesn't, and browsers send both
694 # Premise 2: RFC 9110 13.1.3 says not to look at the date if
695 # there's an If-None-Match
696 # Conclusion: only one of them is ever looked at
697 # _check_modified_since() checks generate_304 itself
698 25 ▶ if($self->{status} == 200) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"status"} == 200) 24 1 25
699 24 ▶ if($ENV{'HTTP_IF_NONE_MATCH'} && defined($self->{etag})) {
Branch: 2 branches
BranchTrueFalseTotal
if ($ENV{'HTTP_IF_NONE_MATCH'} and defined $self->{'etag'}) { } 5 19 24
elsif ($ENV{'HTTP_IF_MODIFIED_SINCE'} and $self->{'cobject'}) { } 6 26 32
Condition66%2/3
$ENV{"HTTP_IF_NONE_MATCH"} and defined $self->{"etag"}
!ll&&!rl&&r
1905
MC/DC50%1/2
$ENV{"HTTP_IF_NONE_MATCH"} and defined $self->{"etag"}
$ENV{"HTTP_IF_NONE_MATCH"} defined $self->{"etag"}
Truth table66%2/3
A and B
A= $ENV{"HTTP_IF_NONE_MATCH"}B= defined $self->{"etag"}
ABresult
0X0
100
111
700 5 ▶ if($self->{generate_304}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"generate_304"}) 4 1 5
701 4 $self->_check_if_none_match();
702 }
703 ▶ } elsif($ENV{'HTTP_IF_MODIFIED_SINCE'} && $self->{cobject}) {
Condition66%2/3
$ENV{"HTTP_IF_MODIFIED_SINCE"} and $self->{"cobject"}
!ll&&!rl&&r
1306
MC/DC50%1/2
$ENV{"HTTP_IF_MODIFIED_SINCE"} and $self->{"cobject"}
$ENV{"HTTP_IF_MODIFIED_SINCE"} $self->{"cobject"}
Truth table66%2/3
A and B
A= $ENV{"HTTP_IF_MODIFIED_SINCE"}B= $self->{"cobject"}
ABresult
0X0
100
111
704 $self->_check_modified_since({
705 since => $ENV{'HTTP_IF_MODIFIED_SINCE'},
706 modified => $self->{cobject}->created_at()
707 6 });
708 }
709 }
710 # A 304 has no body to compress, and mustn't say that it has
711 25 ▶ if(($self->{status} == 200) && $self->{send_body}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"status"} == 200 and $self->{"send_body"}) 16 9 25
Condition66%2/3
$self->{"status"} == 200 and $self->{"send_body"}
!ll&&!rl&&r
9016
MC/DC50%1/2
$self->{"status"} == 200 and $self->{"send_body"}
$self->{"status"} == 200 $self->{"send_body"}
Truth table66%2/3
A and B
A= $self->{"status"} == 200B= $self->{"send_body"}
ABresult
0X0
100
111
712 16 $encoding = $self->_should_gzip();
713 16 $self->_compress({ encoding => $encoding });
714 }
715 25 ▶ if($self->{cobject}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cobject"}) 25 0 25
716 25 ▶ if(($self->{status} == 200) && $self->{generate_last_modified}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"status"} == 200 and $self->{"generate_last_modified"}) 16 9 25
Condition66%2/3
$self->{"status"} == 200 and $self->{"generate_last_modified"}
!ll&&!rl&&r
9016
MC/DC50%1/2
$self->{"status"} == 200 and $self->{"generate_last_modified"}
$self->{"status"} == 200 $self->{"generate_last_modified"}
Truth table66%2/3
A and B
A= $self->{"status"} == 200B= $self->{"generate_last_modified"}
ABresult
0X0
100
111
717 16 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 2 14 16
718 2 $self->{logger}->debug('Set Last-Modified to ', HTTP::Date::time2str($self->{cobject}->created_at()));
719 }
720 16 push @{$self->{o}}, 'Last-Modified: ' . HTTP::Date::time2str($self->{cobject}->created_at());
721 }
722 }
723 } else {
724 # Not in the server-side cache
725 123 ▶ if($self->{status} == 200) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"status"} == 200) 121 2 123
726 121 ▶ unless($self->{cache_duration}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"cache_duration"}) 120 1 121
727 # It would be great if CHI::set()
728 # allowed the time to be 'lru' for least
729 # recently used.
730 120 $self->{cache_duration} = $DEFAULT_CACHE_DURATION;
731 }
732 121 $cache_hash->{'body'} = $unzipped_body;
733  
734 121 my $storable = $self->_is_storable($headers, $unzipped_body);
735 121 ▶ if($storable) {
Branch: 1 branch
BranchTrueFalseTotal
if ($storable) 111 10 121
736 111 ▶ if($self->{o} && scalar(@{$self->{o}})) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'o'} and scalar @{$self->{'o'};}) { } 18 93 111
elsif (defined $headers and length $headers) { } 93 0 93
Condition100%2/2
$self->{"o"} and scalar @{$self->{"o"};}
!ll
9318
MC/DC100%1/1
$self->{"o"} and scalar @{$self->{"o"};}
$self->{"o"}
Truth table100%2/2
A
A= $self->{"o"}
Aresult
00
11
737 # Remember, we're storing the UNzipped
738 # version in the cache. An Expires that
739 # was generated here is about the links
740 # in this response, and they are looked
741 # at again for each request
742 18 my $generated = join("\r\n", grep { !/^Expires:/i } @{$self->{o}});
743 18 my $c;
744 18 ▶ if(defined($headers) && length($headers)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $headers and length $headers) { } 18 0 18
Condition33%1/3
defined $headers and length $headers
!ll&&!rl&&r
0018
MC/DC0%0/2
defined $headers and length $headers
defined $headers length $headers
Truth table33%1/3
A and B
A= defined $headersB= length $headers
ABresult
0X0
100
111
745 18 $c = "$headers\r\n$generated";
746 } else {
747 0 $c = $generated;
748 }
749 18 $c =~ s/^Content-Encoding: .+$//mgi;
750 18 $c =~ s/^Content-Length: .+$//mgi;
751 18 $c =~ s/^Vary: Accept-Encoding.*\r?$//mgi;
752 18 $c =~ s/\n+/\n/gs;
753 18 ▶ if(length($c)) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $c) 18 0 18
754 18 $cache_hash->{'headers'} = $c;
755 }
756 ▶ } elsif(defined($headers) && length($headers)) {
Condition33%1/3
defined $headers and length $headers
!ll&&!rl&&r
0093
MC/DC0%0/2
defined $headers and length $headers
defined $headers length $headers
Truth table33%1/3
A and B
A= defined $headersB= length $headers
ABresult
0X0
100
111
757 93 my $c = $headers;
758 93 $c =~ s/^Content-Encoding: .+$//mgi;
759 93 $c =~ s/^Content-Length: .+$//mgi;
760 93 $c =~ s/^Vary: Accept-Encoding.*\r?$//mgi;
761 93 $c =~ s/\n+/\n/gs;
762 93 ▶ if(length($c)) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $c) 93 0 93
763 93 $cache_hash->{'headers'} = $c;
764 }
765 }
766 111 ▶ if($self->{generate_etag}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"generate_etag"}) 64 47 111
767 64 $self->_generate_etag();
768 64 $cache_hash->{'etag'} = $self->{etag};
769 }
770 111 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 15 96 111
771 15 $self->{logger}->debug("Store $key in the cache, age = ", $self->{cache_duration}, ' ', length($cache_hash->{'body'}), ' bytes');
772 }
773 111 ▶ $self->_try('storing in the cache', sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
774 111 $self->{cache}->set($key, Storable::freeze($cache_hash), $self->{cache_duration});
775 111 });
776  
777 # Create a static page with the information and link to that in the output
778 # HTML
779 # Pages whose content depends on who the client is are
780 # never saved, since anyone following the static
781 # link would be given them
782 111 ▶ if($dbh && $self->{info} && $self->{save_to} && (my $request_uri = $ENV{'REQUEST_URI'}) && $self->_is_html() && !_is_per_client()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dbh and $self->{"info"} and $self->{"save_to"} and my $request_uri = $ENV{"REQUEST_URI"} and $self->_is_html and not _is_per_client()) 72 39 111
Condition80%12/15
$dbh and $self->{"info"} and $self->{"save_to"} and my $request_uri = $ENV{"REQUEST_URI"} and $self->_is_html and not _is_per_client()
!ll&&!rl&&r
36372
$dbh and $self->{"info"} and $self->{"save_to"} and my $request_uri = $ENV{"REQUEST_URI"} and $self->_is_html
!ll&&!rl&&r
34275
$dbh and $self->{"info"} and $self->{"save_to"} and my $request_uri = $ENV{"REQUEST_URI"}
!ll&&!rl&&r
34077
$dbh and $self->{"info"} and $self->{"save_to"}
!ll&&!rl&&r
34077
$dbh and $self->{"info"}
!ll&&!rl&&r
34077
MC/DC50%3/6
$dbh and $self->{"info"} and $self->{"save_to"} and my $request_uri = $ENV{"REQUEST_URI"} and $self->_is_html and not _is_per_client()
$dbh $self->{"info"} $self->{"save_to"} my $request_uri = $ENV{"REQUEST_URI"} $self->_is_html not _is_per_client()
Truth table57%4/7
A and B and C and D and E and not(F)
A= $dbhB= $self->{"info"}C= $self->{"save_to"}D= my $request_uri = $ENV{"REQUEST_URI"}E= $self->_is_htmlF= not _is_per_client()
ABCDEFresult
0XXXXX0
10XXXX0
110XXX0
1110XX0
11110X0
1111100
1111111
783 72 ▶ $self->_try('writing a static page', sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
784 72 $self->_write_static_page($key, $unzipped_body, $dbh, $request_uri);
785 72 });
786 }
787 }
788 121 ▶ if($self->{generate_last_modified}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"generate_last_modified"}) 121 0 121
789 121 ▶ $self->{cobject} = $storable ? $self->_cache_lookup($key) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$storable ? : 111 10 121
790 121 ▶ if(defined($self->{cobject})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{'cobject'}) { } 109 12 121
791 109 push @{$self->{o}}, 'Last-Modified: ' . HTTP::Date::time2str($self->{cobject}->created_at());
792 } else {
793 12 push @{$self->{o}}, 'Last-Modified: ' . HTTP::Date::time2str(time);
794 }
795 }
796 }
797 123 ▶ push @{$self->{o}}, @{$self->_x_cache_headers(defined($self->{x_cache}) ? $self->{x_cache} : 'MISS', 'MISS')}, "X-FCGI-Buffer-$VERSION: Miss";
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'x_cache'} ? : 123 0 123
798 }
799 # We don't need it any more, so give Perl a chance to
800 # tidy it up seeing as we're in the destructor
801 148 delete $self->{cache};
802 } elsif($self->{info}) {
803 83 push @{$self->{o}}, @{$self->_x_cache_headers('MISS', 'MISS')};
804 83 ▶ if($self->{generate_last_modified}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"generate_last_modified"}) 83 0 83
805 83 ▶ if(my $age = $self->_my_age()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $age = $self->_my_age) 57 26 83
806 57 push @{$self->{o}}, 'Last-Modified: ' . HTTP::Date::time2str($age);
807 }
808 }
809 } else {
810 24 push @{$self->{o}}, @{$self->_x_cache_headers('MISS', 'MISS')};
811 }
812  
813 # The branch that was taken when there was no ETag had an empty body,
814 # but called is_cached() which looks in the cache, so it is removed
815 255 $self->_add_vary($headers);
816  
817 255 ▶ if($self->{generate_etag} && defined($self->{etag}) && ((!defined($headers)) || ($headers !~ /^ETag:/mi))) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"generate_etag"} and defined $self->{"etag"} and not defined $headers && $headers =~ /^ETag:/im) 156 99 255
Condition88%8/9
$self->{"generate_etag"} and defined $self->{"etag"} and not defined $headers && $headers =~ /^ETag:/im
!ll&&!rl&&r
981156
$self->{"generate_etag"} and defined $self->{"etag"}
!ll&&!rl&&r
962157
defined $headers && $headers =~ /^ETag:/im
!ll&&!rl&&r
01561
MC/DC75%3/4
$self->{"generate_etag"} and defined $self->{"etag"} and not defined $headers && $headers =~ /^ETag:/im
$self->{"generate_etag"} defined $self->{"etag"} defined $headers $headers =~ /^ETag:/im
Truth table80%4/5
A and B and not(C && D)
A= $self->{"generate_etag"}B= defined $self->{"etag"}C= defined $headersD= $headers =~ /^ETag:/im
ABCDresult
0XXX0
10XX0
11110
110X1
11101
818 # The compressed and the uncompressed versions aren't the same
819 # bytes, so can't have the same strong ETag.
820 # _check_if_none_match() removes the suffix again, and a 304 is
821 # about the copy that the client has so gives back its ETag
822 156 ▶ my $etag = defined($self->{_matched_etag}) ? $self->{_matched_etag} : $self->{etag};
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'_matched_etag'} ? : 9 147 156
823 156 ▶ if($self->{_content_encoding} && !defined($self->{_matched_etag})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_content_encoding"} and not defined $self->{"_matched_etag"}) 7 149 156
Condition66%2/3
$self->{"_content_encoding"} and not defined $self->{"_matched_etag"}
!ll&&!rl&&r
14907
MC/DC50%1/2
$self->{"_content_encoding"} and not defined $self->{"_matched_etag"}
$self->{"_content_encoding"} not defined $self->{"_matched_etag"}
Truth table66%2/3
A and not(B)
A= $self->{"_content_encoding"}B= not defined $self->{"_matched_etag"}
ABresult
0X0
100
111
824 7 $etag =~ s/"$/-$self->{_content_encoding}"/;
825 }
826 156 push @{$self->{o}}, "ETag: $etag";
827 156 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 18 138 156
828 18 $self->{logger}->debug("Set ETag to $etag");
829 }
830 }
831  
832 255 my $body_length = 0;
833 255 ▶ if(defined($self->{body})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"body"}) 251 4 255
834 251 $self->{body} = _to_bytes($self->{body});
835 251 $body_length = length($self->{body});
836 }
837  
838 255 ▶ if(defined($headers) && length($headers)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $headers and length $headers) { } 254 1 255
Condition66%2/3
defined $headers and length $headers
!ll&&!rl&&r
01254
MC/DC50%1/2
defined $headers and length $headers
defined $headers length $headers
Truth table66%2/3
A and B
A= defined $headersB= length $headers
ABresult
0X0
100
111
839 # Put the original headers first, then those generated within
840 # FCGI::Buffer. The script is free to end its lines with \n
841 254 unshift @{$self->{o}}, grep { length } split(/\r?\n/, $headers);
842  
843 # The body may well have changed since the script worked out its
844 # length
845 254 ▶ if(defined($self->{body})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"body"}) 250 4 254
846 250 @{$self->{o}} = grep { !/^Content-Length:/i } @{$self->{o}};
847 }
848 254 ▶ if($body_length && $self->{send_body}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($body_length and $self->{"send_body"}) 232 22 254
Condition100%3/3
$body_length and $self->{"send_body"}
!ll&&!rl&&r
418232
MC/DC100%2/2
$body_length and $self->{"send_body"}
$body_length $self->{"send_body"}
Truth table100%3/3
A and B
A= $body_lengthB= $self->{"send_body"}
ABresult
0X0
100
111
849 232 push @{$self->{o}}, "Content-Length: $body_length";
850 }
851 254 $self->_set_status_header();
852 } else {
853 1 push @{$self->{o}}, "X-FCGI-Buffer-$VERSION: No headers";
854 }
855  
856 255 @{$self->{o}} = _one_expires(@{$self->{o}});
857  
858 255 ▶ if($body_length && $self->{send_body}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($body_length and $self->{"send_body"}) 232 23 255
Condition100%3/3
$body_length and $self->{"send_body"}
!ll&&!rl&&r
518232
MC/DC100%2/2
$body_length and $self->{"send_body"}
$body_length $self->{"send_body"}
Truth table100%3/3
A and B
A= $body_lengthB= $self->{"send_body"}
ABresult
0X0
100
111
859 232 push @{$self->{o}}, ('', $self->{body});
860 }
861  
862 # The Wide character debugging code that was here was inside if(0), so
863 # could never run
864 255 $self->{_sent} = 1;
865 255 ▶ if(scalar(@{$self->{o}})) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @{$self->{"o"};}) 255 0 255
866 255 print join("\r\n", @{$self->{o}});
867 }
868  
869 255 ▶ if(!($self->{send_body} && defined($self->{body}))) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $self->{"send_body"} && defined $self->{"body"}) 22 233 255
Condition100%3/3
$self->{'send_body'} && defined $self->{'body'}
!ll&&!rl&&r
193233
MC/DC100%2/2
$self->{'send_body'} && defined $self->{'body'}
$self->{'send_body'} defined $self->{'body'}
Truth table100%3/3
A && B
A= $self->{'send_body'}B= defined $self->{'body'}
ABresult
0X0
100
111
870 22 print "\r\n\r\n";
871 }
872 }
873  
874 224 ▶sub _generate_etag {
Subroutine _generate_etag: called CC=4 SCAR=13.9
875 224 my $self = shift;
876  
877 224 ▶ return if defined($self->{'etag'});
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"etag"} 67 157 224
878 157 ▶ return unless defined($self->{'body'});
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"body"} 0 157 157
879  
880 # bytes to avoid "Wide character in subroutine entry"
881 157 $self->{etag} = '"' . Digest::MD5->new->add(_to_bytes($self->{body}))->hexdigest() . '"';
882 157 ▶ if($self->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 18 139 157
883 18 $self->{'logger'}->debug('Etag = ', $self->{'etag'});
884 }
885 }
886  
887 17 ▶sub _check_modified_since {
Subroutine _check_modified_since: called CC=14 SCAR=26.4
888 17 my $self = shift;
889  
890 17 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 3 14 17
891 3 $self->{logger}->trace('In _check_modified_since');
892 }
893  
894 17 ▶ if(!$self->{generate_304}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"generate_304"}) 1 16 17
895 1 return;
896 }
897 # RFC 9110 13.1.3: If-Modified-Since is ignored for other methods
898 16 ▶ return unless(_is_safe_method());
Branch: 1 branch
BranchTrueFalseTotal
unless _is_safe_method() 1 15 16
899  
900 15 my $params = shift;
901  
902 15 ▶ if(!defined($$params{since})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $params->{"since"}) 1 14 15
903 1 return;
904 }
905 14 my $s = HTTP::Date::str2time($$params{since});
906 14 ▶ if(!defined($s)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $s) 2 12 14
907 2 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 0 2 2
908 0 $self->{logger}->info("$$params{since} is not a valid date");
909 }
910 2 return;
911 }
912  
913 12 my $age = $self->_my_age();
914 12 ▶ if(!defined($age)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $age) 2 10 12
915 2 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 0 2 2
916 0 $self->{logger}->info("Can't determine my age");
917 }
918 2 return;
919 }
920 10 ▶ if($age > $s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($age > $s) 2 8 10
921 2 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 1 1 2
922 1 $self->{logger}->debug('_check_modified_since: script has been modified');
923 }
924 # Script has been updated so it may produce different output
925 2 return;
926 }
927  
928 8 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 2 6 8
929 2 $self->{logger}->debug("_check_modified_since: Compare $$params{modified} with $s");
930 }
931 8 ▶ if($$params{modified} <= $s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{"modified"} <= $s) 7 1 8
932 7 push @{$self->{o}}, 'Status: 304 Not Modified';
933 7 $self->_set_status(304);
934 7 $self->{send_body} = 0;
935 7 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 2 5 7
936 2 $self->{logger}->debug('Set status to 304');
937 }
938 }
939 }
940  
941 # Reduce output, e.g. remove superfluous white-space.
942 47 ▶sub _optimise_content {
Subroutine _optimise_content: called CC=1 SCAR=0.0
943 47 my $self = shift;
944  
945 # FIXME: regex bad, HTML parser good
946 # Regexp::List - wow!
947 # Remove whitespace around newlines. Possessive quantifiers and only
948 # starting at the beginning of a run of whitespace keep it linear
949 47 $self->{body} =~ s{
950 (?<![^\S\n]) # start only at the beginning of a whitespace run
951 [^\S\n]*+ # trailing spaces, tabs and \r before the newline
952 \n
953 \s*+ # blank lines and indentation after it
954 }{\n}gx;
955 # $self->{body} =~ s/\r\n/\n/gs;
956 # $self->{body} =~ s/\s+\n/\n/gs;
957 # $self->{body} =~ s/\n+/\n/gs;
958 # $self->{body} =~ s/\n\s+|\s+\n/\n/g;
959 47 $self->{body} =~ s/\<\/div\>\s+\<div/\<\/div\>\<div/gis;
960 # $self->{body} =~ s/\<\/p\>\s\<\/div/\<\/p\>\<\/div/gis;
961 # $self->{body} =~ s/\<div\>\s+/\<div\>/gis; # Remove spaces after <div>
962 # In these, (?<!\s) and possessive quantifiers stop each alternation
963 # being retried at every position inside a long run of whitespace
964 47 $self->{body} =~ s/(?:<div>\s++|(?<!\s)\s++<div>)/<div>/gi;
965 47 $self->{body} =~ s/\s+<\/div\>/\<\/div\>/gis; # Remove spaces before </div>
966 47 $self->{body} =~ s/(?:(?<!\s)\s++<p>|<p>\s++)/<p>/i; # TODO <p class=
967 47 $self->{body} =~ s/(?:(?<!\s)\s++<\/p>|<\/p>\s++)/<\/p>/gi;
968 47 $self->{body} =~ s/<html>\s+<head>/<html><head>/is;
969 47 $self->{body} =~ s/(?<!\s)\s*+<\/head>\s++<body>\s*+/<\/head><body>/i;
970 47 $self->{body} =~ s/<html>\s+<body>/<html><body>/is;
971 47 $self->{body} =~ s/<body>\s+/<body>/is;
972 47 $self->{body} =~ s/\s+\<\/html/\<\/html/is;
973 47 $self->{body} =~ s/\s+\<\/body/\<\/body/is;
974 # $self->{body} =~ s/(\<.+?\>\s\<.+?\>)\s/$1/g;
975 47 $self->{body} =~ s/\<p\>\s/\<p\>/gi;
976 47 $self->{body} =~ s/\<\/p\>\s\<p\>/\<\/p\>\<p\>/gi;
977 47 $self->{body} =~ s/\<\/tr\>\s\<tr\>/\<\/tr\>\<tr\>/gi;
978 47 $self->{body} =~ s/\<\/td\>\s\<\/tr\>/\<\/td\>\<\/tr\>/gi;
979 47 $self->{body} =~ s/\<\/td\>\s*\<td\>/\<\/td\>\<td\>/gis;
980 47 $self->{body} =~ s/\<\/tr\>\s\<\/table\>/\<\/tr\>\<\/table\>/gi;
981 47 $self->{body} =~ s/\<br\s?\/?\>\s?\<p\>/\<p\>/gi;
982 47 $self->{body} =~ s/\<br\>\s+/\<br\>/gi;
983 47 $self->{body} =~ s/\s+\<br/\<br/gi;
984 47 $self->{body} =~ s/\<br\s?\/\>\s/\<br \/\>/gi;
985 47 $self->{body} =~ s/[ \t]+/ /gs; # Remove duplicate space, don't use \s+ it breaks JavaScript
986 47 $self->{body} =~ s/\s\<p\>/\<p\>/gi;
987 47 $self->{body} =~ s/\s\<script/\<script/gi;
988 47 $self->{body} =~ s/(<script>\s|\s<script>)/<script>/gis;
989 47 $self->{body} =~ s/(<\/script>\s|\s<\/script>)/<\/script>/gis;
990 47 $self->{body} =~ s/\<td\>\s/\<td\>/gi;
991 # The link can't leave its quotes, so these can't span tags or
992 # backtrack across the rest of the page
993 47 $self->{body} =~ s{
994 (?<!\s)\s++ # a whole run of whitespace, starting at its first character
995 <a\shref="([^"]*+)"> # $1: the link
996 \s?
997 }{ <a href="$1">}gix;
998 47 $self->{body} =~ s{
999 \s?
1000 <a\shref=\s"([^"]*+)"> # $1: the link
1001 }{ <a href="$1">}gix;
1002 47 $self->{body} =~ s/\s+<\/a\>\s+/<\/a> /gis;
1003 47 $self->{body} =~ s/(?:\s?<hr>\s++|(?<!\s)\s++<hr>\s?)/<hr>/gi;
1004 # $self->{body} =~ s/\s<hr>/<hr>/gis;
1005 # $self->{body} =~ s/<hr>\s/<hr>/gis;
1006 47 $self->{body} =~ s/<\/li>\s+<li>/<\/li><li>/gis;
1007 47 $self->{body} =~ s/<\/li>\s+<\/ul>/<\/li><\/ul>/gis;
1008 47 $self->{body} =~ s/<ul>\s+<li>/<ul><li>/gis;
1009 47 $self->{body} =~ s/\s+<\/li>/<\/li>/gis;
1010 47 $self->{body} =~ s/\<\/option\>\s+\<option/\<\/option\>\<option/gis;
1011 # A title can't contain a tag. [^<] and the possessive quantifiers stop
1012 # each unterminated <title> from being searched to the end of the page
1013 47 $self->{body} =~ s{<title>\s*+([^<]*+)</title>}{
1014 4 my $title = $1;
1015 4 $title =~ s/(?<!\s)\s++\z//;
1016 4 "<title>$title</title>"
1017 }eix;
1018 47 $self->{body} =~ s/<\/center>\s+<center>/ /gis;
1019 }
1020  
1021 # Create a key for the cache
1022 234 ▶sub _generate_key {
Subroutine _generate_key: called CC=7 SCAR=19.5
1023 234 my $self = shift;
1024 234 ▶ if($self->{cache_key}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache_key"}) 99 135 234
1025 99 return $self->{cache_key};
1026 }
1027 135 $self->_info();
1028  
1029 135 my $key = __PACKAGE__ . '::' . $self->{info}->browser_type() . '::' . $self->{info}->domain_name() . '::' . $self->{info}->script_name() . '::' . $self->{info}->as_string();
1030  
1031 135 ▶ if(defined($ENV{'PATH_INFO'}) && length($ENV{'PATH_INFO'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ENV{"PATH_INFO"} and length $ENV{"PATH_INFO"}) 3 132 135
Condition66%2/3
defined $ENV{"PATH_INFO"} and length $ENV{"PATH_INFO"}
!ll&&!rl&&r
13203
MC/DC50%1/2
defined $ENV{"PATH_INFO"} and length $ENV{"PATH_INFO"}
defined $ENV{"PATH_INFO"} length $ENV{"PATH_INFO"}
Truth table66%2/3
A and B
A= defined $ENV{"PATH_INFO"}B= length $ENV{"PATH_INFO"}
ABresult
0X0
100
111
1032 # /cgi-bin/foo.fcgi/bar and /cgi-bin/foo.fcgi/baz are different pages
1033 3 $key .= '::PATH_INFO=' . $ENV{'PATH_INFO'};
1034 }
1035 135 ▶ if($self->{lingua}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"lingua"}) 61 74 135
1036 61 $key .= '::' . $self->{lingua}->language();
1037 }
1038 # Different states of the client are stored in different caches
1039 135 foreach my $cookie(_client_cookies()) {
1040 2 $key .= "::$cookie";
1041 }
1042  
1043 # The key is needed before the script has given its headers, so a Vary
1044 # header can't be part of it. _is_storable() doesn't store those pages
1045 135 $key =~ s/\//::/g;
1046 135 $key =~ s/(?:::){2,}/::/g;
1047 135 $key =~ s/::$//;
1048 135 ▶ if(defined($self->{logger})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"logger"}) 13 122 135
1049 13 $self->{logger}->trace("Returning $key");
1050 }
1051 135 $self->{cache_key} = $key;
1052 135 return $key;
1053 }
1054  
1055 =head2 init
1056  
1057 Set various options and override default values.
1058  
1059 # Put this toward the top of your program before you do anything
1060 # By default, generate_etag, generate_304 and compress_content are ON,
1061 # optimise_content and lint_content are OFF. Set optimise_content to 2 to
1062 # do aggressive JavaScript optimisations which may fail.
1063 use FCGI::Buffer;
1064  
1065 my $buffer = FCGI::Buffer->new()->init({
1066 generate_etag => 1, # make good use of client's cache
1067 generate_last_modified => 1, # more use of client's cache
1068 compress_content => 1, # if gzip the output
1069 optimise_content => 0, # optimise your program's HTML, CSS and JavaScript
1070 cache => CHI->new(driver => 'File'), # cache requests
1071 cache_key => 'string', # key for the cache
1072 cache_duration => '10 minutes', # how long to store responses in the cache
1073 logger => $self->{logger},
1074 lint_content => 0, # Pass through HTML::Lint
1075 generate_304 => 1, # When appropriate, generate 304: Not modified
1076 save_to => { directory => '/var/www/htdocs/save_to', ttl => 600, create_table => 1, max_pages => 10000 },
1077 info => CGI::Info->new(),
1078 lingua => CGI::Lingua->new(),
1079 });
1080  
1081 If no cache_key is given, one will be generated which may not be unique.
1082 The cache_key should be a unique value dependent upon the values set by the
1083 browser.
1084  
1085 The cache object will be an object that understands get_object(),
1086 set(), remove() and created_at() messages, such as an L<CHI> object. It is
1087 used as a server-side cache to reduce the need to rerun database accesses.
1088  
1089 Items stay in the server-side cache by default for 10 minutes, the default can
1090 be changed by the cache_duration argument to init().
1091 An item that has expired is no longer used.
1092 The max-age directive of the client's Cache-Control HTTP header overrides this
1093 if it's a number no larger than 600 seconds.
1094 A larger value or something that isn't a number is ignored,
1095 so a client can't fill your cache with items that are kept for years.
1096  
1097 Responses are not stored in the server-side cache if the script's headers
1098 include Set-Cookie,
1099 or a Cache-Control of no-store, no-cache or private,
1100 or a Content-Encoding,
1101 or a Vary on anything except Accept-Encoding
1102 (and Accept-Language, if a lingua argument has been given),
1103 or if the output is an HTML page with an <html> tag but no </html> tag,
1104 which suggests that the script died part way through.
1105 If your script finds an error after printing other types of content,
1106 turn off the cache and save_to as described below.
1107  
1108 Save_to is feature which stores output of dynamic pages to your
1109 htdocs tree and replaces future links that point to that page with static links
1110 to avoid going through CGI at all.
1111 Ttl is set to the number of seconds that the static pages are deemed to
1112 be live for, the default is 10 minutes.
1113 If set to 0, the page is live forever.
1114 A page that has passed its ttl is saved again the next time it's requested,
1115 and is removed when any page is requested.
1116 Max_pages is the most static pages to keep, the default is 10000, and 0 means no
1117 limit.
1118 It stops a client from filling your disc by asking for many different arguments.
1119 Create_table says to create the table in the database if it doesn't exist.
1120 To enable save_to, info and cache arguments must also be given,
1121 and a lingua argument should be given if the output depends on the language.
1122 Without a cache no static pages are written.
1123 The directory must be inside the document root,
1124 otherwise the static pages can't be linked to, so save_to is turned off and a
1125 warning given once.
1126 Only use where output is guaranteed to be the same with a given set of arguments
1127 (the same criteria for enabling generate_304).
1128 Only HTML pages are saved.
1129 Pages generated for clients that send cookies (other than Google Analytics
1130 cookies and C<csrf_token>) or have logged in, or those that aren't stored in the server-side
1131 cache for the reasons above, are not saved,
1132 since the static page would be given to everyone.
1133 Those cookies don't change which entry in the server-side cache is used,
1134 so a script whose output depends on one must send a Set-Cookie header with that
1135 output.
1136 A page that includes the value of the C<csrf_token> cookie is never stored.
1137 Links can give the arguments of a page in any order.
1138 Several virtual hosts can share a directory.
1139 You can turn it off on a case by case basis thus:
1140  
1141 my $params = CGI::Info->new()->params();
1142 if($params->{'send_private_email'}) {
1143 $buffer->init('save_to' => undef);
1144 }
1145  
1146 Info is an optional argument to give information about the FCGI environment, e.g.
1147 a L<CGI::Info> object.
1148  
1149 Logger will be an object that understands trace(), debug(), info(), warn() and
1150 error(), such as an L<Log::Log4perl> object.
1151 A logger without those is ignored, with a warning.
1152 is_debug() is also used, if it's there.
1153  
1154 A Last-Modified header is generated if you give a cache object or an info
1155 object, since the time comes from when the cache entry was created or from the
1156 script's file.
1157  
1158 Init allows a reference of the options to be passed. So both of these work:
1159  
1160 use FCGI::Buffer;
1161 #...
1162 my $buffer = FCGI::Buffer->new();
1163 $buffer->init(generate_etag => 1);
1164 $buffer->init({ generate_etag => 1, info => CGI::Info->new() });
1165  
1166 Generally speaking, passing by reference is better since it copies less on to
1167 the stack.
1168  
1169 If you give a cache to init() then later give cache => undef,
1170 the server-side cache is no longer used.
1171 This is useful when you find an error condition when creating your HTML
1172 and decide that you no longer wish to store the output in the cache.
1173  
1174 Init always returns the object, so that calls can be chained.
1175 If the save_to argument can't be used,
1176 for example if the directory can't be written to,
1177 a warning is given once and the page is sent without save_to.
1178  
1179 =head3 API SPECIFICATION
1180  
1181 =head4 INPUT
1182  
1183 The same as new(), where save_to is:
1184  
1185 {
1186 directory => { type => 'string' },
1187 ttl => { type => 'integer', min => 0, optional => 1 },
1188 create_table => { type => 'boolean', optional => 1 },
1189 max_pages => { type => 'integer', min => 0, optional => 1 },
1190 }
1191  
1192 =head4 OUTPUT
1193  
1194 { type => 'object', isa => 'FCGI::Buffer' }
1195  
1196 =head3 MESSAGES
1197  
1198 +------------------------------------+------------------------------+--------------------------+
1199 | Message | Meaning | Resolution |
1200 +------------------------------------+------------------------------+--------------------------+
1201 | Too late to call init | Output was printed first | Call init earlier |
1202 | save_to must be a hash reference | Another type was given | Give a hash reference |
1203 | save_to needs a directory | The directory key is missing | Give a directory |
1204 | D isn't a directory | It can't be created | Check the path |
1205 | D isn't writeable | Permissions | Check the permissions |
1206 | D is not under the document root | Pages could not be linked to | Move it under the root |
1207 | The logger doesn't understand M | Missing method | Use another logger |
1208 +------------------------------------+------------------------------+--------------------------+
1209  
1210 =head3 FORMAL SPECIFICATION
1211  
1212 init
1213 params? : OPTION -+-> VALUE
1214 self, self' : BUFFER
1215 ---
1216 dom params? is a subset of OPTION
1217 self'.save_to is defined =>
1218 can_cache(self) and writeable(self'.save_to.directory) and
1219 under(rootdir, self'.save_to.directory)
1220 params?.cache = undef => self'.cache is undefined
1221 result! = self'
1222  
1223 =cut
1224  
1225 271 ▶sub init {
Subroutine init: called CC=26 SCAR=33.1
Pod documented
1226 271 my $self = shift;
1227 271 ▶ my %params = (ref($_[0]) eq 'HASH') ? %{$_[0]} : @_;
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 237 34 271
1228  
1229 # Safe options - can be called at any time
1230 271 foreach my $option(@SAFE_OPTIONS) {
1231 2168 ▶ if(defined($params{$option})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params{$option}) 180 1988 2168
1232 180 $self->{$option} = $params{$option};
1233 }
1234 }
1235 271 ▶ if(defined($params{'logger'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params{"logger"}) 26 245 271
1236 26 $self->_check_logger();
1237 }
1238  
1239 # Before save_to, which needs it
1240 271 ▶ if(defined($params{info}) && (!defined($self->{info}))) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params{"info"} and not defined $self->{"info"}) 196 75 271
Condition66%2/3
defined $params{"info"} and not defined $self->{"info"}
!ll&&!rl&&r
750196
MC/DC50%1/2
defined $params{"info"} and not defined $self->{"info"}
defined $params{"info"} not defined $self->{"info"}
Truth table66%2/3
A and not(B)
A= defined $params{"info"}B= not defined $self->{"info"}
ABresult
0X0
100
111
1241 196 $self->{info} = $params{info};
1242 }
1243  
1244 271 ▶ if(defined($params{save_to}) && $self->can_cache()) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $params{'save_to'} and $self->can_cache) { } 110 161 271
elsif (exists $params{'save_to'} and not defined $params{'save_to'}) { } 4 311 315
Condition100%3/3
defined $params{"save_to"} and $self->can_cache
!ll&&!rl&&r
1583110
MC/DC100%2/2
defined $params{"save_to"} and $self->can_cache
defined $params{"save_to"} $self->can_cache
Truth table100%3/3
A and B
A= defined $params{"save_to"}B= $self->can_cache
ABresult
0X0
100
111
1245 110 ▶ if(my $problem = $self->_save_to_problem($params{save_to})) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $problem = $self->_save_to_problem($params{'save_to'})) { } 11 99 110
1246 # The page can still be sent, so this isn't fatal. It
1247 # would be repeated for each request of a long running
1248 # process, but only needs saying once
1249 11 $self->_problem_once($problem);
1250 11 delete $self->{'save_to'};
1251 } else {
1252 99 $self->{save_to} = $params{save_to};
1253 99 ▶ if(!exists($params{save_to}->{'ttl'})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $params{"save_to"}{"ttl"}) 1 98 99
1254 1 $self->{save_to}->{'ttl'} = $DEFAULT_SAVE_TO_TTL;
1255 }
1256 }
1257 ▶ } elsif(exists($params{'save_to'}) && !defined($params{'save_to'})) {
Condition100%3/3
exists $params{"save_to"} and not defined $params{"save_to"}
!ll&&!rl&&r
15434
MC/DC100%2/2
exists $params{"save_to"} and not defined $params{"save_to"}
exists $params{"save_to"} not defined $params{"save_to"}
Truth table100%3/3
A and not(B)
A= exists $params{"save_to"}B= not defined $params{"save_to"}
ABresult
0X0
100
111
1258 4 delete $self->{'save_to'};
1259 }
1260  
1261 # Unsafe options - must be called before output has been started
1262 271 my $pos = $self->{buf}->getpos;
1263 271 ▶ if($pos > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos > 0) 1 270 271
1264 1 ▶ if(defined($self->{logger})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{'logger'}) { } 0 1 1
1265 0 my @call_details = caller(0);
1266 0 $self->{logger}->warn("Too late to call init, $pos characters have been printed, caller line $call_details[2] of $call_details[1]");
1267 } else {
1268 # Must do Carp::carp instead of carp for Test::Carp
1269 1 Carp::carp "Too late to call init, $pos characters have been printed";
1270 }
1271 }
1272 271 ▶ if(exists($params{cache}) && $self->can_cache()) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"cache"} and $self->can_cache) 158 113 271
Condition100%3/3
exists $params{"cache"} and $self->can_cache
!ll&&!rl&&r
1085158
MC/DC100%2/2
exists $params{"cache"} and $self->can_cache
exists $params{"cache"} $self->can_cache
Truth table100%3/3
A and B
A= exists $params{"cache"}B= $self->can_cache
ABresult
0X0
100
111
1273 # There is an argument not to do this since one client will
1274 # affect others, so it's limited
1275 158 my $max_age = _client_max_age();
1276 158 ▶ if(defined($max_age) && ($max_age <= $MAX_CLIENT_CACHE_SECONDS)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $max_age and $max_age <= $MAX_CLIENT_CACHE_SECONDS) 3 155 158
Condition100%3/3
defined $max_age and $max_age <= $MAX_CLIENT_CACHE_SECONDS
!ll&&!rl&&r
15323
MC/DC100%2/2
defined $max_age and $max_age <= $MAX_CLIENT_CACHE_SECONDS
defined $max_age $max_age <= $MAX_CLIENT_CACHE_SECONDS
Truth table100%3/3
A and B
A= defined $max_ageB= $max_age <= $MAX_CLIENT_CACHE_SECONDS
ABresult
0X0
100
111
1277 3 $self->{cache_duration} = "$max_age seconds";
1278 3 ▶ if(defined($self->{logger})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"logger"}) 0 3 3
1279 0 $self->{logger}->debug("cache_duration = $self->{cache_duration}");
1280 }
1281 }
1282 158 ▶ $self->{cache_duration} ||= $params{cache_duration};
Condition100%3/3
$self->{"cache_duration"} ||= $params{"cache_duration"}
l!l&&r!l&&!r
44150
MC/DC100%2/2
$self->{"cache_duration"} ||= $params{"cache_duration"}
$self->{"cache_duration"} $params{"cache_duration"}
Truth table100%3/3
A ||= B
A= $self->{"cache_duration"}B= $params{"cache_duration"}
ABresult
1X1
011
000
1283 158 ▶ if(defined($params{cache})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params{'cache'}) { } 156 2 158
1284 156 $self->{cache} = $params{cache};
1285 } else {
1286 2 ▶ if(defined($self->{logger}) && defined($self->{cache})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"logger"} and defined $self->{"cache"}) 0 2 2
Condition33%1/3
defined $self->{"logger"} and defined $self->{"cache"}
!ll&&!rl&&r
200
MC/DC0%0/2
defined $self->{"logger"} and defined $self->{"cache"}
defined $self->{"logger"} defined $self->{"cache"}
Truth table33%1/3
A and B
A= defined $self->{"logger"}B= defined $self->{"cache"}
ABresult
0X0
100
111
1287 0 ▶ $self->{logger}->debug('disabling cache', ($self->{cache_key} ? " $self->{cache_key}" : ''));
Branch: 1 branch
BranchTrueFalseTotal
$self->{'cache_key'} ? : 0 0 0
1288 }
1289 2 delete $self->{cache};
1290 }
1291 158 ▶ if(defined($params{cache_key})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params{"cache_key"}) 15 143 158
1292 15 $self->{cache_key} = $params{cache_key};
1293 }
1294 }
1295  
1296 271 return $self;
1297 }
1298  
1299 =head2 set_options
1300  
1301 Synonym for init, kept for historical reasons.
1302  
1303 =head3 API SPECIFICATION
1304  
1305 =head4 INPUT
1306  
1307 The same as init().
1308  
1309 =head4 OUTPUT
1310  
1311 { type => 'object', isa => 'FCGI::Buffer' }
1312  
1313 =head3 FORMAL SPECIFICATION
1314  
1315 set_options == init
1316  
1317 =cut
1318  
1319 11 ▶sub set_options {
Subroutine set_options: called CC=2 SCAR=6.9
Pod documented
1320 11 my $self = shift;
1321 11 ▶ my %params = (ref($_[0]) eq 'HASH') ? %{$_[0]} : @_;
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 8 3 11
1322  
1323 11 $self->init(\%params);
1324 }
1325  
1326 =head2 can_cache
1327  
1328 Returns true if the server is allowed to store the results locally.
1329 This is the value of X-Cache in the returned header.
1330  
1331 The cache isn't used if the NO_CACHE or NO_STORE environment variables are set,
1332 if the request method isn't GET or HEAD,
1333 if the client has logged in (the Authorization header or REMOTE_USER is set),
1334 or if the client's Cache-Control header includes any of no-store, no-cache,
1335 private or max-age=0.
1336 The answer is decided on the first call, and doesn't change for the rest of the
1337 request.
1338  
1339 =head3 API SPECIFICATION
1340  
1341 =head4 INPUT
1342  
1343 None.
1344  
1345 =head4 OUTPUT
1346  
1347 { type => 'boolean' }
1348  
1349 =head3 FORMAL SPECIFICATION
1350  
1351 can_cache
1352 env : NAME -+-> STRING
1353 result! : BOOLEAN
1354 ---
1355 result! = true <=>
1356 NO_CACHE, NO_STORE, HTTP_AUTHORIZATION, REMOTE_USER are not in dom env and
1357 (REQUEST_METHOD is not in dom env or env(REQUEST_METHOD) is in {GET, HEAD}) and
1358 directives(env(HTTP_CACHE_CONTROL)) has none of {no-store, no-cache, private, max-age=0}
1359  
1360 =cut
1361  
1362 308 ▶sub can_cache {
Subroutine can_cache: called CC=12 SCAR=24.9
Pod documented
1363 308 my $self = shift;
1364  
1365 308 ▶ if(defined($self->{x_cache})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"x_cache"}) 115 193 308
1366 115 return ($self->{x_cache} eq 'HIT');
1367 }
1368 193 ▶ if(defined($self->{logger}) && defined($ENV{'HTTP_CACHE_CONTROL'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"logger"} and defined $ENV{"HTTP_CACHE_CONTROL"}) 0 193 193
Condition66%2/3
defined $self->{"logger"} and defined $ENV{"HTTP_CACHE_CONTROL"}
!ll&&!rl&&r
177160
MC/DC0%0/2
defined $self->{"logger"} and defined $ENV{"HTTP_CACHE_CONTROL"}
defined $self->{"logger"} defined $ENV{"HTTP_CACHE_CONTROL"}
Truth table66%2/3
A and B
A= defined $self->{"logger"}B= defined $ENV{"HTTP_CACHE_CONTROL"}
ABresult
0X0
100
111
1369 0 $self->{logger}->debug("cache_control = $ENV{HTTP_CACHE_CONTROL}");
1370 }
1371  
1372 # A request may give several directives, e.g. "no-cache, max-age=0",
1373 # and any one of them forbids the cache
1374 193 my $control = _cache_control();
1375 193 my $max_age = _client_max_age();
1376 my $forbidden = defined($ENV{'NO_CACHE'}) || defined($ENV{'NO_STORE'}) ||
1377 (!_is_safe_method()) || _is_logged_in() ||
1378 193 ▶ (grep { $NO_CACHE_DIRECTIVES{$_} } keys %{$control}) ||
Condition100%18/18
defined $ENV{'NO_CACHE'} || defined $ENV{'NO_STORE'} || !_is_safe_method() || _is_logged_in() || grep({$NO_CACHE_DIRECTIVES{$_};} keys %{$control;}) || defined $max_age && $max_age == 0
l!l&&r!l&&!r
161176
defined $ENV{"NO_CACHE"} or defined $ENV{"NO_STORE"} or not _is_safe_method() or _is_logged_in() or grep {$NO_CACHE_DIRECTIVES{$_};} keys %{$control;}
l!l&&r!l&&!r
115177
defined $ENV{"NO_CACHE"} or defined $ENV{"NO_STORE"} or not _is_safe_method() or _is_logged_in()
l!l&&r!l&&!r
92182
defined $ENV{"NO_CACHE"} or defined $ENV{"NO_STORE"} or not _is_safe_method()
l!l&&r!l&&!r
63184
defined $ENV{"NO_CACHE"} or defined $ENV{"NO_STORE"}
l!l&&r!l&&!r
33187
defined $max_age and $max_age == 0
!ll&&!rl&&r
17061
MC/DC100%7/7
defined $ENV{'NO_CACHE'} || defined $ENV{'NO_STORE'} || !_is_safe_method() || _is_logged_in() || grep({$NO_CACHE_DIRECTIVES{$_};} keys %{$control;}) || defined $max_age && $max_age == 0
defined $ENV{"NO_CACHE"} defined $ENV{"NO_STORE"} not _is_safe_method() _is_logged_in() grep {$NO_CACHE_DIRECTIVES{$_};} keys %{$control;} defined $max_age $max_age == 0
Truth table100%8/8
A or B or not(C) or D or E || F and G
A= defined $ENV{"NO_CACHE"}B= defined $ENV{"NO_STORE"}C= not _is_safe_method()D= _is_logged_in()E= grep {$NO_CACHE_DIRECTIVES{$_};} keys %{$control;}F= defined $max_ageG= $max_age == 0
ABCDEFGresult
1XXXXXX1
01XXXXX1
001XXXX1
0001XXX1
00001XX1
00000111
000000X0
00000100
1379 (defined($max_age) && ($max_age == 0));
1380  
1381 193 ▶ $self->{x_cache} = $forbidden ? 'MISS' : 'HIT';
Branch: 1 branch
BranchTrueFalseTotal
$forbidden ? : 17 176 193
1382 193 ▶ return $forbidden ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$forbidden ? : 17 176 193
1383 }
1384  
1385 =head2 is_cached
1386  
1387 Returns true if the output is cached. If it is then it means that all of the
1388 expensive routines in the FCGI script can be by-passed because we already have
1389 the result stored in the cache.
1390  
1391 # Put this toward the top of your program before you do anything
1392  
1393 # Example key generation - use whatever you want as something
1394 # unique for this call, so that subsequent calls with the same
1395 # values match something in the cache
1396 use CGI::Info;
1397 use CGI::Lingua;
1398 use FCGI::Buffer;
1399  
1400 my $i = CGI::Info->new();
1401 my $l = CGI::Lingua->new(supported => ['en']);
1402  
1403 # To use server-side caching you must give the cache argument, however
1404 # the cache_key argument is optional - if you don't give one then one will
1405 # be generated for you
1406 my $buffer = FCGI::Buffer->new();
1407 if($buffer->can_cache()) {
1408 $buffer->init(
1409 cache => CHI->new(driver => 'File'),
1410 cache_key => $i->domain_name() . '/' . $i->script_name() . '/' . $i->as_string() . '/' . $l->language()
1411 );
1412 if($buffer->is_cached()) {
1413 # Output will be retrieved from the cache and sent automatically
1414 exit;
1415 }
1416 }
1417 # Not in the cache, so now do our expensive computing to generate the
1418 # results
1419 print "Content-type: text/html\n";
1420 # ...
1421  
1422 An entry that has expired isn't cached,
1423 and neither is any entry if the script's file has changed since,
1424 or if the age of the script can't be determined.
1425 If the cache fails, a warning is given and the output isn't cached.
1426  
1427 =head3 API SPECIFICATION
1428  
1429 =head4 INPUT
1430  
1431 None.
1432  
1433 =head4 OUTPUT
1434  
1435 { type => 'boolean' }
1436  
1437 =head3 FORMAL SPECIFICATION
1438  
1439 is_cached
1440 cache : KEY -+-> ENTRY
1441 key : KEY
1442 script_mtime : TIME
1443 now : TIME
1444 result! : BOOLEAN
1445 ---
1446 result! = true <=>
1447 key is in dom cache and
1448 cache(key).value is defined and
1449 cache(key).expires_at > now and
1450 script_mtime <= cache(key).created_at
1451  
1452 =cut
1453  
1454 112 ▶sub is_cached {
Subroutine is_cached: called CC=14 SCAR=35.0
Pod documented
1455 112 my $self = shift;
1456  
1457 112 ▶ unless($self->{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"cache"}) 27 85 112
1458 27 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 0 27 27
1459 0 $self->{logger}->debug("is_cached: cache hasn't been enabled");
1460 0 my $i = 0;
1461 0 ▶ while((my @call_details = (caller($i++)))) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@call_details) = &CORE::GLOBAL::caller($i++)) 0 0 0
1462 0 $self->{logger}->debug($call_details[1], ':', $call_details[2], ' calling function ', $call_details[3]);
1463 }
1464 }
1465 27 return 0;
1466 }
1467  
1468 85 my $key = $self->_generate_key();
1469  
1470 85 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 17 68 85
1471 17 $self->{logger}->debug("is_cached: looking for key = $key");
1472 }
1473 85 $self->{cobject} = $self->_cache_lookup($key);
1474 85 ▶ unless($self->{cobject}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"cobject"}) 32 53 85
1475 32 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 4 28 32
1476 4 $self->{logger}->debug('not found in cache');
1477 }
1478 32 return 0;
1479 }
1480 53 ▶ unless($self->{cobject}->value($key)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"cobject"}->value($key)) 0 53 53
1481 0 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 0 0 0
1482 0 $self->{logger}->warn('is_cached: object is in the cache but not the data');
1483 }
1484 0 delete $self->{cobject};
1485 0 return 0;
1486 }
1487  
1488 # If the script has changed, don't use the cache since we may produce
1489 # different output
1490 53 my $age = $self->_my_age();
1491 53 ▶ unless(defined($age)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $age) 0 53 53
1492 0 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 0 0 0
1493 0 $self->{logger}->debug("Can't determine script's age");
1494 }
1495 # Can't determine the age. Play it safe an assume we're not
1496 # cached
1497 0 delete $self->{cobject};
1498 0 return 0;
1499 }
1500 53 ▶ if($age > $self->{cobject}->created_at()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($age > $self->{"cobject"}->created_at) 0 53 53
1501 # Script has been updated so it may produce different output
1502 0 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 0 0 0
1503 0 $self->{logger}->debug('Script has been updated');
1504 }
1505 0 delete $self->{cobject};
1506 # Nothing will be in date and all new searches would miss
1507 # anyway, so may as well clear it all
1508 # FIXME: RT104471
1509 # $self->{cache}->clear();
1510 0 return 0;
1511 }
1512 53 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 13 40 53
1513 13 $self->{logger}->debug('Script is in the cache');
1514 }
1515 53 return 1;
1516 }
1517  
1518 # Determine the last modification time of the script and cache it for subsequent calls
1519 155 ▶sub _my_age {
Subroutine _my_age: called CC=3 SCAR=11.0
1520 155 my $self = shift;
1521  
1522 155 ▶ return $self->{script_mtime} if(defined($self->{script_mtime}));
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"script_mtime"} 42 113 155
1523  
1524 # croak() never returns, so nothing is needed after it
1525 113 my $path = $self->_info()->script_path();
1526 113 ▶ croak 'Failed to retrieve script path' unless(defined($path));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 0 113 113
1527  
1528 113 my @statb = stat($path);
1529 113 $self->{'script_mtime'} = $statb[9]; # Set script_mtime to the modification time of the script
1530 113 return $self->{script_mtime};
1531 }
1532  
1533 # Return the content encoding to use, or '' for none.
1534 # Premise 1: _compress() fails the request with a 406 if it can't load the
1535 # module for the encoding
1536 # Premise 2: the client is happy with any of the encodings it lists
1537 # Conclusion: choose the first listed encoding that can be loaded, then the 406
1538 # can't happen
1539 sub _should_gzip
1540 282 ▶{
Subroutine _should_gzip: called CC=11 SCAR=24.0
1541 282 my $self = shift;
1542  
1543 282 ▶ return '' unless($self->{compress_content});
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"compress_content"} 2 280 282
1544 280 ▶ my $accept = $ENV{'HTTP_ACCEPT_ENCODING'} || $ENV{'HTTP_TE'};
Condition100%3/3
$ENV{'HTTP_ACCEPT_ENCODING'} || $ENV{'HTTP_TE'}
l!l&&r!l&&!r
212257
MC/DC100%2/2
$ENV{'HTTP_ACCEPT_ENCODING'} || $ENV{'HTTP_TE'}
$ENV{'HTTP_ACCEPT_ENCODING'} $ENV{'HTTP_TE'}
Truth table100%3/3
A || B
A= $ENV{'HTTP_ACCEPT_ENCODING'}B= $ENV{'HTTP_TE'}
ABresult
1X1
011
000
1545 280 ▶ return '' unless($accept);
Branch: 1 branch
BranchTrueFalseTotal
unless $accept 257 23 280
1546 23 ▶ return '' if(defined($self->{content_type}) && (lc($self->{content_type}->[0]) ne 'text'));
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"content_type"} and lc $self->{"content_type"}[0] ne "text" 1 22 23
Condition100%3/3
defined $self->{"content_type"} and lc $self->{"content_type"}[0] ne "text"
!ll&&!rl&&r
9131
MC/DC100%2/2
defined $self->{"content_type"} and lc $self->{"content_type"}[0] ne "text"
defined $self->{"content_type"} lc $self->{"content_type"}[0] ne "text"
Truth table100%3/3
A and B
A= defined $self->{"content_type"}B= lc $self->{"content_type"}[0] ne "text"
ABresult
0X0
100
111
1547 22 ▶ return '' if($self->{_script_encoded}); # It would be compressed twice
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_script_encoded"} 1 21 22
1548  
1549 21 foreach my $method(split(/\s*,\s*/, lc($accept))) {
1550 # e.g. "gzip;q=0.8", where q=0 means "not acceptable"
1551 24 my ($name, @params) = split(/\s*;\s*/, $method);
1552 24 ▶ next if(grep { /^q=0(?:\.0*)?$/ } @params);
Branch: 1 branch
BranchTrueFalseTotal
if grep {/^q=0(?:\.0*)?$/;} @params 1 23 24
1553 23 ▶ return $name if($ENCODING_MODULE{$name} && _can_load($ENCODING_MODULE{$name}));
Branch: 1 branch
BranchTrueFalseTotal
if $ENCODING_MODULE{$name} and _can_load($ENCODING_MODULE{$name}) 20 3 23
Condition100%3/3
$ENCODING_MODULE{$name} and _can_load($ENCODING_MODULE{$name})
!ll&&!rl&&r
2120
MC/DC100%2/2
$ENCODING_MODULE{$name} and _can_load($ENCODING_MODULE{$name})
$ENCODING_MODULE{$name} _can_load($ENCODING_MODULE{$name})
Truth table100%3/3
A and B
A= $ENCODING_MODULE{$name}B= _can_load($ENCODING_MODULE{$name})
ABresult
0X0
100
111
1554 }
1555  
1556 1 return '';
1557 }
1558  
1559 # Can the given module be loaded? The answer is remembered
1560 {
1561 15 my %loadable;
1562  
1563 sub _can_load
1564 27 ▶ {
Subroutine _can_load: called CC=3 SCAR=11.0
1565 27 my $module = shift;
1566  
1567 27 ▶ if(!exists($loadable{$module})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $loadable{$module}) 7 20 27
1568 7 ▶ $loadable{$module} = eval "require $module; 1" ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
eval "require $module; 1" ? : 7 0 7
1569 }
1570 27 return $loadable{$module};
1571 }
1572 }
1573  
1574 sub _set_content_type
1575 15 ▶{
Subroutine _set_content_type: called CC=7 SCAR=19.5
1576 255 my $self = shift;
1577 255 my $headers = shift;
1578  
1579 255 foreach my $header (split(/\r?\n/, $headers)) {
1580 281 my ($header_name, $header_value) = split /\:\s*/, $header, 2;
1581 281 ▶ next unless(defined($header_name) && defined($header_value));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $header_name and defined $header_value 4 277 281
Condition100%3/3
defined $header_name and defined $header_value
!ll&&!rl&&r
13277
MC/DC100%2/2
defined $header_name and defined $header_value
defined $header_name defined $header_value
Truth table100%3/3
A and B
A= defined $header_nameB= defined $header_value
ABresult
0X0
100
111
1582 277 ▶ if(lc($header_name) eq 'content-type') {
Branch: 2 branches
BranchTrueFalseTotal
if (lc $header_name eq 'content-type') { } 250 27 277
elsif (lc $header_name eq 'content-encoding' and not lc($header_value) =~ /^\s*identity\s*$/) { } 1 52 53
1583 250 my @content_type = split /\//, $header_value, 2;
1584 250 $self->{content_type} = \@content_type;
1585 ▶ } elsif((lc($header_name) eq 'content-encoding') && (lc($header_value) !~ /^\s*identity\s*$/)) {
Condition66%2/3
lc $header_name eq "content-encoding" and not lc($header_value) =~ /^\s*identity\s*$/
!ll&&!rl&&r
2601
MC/DC50%1/2
lc $header_name eq "content-encoding" and not lc($header_value) =~ /^\s*identity\s*$/
lc $header_name eq "content-encoding" not lc($header_value) =~ /^\s*identity\s*$/
Truth table66%2/3
A and not(B)
A= lc $header_name eq "content-encoding"B= not lc($header_value) =~ /^\s*identity\s*$/
ABresult
0X0
100
111
1586 1 $self->{_script_encoded} = 1;
1587 }
1588 }
1589 }
1590  
1591 # Compress the body with the given encoding, from _should_gzip()
1592 sub _compress
1593 241 ▶{
Subroutine _compress: called CC=16 SCAR=27.8
1594 241 my $self = shift;
1595 241 ▶ my %params = (ref($_[0]) eq 'HASH') ? %{$_[0]} : @_;
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 234 7 241
1596  
1597 241 my $encoding = $params{encoding};
1598  
1599 # This can be called again after the links in the body have been changed,
1600 # by which time the body is no longer compressed
1601 241 delete $self->{_content_encoding};
1602 241 ▶ @{$self->{o}} = grep { !/^Content-Encoding:/ } @{$self->{o}} if($self->{o});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"o"} 54 187 241
1603  
1604 241 ▶ return unless(defined($self->{'body'}) && defined($encoding) && length($encoding));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"body"} and defined $encoding and length $encoding 227 14 241
Condition83%5/6
defined $self->{"body"} and defined $encoding and length $encoding
!ll&&!rl&&r
122614
defined $self->{"body"} and defined $encoding
!ll&&!rl&&r
01240
MC/DC66%2/3
defined $self->{"body"} and defined $encoding and length $encoding
defined $self->{"body"} defined $encoding length $encoding
Truth table75%3/4
A and B and C
A= defined $self->{"body"}B= defined $encodingC= length $encoding
ABCresult
0XX0
10X0
1100
1111
1605 14 ▶ return if(length($self->{body}) < $MIN_GZIP_LEN);
Branch: 1 branch
BranchTrueFalseTotal
if length $self->{"body"} < $MIN_GZIP_LEN 1 13 14
1606  
1607 # Premise: _should_gzip() only returns encodings whose module loads
1608 # Conclusion: if one can't be loaded here, the request can't be met
1609 13 my $module = $ENCODING_MODULE{$encoding};
1610 13 ▶ if((!defined($module)) || !_can_load($module)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $module and _can_load($module)) 1 12 13
Condition66%2/3
defined $module and _can_load($module)
!ll&&!rl&&r
1012
MC/DC50%1/2
defined $module and _can_load($module)
defined $module _can_load($module)
Truth table66%2/3
A and B
A= defined $moduleB= _can_load($module)
ABresult
0X0
100
111
1611 1 $self->_set_status(406);
1612 1 return;
1613 }
1614  
1615 # Avoid 'Wide character in memGzip'
1616 12 my $bytes = _to_bytes($self->{body});
1617 12 my $compressed;
1618 12 ▶ if($module eq 'Compress::Zlib') {
Branch: 2 branches
BranchTrueFalseTotal
if ($module eq 'Compress::Zlib') { } 11 1 12
elsif ($module eq 'Compress::Zstd') { } 0 1 1
1619 11 $compressed = Compress::Zlib::memGzip(\$bytes);
1620 } elsif($module eq 'Compress::Zstd') {
1621 # Facebook
1622 0 $compressed = Compress::Zstd::compress(\$bytes);
1623 } else {
1624 1 $compressed = IO::Compress::Brotli::bro($bytes);
1625 }
1626  
1627 # Don't send it compressed if that makes it larger
1628 12 ▶ return unless(defined($compressed) && (length($compressed) < length($bytes)));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $compressed and length $compressed < length $bytes 2 10 12
Condition66%2/3
defined $compressed and length $compressed < length $bytes
!ll&&!rl&&r
0210
MC/DC50%1/2
defined $compressed and length $compressed < length $bytes
defined $compressed length $compressed < length $bytes
Truth table66%2/3
A and B
A= defined $compressedB= length $compressed < length $bytes
ABresult
0X0
100
111
1629  
1630 10 $self->{body} = $compressed;
1631 10 ▶ $encoding = 'gzip' if($encoding eq 'x-gzip');
Branch: 1 branch
BranchTrueFalseTotal
if $encoding eq "x-gzip" 1 9 10
1632 10 $self->{_content_encoding} = $encoding;
1633 10 foreach my $header("Content-Encoding: $encoding", 'Vary: Accept-Encoding') {
1634 20 ▶ push @{$self->{o}}, $header unless(grep { $_ eq $header } @{$self->{o}});
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $header;} @{$$self{"o"};} 19 1 20
1635 }
1636 }
1637  
1638 21 ▶sub _check_if_none_match {
Subroutine _check_if_none_match: called CC=15 SCAR=27.4
1639 21 my $self = shift;
1640  
1641 21 ▶ if($ENV{'HTTP_IF_NONE_MATCH'} && defined($self->{etag})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{"HTTP_IF_NONE_MATCH"} and defined $self->{"etag"}) 19 2 21
Condition100%3/3
$ENV{"HTTP_IF_NONE_MATCH"} and defined $self->{"etag"}
!ll&&!rl&&r
1119
MC/DC100%2/2
$ENV{"HTTP_IF_NONE_MATCH"} and defined $self->{"etag"}
$ENV{"HTTP_IF_NONE_MATCH"} defined $self->{"etag"}
Truth table100%3/3
A and B
A= $ENV{"HTTP_IF_NONE_MATCH"}B= defined $self->{"etag"}
ABresult
0X0
100
111
1642 19 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 1 18 19
1643 1 $self->{logger}->debug("Compare $ENV{HTTP_IF_NONE_MATCH} with $self->{etag}");
1644 }
1645 # The header is "*" or a list of entity tags, any of which may be
1646 # weak. If-None-Match uses the weak comparison (RFC 9110 8.8.3.2),
1647 # under which the compressed version of a page matches
1648 19 my $matched = 0;
1649 19 foreach my $tag(split(/\s*,\s*/, $ENV{'HTTP_IF_NONE_MATCH'})) {
1650 20 (my $client_etag = $tag) =~ s/^W\///;
1651 20 (my $etag = $client_etag) =~ s/$ENCODED_ETAG_SUFFIX/"/;
1652 20 ▶ if($etag eq $self->{etag}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($etag eq $self->{"etag"}) 13 7 20
1653 13 $self->{_matched_etag} = $client_etag;
1654 13 $matched = 1;
1655 13 last;
1656 }
1657 7 ▶ $matched = 1 if($etag eq '*');
Branch: 1 branch
BranchTrueFalseTotal
if $etag eq "*" 1 6 7
1658 }
1659 19 ▶ if($matched) {
Branch: 1 branch
BranchTrueFalseTotal
if ($matched) 14 5 19
1660 # RFC 9110 13.1.2: 304 is only for GET and HEAD
1661 14 ▶ my $status = _is_safe_method() ? 304 : 412;
Branch: 1 branch
BranchTrueFalseTotal
_is_safe_method() ? : 13 1 14
1662 14 require HTTP::Status;
1663 14 push @{$self->{o}}, "Status: $status " . HTTP::Status::status_message($status);
1664 14 $self->{send_body} = 0;
1665 14 $self->_set_status($status);
1666 14 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 0 14 14
1667 0 $self->{logger}->debug("Set status to $status");
1668 }
1669 14 return 1;
1670 }
1671 }
1672 7 ▶ if($self->{cache} && $self->{logger} && $self->{logger}->can('is_debug') && $self->{logger}->is_debug() && _can_load('Text::Diff')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"} and $self->{"logger"} and $self->{"logger"}->can("is_debug") and $self->{"logger"}->is_debug and _can_load("Text::Diff")) 1 6 7
Condition75%9/12
$self->{"cache"} and $self->{"logger"} and $self->{"logger"}->can("is_debug") and $self->{"logger"}->is_debug and _can_load("Text::Diff")
!ll&&!rl&&r
601
$self->{"cache"} and $self->{"logger"} and $self->{"logger"}->can("is_debug") and $self->{"logger"}->is_debug
!ll&&!rl&&r
601
$self->{"cache"} and $self->{"logger"} and $self->{"logger"}->can("is_debug")
!ll&&!rl&&r
601
$self->{"cache"} and $self->{"logger"}
!ll&&!rl&&r
421
MC/DC40%2/5
$self->{"cache"} and $self->{"logger"} and $self->{"logger"}->can("is_debug") and $self->{"logger"}->is_debug and _can_load("Text::Diff")
$self->{"cache"} $self->{"logger"} $self->{"logger"}->can("is_debug") $self->{"logger"}->is_debug _can_load("Text::Diff")
Truth table50%3/6
A and B and C and D and E
A= $self->{"cache"}B= $self->{"logger"}C= $self->{"logger"}->can("is_debug")D= $self->{"logger"}->is_debugE= _can_load("Text::Diff")
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
1673 1 ▶ $self->_try('comparing with the cache', sub {
Subroutine __ANON__: called CC=3 SCAR=12.0
1674 1 my $cached_copy = $self->{cache}->get($self->_generate_key());
1675  
1676 1 ▶ if($cached_copy && $self->{body}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cached_copy and $self->{'body'}) { } 1 0 1
Condition33%1/3
$cached_copy and $self->{"body"}
!ll&&!rl&&r
001
MC/DC0%0/2
$cached_copy and $self->{"body"}
$cached_copy $self->{"body"}
Truth table33%1/3
A and B
A= $cached_copyB= $self->{"body"}
ABresult
0X0
100
111
1677 1 require Storable;
1678  
1679 1 $cached_copy = Storable::thaw($cached_copy)->{body};
1680 1 my $diffs = Text::Diff::diff(\$self->{body}, \$cached_copy);
1681 1 $self->{logger}->debug('diffs: ', $diffs);
1682 } else {
1683 0 $self->{logger}->debug('Nothing to compare');
1684 }
1685 1 });
1686 }
1687 7 return 0;
1688 }
1689  
1690 # Run some code which isn't essential to sending the page, e.g. something using
1691 # a cache or a database. If it fails, give a warning and return undef
1692 867 ▶sub _try {
Subroutine _try: called CC=2 SCAR=6.9
1693 867 my ($self, $what, $code) = @_;
1694  
1695 867 my $rc;
1696 867 ▶ return $rc if(eval { $rc = $code->(); 1 });
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { $rc = &$code(); 1 } } 859 8 867
1697 8 $self->_problem(__PACKAGE__ . ": $what failed: $@");
1698 8 return;
1699 }
1700  
1701 # Report something which has gone wrong. This can be called from anywhere, so
1702 # the logger itself may be the thing that's failing
1703 22 ▶sub _problem {
Subroutine _problem: called CC=3 SCAR=11.0
1704 22 my ($self, $message) = @_;
1705  
1706 22 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 14 8 22
1707 14 ▶ return if(eval { $self->{logger}->warn($message); 1 });
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { $self->{"logger"}->warn($message); 1 } } 14 0 14
1708 }
1709 # Must be Carp::carp instead of carp for Test::Carp
1710 8 Carp::carp($message);
1711 }
1712  
1713 # As _problem, for a problem which doesn't change from one request to the next
1714 {
1715 15 my %reported;
1716  
1717 15 ▶ sub _problem_once {
Subroutine _problem_once: called CC=2 SCAR=6.9
1718 15 my ($self, $message) = @_;
1719  
1720 15 ▶ $self->_problem($message) unless($reported{$message}++);
Branch: 1 branch
BranchTrueFalseTotal
unless $reported{$message}++ 10 5 15
1721 }
1722 }
1723  
1724 # Check that the logger can do what will be asked of it, otherwise forget it.
1725 # AUTOLOAD is taken on trust
1726 15 ▶sub _check_logger {
Subroutine _check_logger: called CC=5 SCAR=16.1
1727 26 my $self = shift;
1728  
1729 26 my $logger = $self->{logger};
1730 26 foreach my $method(@LOGGER_METHODS) {
1731 122 ▶ next if(Scalar::Util::blessed($logger) && ($logger->can($method) || $logger->can('AUTOLOAD')));
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($logger) and $logger->can($method) || $logger->can("AUTOLOAD") 120 2 122
Condition83%5/6
builtin::blessed($logger) and $logger->can($method) || $logger->can("AUTOLOAD")
!ll&&!rl&&r
11120
$logger->can($method) or $logger->can("AUTOLOAD")
l!l&&r!l&&!r
12001
MC/DC66%2/3
builtin::blessed($logger) and $logger->can($method) || $logger->can("AUTOLOAD")
builtin::blessed($logger) $logger->can($method) $logger->can("AUTOLOAD")
Truth table75%3/4
A and B or C
A= builtin::blessed($logger)B= $logger->can($method)C= $logger->can("AUTOLOAD")
ABCresult
0XX0
1000
11X1
1011
1732 2 delete $self->{logger};
1733 2 $self->_problem_once(__PACKAGE__ . ": The logger doesn't understand $method()");
1734 2 return;
1735 }
1736 }
1737  
1738 # Why this save_to argument to init() can't be used, or undef if it can
1739 110 ▶sub _save_to_problem {
Subroutine _save_to_problem: called CC=9 SCAR=22.0
1740 110 my ($self, $save_to) = @_;
1741  
1742 110 ▶ return 'save_to must be a hash reference' unless(ref($save_to) eq 'HASH');
Branch: 1 branch
BranchTrueFalseTotal
unless ref $save_to eq "HASH" 3 107 110
1743  
1744 107 my $dir = $save_to->{'directory'};
1745 107 ▶ return 'save_to needs a directory' unless(defined($dir) && length($dir));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dir and length $dir 1 106 107
Condition66%2/3
defined $dir and length $dir
!ll&&!rl&&r
10106
MC/DC50%1/2
defined $dir and length $dir
defined $dir length $dir
Truth table66%2/3
A and B
A= defined $dirB= length $dir
ABresult
0X0
100
111
1746  
1747 106 ▶ if(! -d $dir) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $dir) 42 64 106
1748 42 mkdir $dir;
1749 42 ▶ return "$dir isn't a directory" if(! -d $dir);
Branch: 1 branch
BranchTrueFalseTotal
unless -d $dir 2 40 42
1750 }
1751 104 ▶ return "$dir isn't writeable" if(! -w $dir);
Branch: 1 branch
BranchTrueFalseTotal
unless -w $dir 2 102 104
1752  
1753 # Premise 1: static pages are only of use if they can be linked to
1754 # Premise 2: this could otherwise only be noticed for each link in each page
1755 # Conclusion: say so now, and don't write pages that nothing can link to
1756 102 ▶ if($self->{info} && !defined($self->_path_to_url(File::Spec->catfile($dir, 'x')))) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"info"} and not defined $self->_path_to_url("File::Spec"->catfile($dir, "x"))) 3 99 102
Condition100%3/3
$self->{"info"} and not defined $self->_path_to_url("File::Spec"->catfile($dir, "x"))
!ll&&!rl&&r
2973
MC/DC100%2/2
$self->{"info"} and not defined $self->_path_to_url("File::Spec"->catfile($dir, "x"))
$self->{"info"} not defined $self->_path_to_url("File::Spec"->catfile($dir, "x"))
Truth table100%3/3
A and not(B)
A= $self->{"info"}B= not defined $self->_path_to_url("File::Spec"->catfile($dir, "x"))
ABresult
0X0
100
111
1757 3 return "$dir is not under the document root";
1758 }
1759 99 return;
1760 }
1761  
1762 # Connect to the save_to database, if there is one
1763 255 ▶sub _save_to_dbh {
Subroutine _save_to_dbh: called CC=7 SCAR=19.5
1764 255 my $self = shift;
1765  
1766 255 my $save_to = $self->{save_to};
1767 255 ▶ return unless($save_to);
Branch: 1 branch
BranchTrueFalseTotal
unless $save_to 158 97 255
1768  
1769 97 my $sqlite_file = File::Spec->catfile($save_to->{directory}, $SAVE_TO_DATABASE);
1770 97 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 11 86 97
1771 11 $self->{logger}->debug("save_to sqlite file: $sqlite_file");
1772 }
1773 97 my $is_new = !-r $sqlite_file;
1774 97 ▶ if($is_new && !-d $save_to->{directory}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_new and not -d $save_to->{"directory"}) 0 97 97
Condition66%2/3
$is_new and not -d $save_to->{"directory"}
!ll&&!rl&&r
55420
MC/DC0%0/2
$is_new and not -d $save_to->{"directory"}
$is_new not -d $save_to->{"directory"}
Truth table66%2/3
A and not(B)
A= $is_newB= not -d $save_to->{"directory"}
ABresult
0X0
100
111
1775 0 mkdir $save_to->{directory};
1776 }
1777 97 require DBD::SQLite;
1778 97 my $dbh = DBI->connect("dbi:SQLite:dbname=$sqlite_file", undef, undef, { RaiseError => 1, PrintError => 0 });
1779 97 ▶ if($is_new && $save_to->{create_table}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_new and $save_to->{"create_table"}) 41 56 97
Condition100%3/3
$is_new and $save_to->{"create_table"}
!ll&&!rl&&r
55141
MC/DC100%2/2
$is_new and $save_to->{"create_table"}
$is_new $save_to->{"create_table"}
Truth table100%3/3
A and B
A= $is_newB= $save_to->{"create_table"}
ABresult
0X0
100
111
1780 # Another process can get in between the two lines above
1781 41 $dbh->do('CREATE TABLE IF NOT EXISTS fcgi_buffer(key char PRIMARY KEY, language char, browser_type char, path char UNIQUE NOT NULL, uri char NOT NULL, creation timestamp NOT NULL)');
1782 }
1783 97 return $dbh;
1784 }
1785  
1786 # Look for an entry in the cache that can still be used. A failing cache is the
1787 # same as an empty one.
1788 # CHI's get_object() returns an object even if it has expired
1789 196 ▶sub _cache_lookup {
Subroutine _cache_lookup: called CC=5 SCAR=16.3
1790 196 my ($self, $key) = @_;
1791  
1792 196 ▶ my $object = $self->_try('reading the cache', sub { return $self->{cache}->get_object($key) });
Subroutine __ANON__: called CC=1 SCAR=0.0
1793 196 ▶ return unless(defined($object));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $object 33 163 196
1794 163 ▶ if($object->can('is_expired') && $object->is_expired()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($object->can("is_expired") and $object->is_expired) 1 162 163
Condition66%2/3
$object->can("is_expired") and $object->is_expired
!ll&&!rl&&r
01621
MC/DC50%1/2
$object->can("is_expired") and $object->is_expired
$object->can("is_expired") $object->is_expired
Truth table66%2/3
A and B
A= $object->can("is_expired")B= $object->is_expired
ABresult
0X0
100
111
1795 1 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 0 1 1
1796 0 $self->{logger}->debug("$key has expired");
1797 }
1798 1 return;
1799 }
1800 162 return $object;
1801 }
1802  
1803 # A string as bytes: a string of characters is encoded, bytes are left alone
1804 735 ▶sub _to_bytes {
Subroutine _to_bytes: called CC=3 SCAR=11.0
1805 735 my $string = shift;
1806  
1807 735 ▶ utf8::encode($string) if(defined($string) && utf8::is_utf8($string));
Branch: 1 branch
BranchTrueFalseTotal
if defined $string and utf8::is_utf8($string) 3 732 735
Condition100%3/3
defined $string and utf8::is_utf8($string)
!ll&&!rl&&r
17313
MC/DC100%2/2
defined $string and utf8::is_utf8($string)
defined $string utf8::is_utf8($string)
Truth table100%3/3
A and B
A= defined $stringB= utf8::is_utf8($string)
ABresult
0X0
100
111
1808 735 return $string;
1809 }
1810  
1811 # Is the output an HTML page?
1812 285 ▶sub _is_html {
Subroutine _is_html: called CC=5 SCAR=16.6
1813 285 my $self = shift;
1814  
1815 285 my $content_type = $self->{content_type};
1816 285 ▶ return 0 unless(defined($content_type) && defined($content_type->[1]));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $content_type and defined $content_type->[1] 0 285 285
Condition33%1/3
defined $content_type and defined $content_type->[1]
!ll&&!rl&&r
00285
MC/DC0%0/2
defined $content_type and defined $content_type->[1]
defined $content_type defined $content_type->[1]
Truth table33%1/3
A and B
A= defined $content_typeB= defined $content_type->[1]
ABresult
0X0
100
111
1817 285 ▶ return ((lc($content_type->[0]) eq 'text') && (lc($content_type->[1]) =~ /^html/)) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
lc $content_type->[0] eq 'text' && lc($content_type->[1]) =~ /^html/ ? : 278 7 285
Condition100%3/3
lc $content_type->[0] eq "text" and lc($content_type->[1]) =~ /^html/
!ll&&!rl&&r
61278
MC/DC100%2/2
lc $content_type->[0] eq "text" and lc($content_type->[1]) =~ /^html/
lc $content_type->[0] eq "text" lc($content_type->[1]) =~ /^html/
Truth table100%3/3
A and B
A= lc $content_type->[0] eq "text"B= lc($content_type->[1]) =~ /^html/
ABresult
0X0
100
111
1818 }
1819  
1820 # The values of a header in a block of headers
1821 473 ▶sub _header_values {
Subroutine _header_values: called CC=3 SCAR=11.3
1822 473 my ($headers, $name) = @_;
1823  
1824 473 ▶ return () unless(defined($headers));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $headers 0 473 473
1825 473 ▶ return map { /^[^:]+:\s*(.*?)\s*$/ ? $1 : () } grep { /^\Q$name\E:/i } split(/\r?\n/, $headers);
Branch: 1 branch
BranchTrueFalseTotal
/^[^:]+:\s*(.*?)\s*$/ ? : 9 0 9
1826 }
1827  
1828 # May this response be kept and given to other clients?
1829 121 ▶sub _is_storable {
Subroutine _is_storable: called CC=18 SCAR=29.0
1830 121 my ($self, $headers, $body) = @_;
1831  
1832 # It would log the next client in as this one
1833 121 ▶ return 0 if(_header_values($headers, 'Set-Cookie') || _header_values($headers, 'Set-Cookie2'));
Branch: 1 branch
BranchTrueFalseTotal
if _header_values($headers, "Set-Cookie") or _header_values($headers, "Set-Cookie2") 1 120 121
Condition66%2/3
_header_values($headers, "Set-Cookie") or _header_values($headers, "Set-Cookie2")
l!l&&r!l&&!r
10120
MC/DC50%1/2
_header_values($headers, "Set-Cookie") or _header_values($headers, "Set-Cookie2")
_header_values($headers, "Set-Cookie") _header_values($headers, "Set-Cookie2")
Truth table66%2/3
A or B
A= _header_values($headers, "Set-Cookie")B= _header_values($headers, "Set-Cookie2")
ABresult
1X1
011
000
1834  
1835 # It would give this client's form token to the next one
1836 120 ▶ return 0 if(_has_form_token($body));
Branch: 1 branch
BranchTrueFalseTotal
if _has_form_token($body) 2 118 120
1837  
1838 118 foreach my $control(_header_values($headers, 'Cache-Control')) {
1839 4 foreach my $directive(split(/\s*,\s*/, lc($control))) {
1840 5 (my $name = $directive) =~ s/\s*=.*$//;
1841 5 ▶ return 0 if($NO_CACHE_DIRECTIVES{$name});
Branch: 1 branch
BranchTrueFalseTotal
if $NO_CACHE_DIRECTIVES{$name} 3 2 5
1842 }
1843 }
1844  
1845 # The cache holds the uncompressed version, so this can't be stored
1846 115 ▶ return 0 if($self->{_script_encoded});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_script_encoded"} 1 114 115
1847  
1848 # Accept-Encoding is dealt with here, and lingua is part of the key
1849 114 foreach my $vary(_header_values($headers, 'Vary')) {
1850 4 foreach my $name(split(/\s*,\s*/, lc($vary))) {
1851 4 ▶ next if($name eq 'accept-encoding');
Branch: 1 branch
BranchTrueFalseTotal
if $name eq "accept-encoding" 1 3 4
1852 3 ▶ next if(($name eq 'accept-language') && $self->{lingua});
Branch: 1 branch
BranchTrueFalseTotal
if $name eq "accept-language" and $self->{"lingua"} 1 2 3
Condition100%3/3
$name eq "accept-language" and $self->{"lingua"}
!ll&&!rl&&r
111
MC/DC100%2/2
$name eq "accept-language" and $self->{"lingua"}
$name eq "accept-language" $self->{"lingua"}
Truth table100%3/3
A and B
A= $name eq "accept-language"B= $self->{"lingua"}
ABresult
0X0
100
111
1853 2 return 0;
1854 }
1855 }
1856  
1857 # Perl doesn't tell a destructor that it's being called because of a die,
1858 # but this is what the page will look like if that has happened
1859 112 ▶ if($self->_is_html() && defined($body) && ($body =~ /<html\b/i) && ($body !~ /<\/html\s*+>/i)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_is_html and defined $body and $body =~ /<html\b/i and not $body =~ m[</html\s*+>]i) 1 111 112
Condition88%8/9
$self->_is_html and defined $body and $body =~ /<html\b/i and not $body =~ m[</html\s*+>]i
!ll&&!rl&&r
16951
$self->_is_html and defined $body and $body =~ /<html\b/i
!ll&&!rl&&r
31396
$self->_is_html and defined $body
!ll&&!rl&&r
30109
MC/DC75%3/4
$self->_is_html and defined $body and $body =~ /<html\b/i and not $body =~ m[</html\s*+>]i
$self->_is_html defined $body $body =~ /<html\b/i not $body =~ m[</html\s*+>]i
Truth table80%4/5
A and B and C and not(D)
A= $self->_is_htmlB= defined $bodyC= $body =~ /<html\b/iD= not $body =~ m[</html\s*+>]i
ABCDresult
0XXX0
10XX0
110X0
11100
11111
1860 1 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 0 1 1
1861 0 $self->{logger}->debug('Not storing an HTML page with no </html>');
1862 }
1863 1 return 0;
1864 }
1865 111 return 1;
1866 }
1867  
1868 # Stop the regular expressions from changing the contents of <pre> and <textarea>
1869 # by swapping them for a marker. Returns what's needed to put them back.
1870 # The end of a tag is only looked for once if it isn't there, so that hostile
1871 # input can't make this quadratic
1872 41 ▶sub _protect_preformatted {
Subroutine _protect_preformatted: called CC=4 SCAR=13.9
1873 41 my $self = shift;
1874  
1875 41 my $body = $self->{body};
1876 41 my $marker = 'FCGIBUFFERPRESERVED' . int(rand(1_000_000_000)) . 'N';
1877 41 my (@saved, %no_end);
1878 41 my $out = '';
1879 41 my $last = 0;
1880  
1881 41 ▶ while($body =~ /<(pre|textarea)\b/gi) {
Branch: 1 branch
BranchTrueFalseTotal
if ($body =~ /<(pre|textarea)\b/gi) 200006 41 200047
1882 200006 my $tag = lc($1);
1883 200006 my $start = $-[0];
1884 200006 my $after = pos($body);
1885  
1886 200006 ▶ next if($no_end{$tag});
Branch: 1 branch
BranchTrueFalseTotal
if $no_end{$tag} 149997 50009 200006
1887 50009 ▶ unless($body =~ /<\/$tag\s*+>/gi) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($body =~ m[</$tag\s*+>]gi) 5 50004 50009
1888 5 $no_end{$tag} = 1;
1889 5 pos($body) = $after;
1890 5 next;
1891 }
1892 50004 my $end = $+[0];
1893 50004 push @saved, substr($body, $start, $end - $start);
1894 50004 $out .= substr($body, $last, $start - $last) . $marker . $#saved . 'X';
1895 50004 $last = $end;
1896 50004 pos($body) = $end;
1897 }
1898 41 $self->{body} = $out . substr($body, $last);
1899 41 return { marker => $marker, saved => \@saved };
1900 }
1901  
1902 # Put back what _protect_preformatted() took out
1903 41 ▶sub _restore_preformatted {
Subroutine _restore_preformatted: called CC=2 SCAR=6.9
1904 41 my ($self, $preformatted) = @_;
1905  
1906 41 my $saved = $preformatted->{'saved'};
1907 41 ▶ $self->{body} =~ s/\Q$preformatted->{marker}\E(\d+)X/$saved->[$1]/g if(scalar(@{$saved}));
Branch: 1 branch
BranchTrueFalseTotal
if scalar @{$saved;} 3 38 41
1908 }
1909  
1910 # Tell caches that what's sent depends on what the client accepts. This is also
1911 # needed when the output isn't compressed, or that's what a cache would then give
1912 # to clients that can take it compressed
1913 255 ▶sub _add_vary {
Subroutine _add_vary: called CC=10 SCAR=23.0
1914 255 my ($self, $headers) = @_;
1915  
1916 255 ▶ return unless(defined($headers) && length($headers));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $headers and length $headers 1 254 255
Condition66%2/3
defined $headers and length $headers
!ll&&!rl&&r
01254
MC/DC50%1/2
defined $headers and length $headers
defined $headers length $headers
Truth table66%2/3
A and B
A= defined $headersB= length $headers
ABresult
0X0
100
111
1917 254 ▶ return unless($self->{compress_content} && defined($self->{body}) && !$self->{_script_encoded});
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"compress_content"} and defined $self->{"body"} and not $self->{"_script_encoded"} 6 248 254
Condition100%6/6
$self->{"compress_content"} and defined $self->{"body"} and not $self->{"_script_encoded"}
!ll&&!rl&&r
51248
$self->{"compress_content"} and defined $self->{"body"}
!ll&&!rl&&r
14249
MC/DC100%3/3
$self->{"compress_content"} and defined $self->{"body"} and not $self->{"_script_encoded"}
$self->{"compress_content"} defined $self->{"body"} not $self->{"_script_encoded"}
Truth table100%4/4
A and B and not(C)
A= $self->{"compress_content"}B= defined $self->{"body"}C= not $self->{"_script_encoded"}
ABCresult
0XX0
10X0
1100
1111
1918 248 ▶ return if(defined($self->{content_type}) && (lc($self->{content_type}->[0]) ne 'text'));
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"content_type"} and lc $self->{"content_type"}[0] ne "text" 3 245 248
Condition100%3/3
defined $self->{"content_type"} and lc $self->{"content_type"}[0] ne "text"
!ll&&!rl&&r
32423
MC/DC100%2/2
defined $self->{"content_type"} and lc $self->{"content_type"}[0] ne "text"
defined $self->{"content_type"} lc $self->{"content_type"}[0] ne "text"
Truth table100%3/3
A and B
A= defined $self->{"content_type"}B= lc $self->{"content_type"}[0] ne "text"
ABresult
0X0
100
111
1919 245 ▶ return if($headers =~ /^Vary:.*\baccept-encoding\b/mi);
Branch: 1 branch
BranchTrueFalseTotal
if $headers =~ /^Vary:.*\baccept-encoding\b/im 2 243 245
1920 243 ▶ return if(grep { /^Vary:.*\baccept-encoding\b/i } @{$self->{o}});
Branch: 1 branch
BranchTrueFalseTotal
if grep {/^Vary:.*\baccept-encoding\b/i;} @{$$self{"o"};} 8 235 243
1921 235 push @{$self->{o}}, 'Vary: Accept-Encoding';
1922 }
1923  
1924 # Send one Status header, that of the status we've ended up with, keeping the
1925 # script's one if it's the same since it may have its own wording
1926 254 ▶sub _set_status_header {
Subroutine _set_status_header: called CC=5 SCAR=16.1
1927 254 my $self = shift;
1928  
1929 254 my $status = $self->{status};
1930 254 my $found = 0;
1931 254 @{$self->{o}} = grep {
1932 1826 my $keep = 1;
1933 1826 ▶ if(/^Status:\s*(\d+)/i) {
Branch: 1 branch
BranchTrueFalseTotal
if (/^Status:\s*(\d+)/i) 25 1801 1826
1934 25 ▶ $keep = (!$found) && ($1 == $status);
Condition66%2/3
!$found && $1 == $status
!ll&&!rl&&r
0223
MC/DC50%1/2
!$found && $1 == $status
!$found $1 == $status
Truth table66%2/3
not(A) && B
A= !$foundB= $1 == $status
ABresult
0X0
100
111
1935 25 ▶ $found ||= $keep;
Condition66%2/3
$found ||= $keep
l!l&&r!l&&!r
0232
MC/DC50%1/2
$found ||= $keep
$found $keep
Truth table66%2/3
A ||= B
A= $foundB= $keep
ABresult
1X1
011
000
1936 }
1937 $keep
1938 254 } @{$self->{o}};
1939  
1940 254 ▶ unless($found) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($found) 231 23 254
1941 231 require HTTP::Status;
1942 231 HTTP::Status->import();
1943  
1944 231 push @{$self->{o}}, 'Status: ' . $status . ' ' . HTTP::Status::status_message($status);
1945 231 $self->_set_status($status);
1946 }
1947 }
1948  
1949 # If-Range asks for a part only if the client's copy is the current one
1950 # (RFC 9110 14.5), which needs an exact match of a strong validator
1951 18 ▶sub _if_range_matches {
Subroutine _if_range_matches: called CC=10 SCAR=23.7
1952 18 my $self = shift;
1953  
1954 18 my $if_range = $ENV{'HTTP_IF_RANGE'};
1955 18 ▶ return 1 unless(defined($if_range) && length($if_range));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $if_range and length $if_range 13 5 18
Condition66%2/3
defined $if_range and length $if_range
!ll&&!rl&&r
1305
MC/DC50%1/2
defined $if_range and length $if_range
defined $if_range length $if_range
Truth table66%2/3
A and B
A= defined $if_rangeB= length $if_range
ABresult
0X0
100
111
1956  
1957 5 ▶ if($if_range =~ /^(?:W\/)?"/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($if_range =~ m[^(?:W/)?"]) 3 2 5
1958 3 $self->_generate_etag();
1959 3 ▶ return (defined($self->{etag}) && ($if_range eq $self->{etag})) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'etag'} && $if_range eq $self->{'etag'} ? : 1 2 3
Condition66%2/3
defined $self->{"etag"} and $if_range eq $self->{"etag"}
!ll&&!rl&&r
021
MC/DC50%1/2
defined $self->{"etag"} and $if_range eq $self->{"etag"}
defined $self->{"etag"} $if_range eq $self->{"etag"}
Truth table66%2/3
A and B
A= defined $self->{"etag"}B= $if_range eq $self->{"etag"}
ABresult
0X0
100
111
1960 }
1961 2 my $since = HTTP::Date::str2time($if_range);
1962 2 ▶ return 0 unless(defined($since) && $self->{info});
Branch: 1 branch
BranchTrueFalseTotal
unless defined $since and $self->{"info"} 0 2 2
Condition33%1/3
defined $since and $self->{"info"}
!ll&&!rl&&r
002
MC/DC0%0/2
defined $since and $self->{"info"}
defined $since $self->{"info"}
Truth table33%1/3
A and B
A= defined $sinceB= $self->{"info"}
ABresult
0X0
100
111
1963 2 my $age = $self->_my_age();
1964 2 ▶ return (defined($age) && ($age == $since)) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $age && $age == $since ? : 1 1 2
Condition66%2/3
defined $age and $age == $since
!ll&&!rl&&r
011
MC/DC50%1/2
defined $age and $age == $since
defined $age $age == $since
Truth table66%2/3
A and B
A= defined $ageB= $age == $since
ABresult
0X0
100
111
1965 }
1966  
1967 # The CGI::Info object, which is created if it wasn't given
1968 286 ▶sub _info {
Subroutine _info: called CC=4 SCAR=13.9
1969 286 my $self = shift;
1970  
1971 286 ▶ if(!defined($self->{info})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"info"}) 34 252 286
1972 34 ▶ $self->{info} = CGI::Info->new($self->{cache} ? { cache => $self->{cache} } : ())
Branch: 2 branches
BranchTrueFalseTotal
$self->{"info"} = "CGI::Info"->new($self->{"cache"} ? {"cache", $self->{"cache"}} : ()) or croak(__PACKAGE__, ": Failed to create CGI::Info object") 34 0 34
$self->{'cache'} ? : 4 30 34
1973 or croak(__PACKAGE__, ': Failed to create CGI::Info object');
1974 }
1975 286 return $self->{info};
1976 }
1977  
1978 # Set the HTTP status, and tell CGI::Info if we have one
1979 267 ▶sub _set_status {
Subroutine _set_status: called CC=2 SCAR=6.9
1980 267 my ($self, $status) = @_;
1981  
1982 267 $self->{status} = $status;
1983 267 ▶ if($self->{info}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"info"}) 231 36 267
1984 231 $self->{info}->status($status);
1985 }
1986 }
1987  
1988 # Does the protocol support conditional requests (ETag etc.)?
1989 468 ▶sub _is_conditional_protocol {
Subroutine _is_conditional_protocol: called CC=2 SCAR=6.9
1990 468 ▶ return defined($ENV{'SERVER_PROTOCOL'}) && ($ENV{'SERVER_PROTOCOL'} =~ $CONDITIONAL_PROTOCOL);
Condition100%3/3
defined $ENV{'SERVER_PROTOCOL'} && $ENV{'SERVER_PROTOCOL'} =~ /$CONDITIONAL_PROTOCOL/
!ll&&!rl&&r
1434321
MC/DC100%2/2
defined $ENV{'SERVER_PROTOCOL'} && $ENV{'SERVER_PROTOCOL'} =~ /$CONDITIONAL_PROTOCOL/
defined $ENV{'SERVER_PROTOCOL'} $ENV{'SERVER_PROTOCOL'} =~ /$CONDITIONAL_PROTOCOL/
Truth table100%3/3
A && B
A= defined $ENV{'SERVER_PROTOCOL'}B= $ENV{'SERVER_PROTOCOL'} =~ /$CONDITIONAL_PROTOCOL/
ABresult
0X0
100
111
1991 }
1992  
1993 # Is the request one that can be answered from a cache or with a 304?
1994 # There is no method when running from the command line
1995 217 ▶sub _is_safe_method {
Subroutine _is_safe_method: called CC=2 SCAR=6.9
1996 217 ▶ return (!defined($ENV{'REQUEST_METHOD'})) || $SAFE_METHODS{$ENV{'REQUEST_METHOD'}};
Condition100%3/3
!defined($ENV{'REQUEST_METHOD'}) || $SAFE_METHODS{$ENV{'REQUEST_METHOD'}}
l!l&&r!l&&!r
151975
MC/DC100%2/2
!defined($ENV{'REQUEST_METHOD'}) || $SAFE_METHODS{$ENV{'REQUEST_METHOD'}}
!defined($ENV{'REQUEST_METHOD'}) $SAFE_METHODS{$ENV{'REQUEST_METHOD'}}
Truth table100%3/3
not(A) || B
A= !defined($ENV{'REQUEST_METHOD'})B= $SAFE_METHODS{$ENV{'REQUEST_METHOD'}}
ABresult
1X1
011
000
1997 }
1998  
1999 19 ▶sub _is_get {
Subroutine _is_get: called CC=2 SCAR=7.2
2000 19 ▶ return (!defined($ENV{'REQUEST_METHOD'})) || ($ENV{'REQUEST_METHOD'} eq 'GET');
Condition66%2/3
!defined($ENV{'REQUEST_METHOD'}) || $ENV{'REQUEST_METHOD'} eq 'GET'
l!l&&r!l&&!r
0181
MC/DC50%1/2
!defined($ENV{'REQUEST_METHOD'}) || $ENV{'REQUEST_METHOD'} eq 'GET'
!defined($ENV{'REQUEST_METHOD'}) $ENV{'REQUEST_METHOD'} eq 'GET'
Truth table66%2/3
not(A) || B
A= !defined($ENV{'REQUEST_METHOD'})B= $ENV{'REQUEST_METHOD'} eq 'GET'
ABresult
1X1
011
000
2001 }
2002  
2003 259 ▶sub _is_logged_in {
Subroutine _is_logged_in: called CC=2 SCAR=6.9
2004 259 ▶ return $ENV{'HTTP_AUTHORIZATION'} || $ENV{'REMOTE_USER'};
Condition100%3/3
$ENV{'HTTP_AUTHORIZATION'} || $ENV{'REMOTE_USER'}
l!l&&r!l&&!r
11257
MC/DC100%2/2
$ENV{'HTTP_AUTHORIZATION'} || $ENV{'REMOTE_USER'}
$ENV{'HTTP_AUTHORIZATION'} $ENV{'REMOTE_USER'}
Truth table100%3/3
A || B
A= $ENV{'HTTP_AUTHORIZATION'}B= $ENV{'REMOTE_USER'}
ABresult
1X1
011
000
2005 }
2006  
2007 # The client's cookies, except for Google Analytics ones and the token that
2008 # protects forms, which are different for each client but don't change the output.
2009 # A page with a form is sent that token in a Set-Cookie header, so _is_storable()
2010 # doesn't store it
2011 210 ▶sub _client_cookies {
Subroutine _client_cookies: called CC=2 SCAR=6.9
2012 210 ▶ return () unless($ENV{'HTTP_COOKIE'});
Branch: 1 branch
BranchTrueFalseTotal
unless $ENV{"HTTP_COOKIE"} 195 15 210
2013 15 return grep { !/^(?:__utm[abcz]|\Q$FORM_TOKEN_COOKIE\E=)/ } split(/;\s*/, $ENV{'HTTP_COOKIE'});
2014 }
2015  
2016 # Does this page include the client's own form token? _client_cookies() ignores
2017 # the cookie that holds it, on the understanding that it doesn't change the output.
2018 # A script that puts its value into the page has made the page per client
2019 120 ▶sub _has_form_token {
Subroutine _has_form_token: called CC=8 SCAR=20.8
2020 120 my $body = shift;
2021  
2022 120 ▶ return 0 unless($ENV{'HTTP_COOKIE'} && defined($body));
Branch: 1 branch
BranchTrueFalseTotal
unless $ENV{"HTTP_COOKIE"} and defined $body 110 10 120
Condition66%2/3
$ENV{"HTTP_COOKIE"} and defined $body
!ll&&!rl&&r
110010
MC/DC50%1/2
$ENV{"HTTP_COOKIE"} and defined $body
$ENV{"HTTP_COOKIE"} defined $body
Truth table66%2/3
A and B
A= $ENV{"HTTP_COOKIE"}B= defined $body
ABresult
0X0
100
111
2023  
2024 10 foreach my $cookie(split(/;\s*/, $ENV{'HTTP_COOKIE'})) {
2025 12 ▶ next unless($cookie =~ /^\Q$FORM_TOKEN_COOKIE\E=(.+)$/);
Branch: 1 branch
BranchTrueFalseTotal
unless $cookie =~ /^\Q$FORM_TOKEN_COOKIE\E=(.+)$/ 5 7 12
2026 7 my $token = $1;
2027 7 ▶ return 1 if(index($body, $token) >= 0);
Branch: 1 branch
BranchTrueFalseTotal
if (index($body, $token) != -1) 1 6 7
2028 # The cookie may be encoded, what's printed may not be
2029 6 ▶ if($token =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/ge) {
Branch: 1 branch
BranchTrueFalseTotal
if ($token =~ s/%([0-9A-Fa-f]{2})/chr hex $1;/eg) 1 5 6
2030 1 ▶ return 1 if(index($body, $token) >= 0);
Branch: 1 branch
BranchTrueFalseTotal
if (index($body, $token) != -1) 1 0 1
2031 }
2032 }
2033 8 return 0;
2034 }
2035  
2036 # Does the output depend on who the client is?
2037 # Separate from the key since the key may have been given to us by the caller
2038 75 ▶sub _is_per_client {
Subroutine _is_per_client: called CC=2 SCAR=7.6
2039 75 ▶ return _is_logged_in() || scalar(_client_cookies());
Condition50%1/2
_is_logged_in() || scalar _client_cookies()
l!l
075
MC/DC0%0/1
_is_logged_in() || scalar _client_cookies()
_is_logged_in()
Truth table50%1/2
A
A= _is_logged_in()
Aresult
11
00
2040 }
2041  
2042 # The directives in the request's Cache-Control header, as a hashref of
2043 # lower case name to value (undef when there is no value)
2044 544 ▶sub _cache_control {
Subroutine _cache_control: called CC=6 SCAR=18.2
2045 544 my %directives;
2046  
2047 544 ▶ if(defined(my $control = $ENV{'HTTP_CACHE_CONTROL'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $control = $ENV{"HTTP_CACHE_CONTROL"})) 35 509 544
2048 35 foreach my $directive(split(/\s*,\s*/, lc($control))) {
2049 37 my ($name, $value) = split(/\s*=\s*/, $directive, 2);
2050 37 ▶ next unless(defined($name) && length($name));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 0 37 37
Condition33%1/3
defined $name and length $name
!ll&&!rl&&r
0037
MC/DC0%0/2
defined $name and length $name
defined $name length $name
Truth table33%1/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
2051 37 ▶ $value =~ s/^"(.*)"$/$1/ if(defined($value));
Branch: 1 branch
BranchTrueFalseTotal
if defined $value 27 10 37
2052 37 $directives{$name} = $value;
2053 }
2054 }
2055 544 return \%directives;
2056 }
2057  
2058 # The max-age directive in the request, or undef if there isn't a valid one.
2059 # This comes from the client, so it mustn't be trusted to be a number
2060 351 ▶sub _client_max_age {
Subroutine _client_max_age: called CC=3 SCAR=11.0
2061 351 my $max_age = _cache_control()->{'max-age'};
2062  
2063 351 ▶ return (defined($max_age) && ($max_age =~ /^\d+$/)) ? $max_age : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $max_age && $max_age =~ /^\d+$/ ? : 13 338 351
Condition100%3/3
defined $max_age and $max_age =~ /^\d+$/
!ll&&!rl&&r
334413
MC/DC100%2/2
defined $max_age and $max_age =~ /^\d+$/
defined $max_age $max_age =~ /^\d+$/
Truth table100%3/3
A and B
A= defined $max_ageB= $max_age =~ /^\d+$/
ABresult
0X0
100
111
2064 }
2065  
2066 # The X-Cache and X-Cache-Lookup headers, as an arrayref
2067 257 ▶sub _x_cache_headers {
Subroutine _x_cache_headers: called CC=2 SCAR=6.9
2068 257 my ($self, $cache, $lookup) = @_;
2069  
2070 257 ▶ my $from = $self->{info} ? ' from ' . $self->{info}->host_name() : '';
Branch: 1 branch
BranchTrueFalseTotal
$self->{'info'} ? : 229 28 257
2071 257 return [ "X-Cache: $cache$from", "X-Cache-Lookup: $lookup$from" ];
2072 }
2073  
2074 # Work out the response to a Range header, as a hashref of the new status,
2075 # body and Content-Range header, or undef if the range isn't one that we
2076 # support, in which case the header is ignored and the whole body is sent.
2077 # Only a single range of bytes is supported.
2078 # 206: the part of the body asked for
2079 # 416: a valid range which is outside of the body, so has no body
2080 32 ▶sub _apply_range {
Subroutine _apply_range: called CC=13 SCAR=25.7
2081 32 my ($body, $range) = @_;
2082  
2083 32 ▶ return unless($range =~ /^bytes=(\d*)-(\d*)$/);
Branch: 1 branch
BranchTrueFalseTotal
unless $range =~ /^bytes=(\d*)-(\d*)$/ 3 29 32
2084 29 my ($first, $last) = ($1, $2);
2085 29 my $length = length($body);
2086  
2087 # "bytes=-" says nothing
2088 29 ▶ return if(($first eq '') && ($last eq ''));
Branch: 1 branch
BranchTrueFalseTotal
if $first eq "" and $last eq "" 1 28 29
Condition100%3/3
$first eq "" and $last eq ""
!ll&&!rl&&r
2171
MC/DC100%2/2
$first eq "" and $last eq ""
$first eq "" $last eq ""
Truth table100%3/3
A and B
A= $first eq ""B= $last eq ""
ABresult
0X0
100
111
2089  
2090 # A backwards range is invalid, so is ignored (RFC 7233 2.1)
2091 28 ▶ return if(($first ne '') && ($last ne '') && ($first > $last));
Branch: 1 branch
BranchTrueFalseTotal
if $first ne "" and $last ne "" and $first > $last 3 25 28
Condition100%6/6
$first ne "" and $last ne "" and $first > $last
!ll&&!rl&&r
13123
$first ne "" and $last ne ""
!ll&&!rl&&r
7615
MC/DC100%3/3
$first ne "" and $last ne "" and $first > $last
$first ne "" $last ne "" $first > $last
Truth table100%4/4
A and B and C
A= $first ne ""B= $last ne ""C= $first > $last
ABCresult
0XX0
10X0
1100
1111
2092  
2093 25 ▶ if($first eq '') {
Branch: 2 branches
BranchTrueFalseTotal
if ($first eq '') { } 7 18 25
elsif ($last eq '' or $last >= $length) { } 8 10 18
2094 # "bytes=-n" is the last n bytes, all of it if there are
2095 # fewer than n
2096 7 ▶ $first = ($last >= $length) ? 0 : $length - $last;
Branch: 1 branch
BranchTrueFalseTotal
$last >= $length ? : 3 4 7
2097 7 $last = $length - 1;
2098 # Premise 1: the last 0 bytes is an empty range
2099 # Premise 2: so is any range of an empty body
2100 # Conclusion: both leave $first > $last, and can't be satisfied
2101 ▶ } elsif(($last eq '') || ($last >= $length)) {
Condition100%3/3
$last eq "" or $last >= $length
l!l&&r!l&&!r
6210
MC/DC100%2/2
$last eq "" or $last >= $length
$last eq "" $last >= $length
Truth table100%3/3
A or B
A= $last eq ""B= $last >= $length
ABresult
1X1
011
000
2102 # A range past the end stops at the end
2103 8 $last = $length - 1;
2104 }
2105  
2106 # A range starting at or after the end can't be satisfied
2107 25 ▶ if(($first >= $length) || ($first > $last)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($first >= $length or $first > $last) 5 20 25
Condition66%2/3
$first >= $length or $first > $last
l!l&&r!l&&!r
5020
MC/DC50%1/2
$first >= $length or $first > $last
$first >= $length $first > $last
Truth table66%2/3
A or B
A= $first >= $lengthB= $first > $last
ABresult
1X1
011
000
2108 5 return { status => 416, content_range => "bytes */$length" };
2109 }
2110  
2111 return {
2112 20 status => 206,
2113 body => substr($body, $first, $last - $first + 1),
2114 content_range => "bytes $first-$last/$length",
2115 };
2116 }
2117  
2118 # Create the static page for this request
2119 72 ▶sub _write_static_page {
Subroutine _write_static_page: called CC=20 SCAR=30.1
2120 72 my ($self, $key, $unzipped_body, $dbh, $request_uri) = @_;
2121  
2122 72 my $ttl = $self->{save_to}->{ttl};
2123 72 my $query = 'SELECT DISTINCT creation FROM fcgi_buffer WHERE key = ?';
2124 72 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 10 62 72
2125 10 $self->{logger}->debug("$query: $key");
2126 }
2127 72 my ($creation) = $dbh->selectrow_array($query, undef, $key);
2128  
2129 # A page that has passed its ttl is replaced, it would otherwise never
2130 # be updated
2131 70 ▶ if(defined($creation) && ((!$ttl) || (($creation + $ttl) >= time))) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $creation and !$ttl || $creation + $ttl >= time) 6 64 70
Condition66%4/6
defined $creation and !$ttl || $creation + $ttl >= time
!ll&&!rl&&r
6406
not $ttl or $creation + $ttl >= time
l!l&&r!l&&!r
150
MC/DC33%1/3
defined $creation and !$ttl || $creation + $ttl >= time
defined $creation not $ttl $creation + $ttl >= time
Truth table75%3/4
A and not(B) or C
A= defined $creationB= not $ttlC= $creation + $ttl >= time
ABCresult
0XX0
1000
11X1
1011
2132 6 ▶ if($ttl) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ttl) 5 1 6
2133 5 push @{$self->{o}}, 'Expires: ' . HTTP::Date::time2str($creation + $ttl);
2134 }
2135 6 return;
2136 }
2137  
2138 # Each different set of arguments, which the client chooses, gives a file
2139 64 ▶ my $max_pages = exists($self->{save_to}->{max_pages}) ? $self->{save_to}->{max_pages} : $DEFAULT_SAVE_TO_MAX_PAGES;
Branch: 1 branch
BranchTrueFalseTotal
exists $self->{'save_to'}{'max_pages'} ? : 8 56 64
2140 64 ▶ if($max_pages && !defined($creation)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($max_pages and not defined $creation) 62 2 64
Condition66%2/3
$max_pages and not defined $creation
!ll&&!rl&&r
2062
MC/DC50%1/2
$max_pages and not defined $creation
$max_pages not defined $creation
Truth table66%2/3
A and not(B)
A= $max_pagesB= not defined $creation
ABresult
0X0
100
111
2141 62 my ($count) = $dbh->selectrow_array('SELECT COUNT(*) FROM fcgi_buffer');
2142 62 ▶ if($count >= $max_pages) {
Branch: 1 branch
BranchTrueFalseTotal
if ($count >= $max_pages) 2 60 62
2143 2 $self->_problem_once(__PACKAGE__ . ": save_to has reached its limit of $max_pages pages");
2144 2 return;
2145 }
2146 }
2147  
2148 62 my $dir = $self->{save_to}->{directory};
2149 62 my $browser_type = $self->{info}->browser_type();
2150 62 my $language = $self->_save_to_language();
2151 62 my $bdir = File::Spec->catfile($dir, _safe_filename($browser_type));
2152 62 ▶ if($bdir =~ /^(.+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bdir =~ /^(.+)$/) 62 0 62
2153 62 $bdir = $1; # Untaint
2154 }
2155 62 my $ldir = File::Spec->catfile($bdir, _safe_filename($language));
2156 62 my $sdir = File::Spec->catfile($ldir, _safe_filename($self->{info}->script_name()));
2157 62 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 6 56 62
2158 6 $self->{logger}->debug("Create paths to $sdir");
2159 }
2160 62 File::Path::make_path($sdir);
2161 61 my $path = File::Spec->catfile($sdir, $self->_save_to_filename() . '.html');
2162  
2163 # The file has the same name for each virtual host using this directory,
2164 # and must not replace the page of another one
2165 61 my ($owner) = $dbh->selectrow_array('SELECT key FROM fcgi_buffer WHERE path = ?', undef, $path);
2166 61 ▶ if(defined($owner) && ($owner ne $key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $owner and $owner ne $key) 1 60 61
Condition66%2/3
defined $owner and $owner ne $key
!ll&&!rl&&r
6001
MC/DC50%1/2
defined $owner and $owner ne $key
defined $owner $owner ne $key
Truth table66%2/3
A and B
A= defined $ownerB= $owner ne $key
ABresult
0X0
100
111
2167 1 $path = File::Spec->catfile($sdir, $self->_save_to_filename($self->_save_to_host()) . '.html');
2168 }
2169 61 ▶ if($path =~ /^(.+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path =~ /^(.+)$/) 61 0 61
2170 61 $path = $1; # Untaint
2171 }
2172  
2173 61 my $copy = $unzipped_body;
2174  
2175 # handle <a href="?arg3=4">Call self with different args</a>
2176 # The static page is somewhere else, so make the links absolute.
2177 # REQUEST_URI comes from the client and is about to be stored in a page
2178 # that everyone can see
2179 61 my $r = $request_uri;
2180 61 $r =~ s/\?.*$//;
2181 61 $r = _escape_attribute($r);
2182 61 $copy =~ s/<a\s+href="(\?[^"]*)"/<a href="$r$1"/gi;
2183  
2184 # Links to this page now point to its static copy
2185 61 my $changes = 0;
2186 61 ▶ if(defined(my $url = $self->_path_to_url($path))) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $url = $self->_path_to_url($path))) 61 0 61
2187 61 $changes = ($copy =~ s/((?i:<a\s+href="))\Q$request_uri\E"/$1$url"/g);
2188 }
2189  
2190 # Avoid Wide character
2191 61 ▶ return unless($self->_write_atomically($path, _to_bytes($copy)));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_write_atomically($path, _to_bytes($copy)) 1 60 61
2192  
2193 # Do INSERT OR REPLACE in case another program has got in first
2194 60 my $uri = $self->_save_to_uri($request_uri);
2195 60 $query = "INSERT OR REPLACE INTO fcgi_buffer(key, language, browser_type, path, uri, creation) VALUES(?, ?, ?, ?, ?, strftime('\%s','now'))";
2196 60 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 4 56 60
2197 4 $self->{logger}->debug("$query: $key, $language, $browser_type, $path, $uri");
2198 }
2199 60 $dbh->do($query, undef, $key, $language, $browser_type, $path, $uri);
2200  
2201 60 ▶ if($changes && $ttl) {
Branch: 1 branch
BranchTrueFalseTotal
if ($changes and $ttl) 1 59 60
Condition66%2/3
$changes and $ttl
!ll&&!rl&&r
5901
MC/DC50%1/2
$changes and $ttl
$changes $ttl
Truth table66%2/3
A and B
A= $changesB= $ttl
ABresult
0X0
100
111
2202 1 push @{$self->{o}}, 'Expires: ' . HTTP::Date::time2str(time + $ttl);
2203 }
2204 }
2205  
2206 # Keep one of the Expires headers, the earliest, since the page is out of date
2207 # as soon as any part of it is. RFC 9111 4.2.1 allows a cache to treat a response
2208 # with more than one as stale. A date that can't be understood means already
2209 # expired (RFC 9111 5.3)
2210 260 ▶sub _one_expires {
Subroutine _one_expires: called CC=6 SCAR=17.9
2211 260 my @headers = @_;
2212  
2213 260 my @expires = grep { /^Expires:/i } @headers;
2214 260 ▶ return @headers if(scalar(@expires) < 2);
Branch: 1 branch
BranchTrueFalseTotal
if scalar @expires < 2 250 10 260
2215  
2216 10 my ($earliest, $earliest_time);
2217 10 foreach my $header(@expires) {
2218 20 my ($date) = $header =~ /^Expires:\s*(.*)$/i;
2219 20 ▶ my $time = HTTP::Date::str2time($date) || 0;
Condition100%2/2
&HTTP::Date::str2time($date) || 0
l!l
191
MC/DC100%1/1
&HTTP::Date::str2time($date) || 0
&HTTP::Date::str2time($date)
Truth table100%2/2
A
A= &HTTP::Date::str2time($date)
Aresult
11
00
2220 20 ▶ if((!defined($earliest_time)) || ($time < $earliest_time)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $earliest_time or $time < $earliest_time) 12 8 20
Condition100%3/3
not defined $earliest_time or $time < $earliest_time
l!l&&r!l&&!r
1028
MC/DC100%2/2
not defined $earliest_time or $time < $earliest_time
not defined $earliest_time $time < $earliest_time
Truth table100%3/3
not(A) or B
A= not defined $earliest_timeB= $time < $earliest_time
ABresult
1X1
011
000
2221 12 ($earliest, $earliest_time) = ($header, $time);
2222 }
2223 }
2224 10 return ((grep { !/^Expires:/i } @headers), $earliest);
2225 }
2226  
2227 # Write a file so that anyone reading it sees all of the old file or all of the
2228 # new one, never a part of it, and the old one survives a failure such as a full
2229 # disc. Returns true if it worked
2230 65 ▶sub _write_atomically {
Subroutine _write_atomically: called CC=7 SCAR=19.9
2231 65 my ($self, $path, $contents) = @_;
2232  
2233 65 require File::Basename;
2234 65 require File::Temp;
2235  
2236 65 my ($fout, $tmp) = eval {
2237 65 File::Temp::tempfile('.fcgi-buffer-XXXXXXXX', DIR => File::Basename::dirname($path), SUFFIX => '.tmp', UNLINK => 0);
2238 };
2239 65 ▶ unless($fout) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($fout) 1 64 65
2240 1 $self->_problem("Can't create $path");
2241 1 return 0;
2242 }
2243 64 ▶ if($tmp =~ /^(.+)$/s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tmp =~ /^(.+)$/s) 64 0 64
2244 64 $tmp = $1; # Untaint
2245 }
2246  
2247 # File::Temp creates files that only their owner can read, but it's the
2248 # web server that sends these
2249 64 ▶ my $ok = chmod(0666 & ~umask(), $fout) && (print $fout $contents);
Condition33%1/3
chmod(438 & ~(umask()), $fout) && print($fout $contents)
!ll&&!rl&&r
0064
MC/DC0%0/2
chmod(438 & ~(umask()), $fout) && print($fout $contents)
chmod(438 & ~(umask()), $fout) print($fout $contents)
Truth table33%1/3
A && B
A= chmod(438 & ~(umask()), $fout)B= print($fout $contents)
ABresult
0X0
100
111
2250 64 ▶ $ok = close($fout) && $ok;
Condition33%1/3
close $fout && $ok
!ll&&!rl&&r
0064
MC/DC0%0/2
close $fout && $ok
close $fout $ok
Truth table33%1/3
A && B
A= close $foutB= $ok
ABresult
0X0
100
111
2251 64 ▶ if($ok && rename($tmp, $path)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ok and rename $tmp, $path) 62 2 64
Condition66%2/3
$ok and rename $tmp, $path
!ll&&!rl&&r
0262
MC/DC50%1/2
$ok and rename $tmp, $path
$ok rename $tmp, $path
Truth table66%2/3
A and B
A= $okB= rename $tmp, $path
ABresult
0X0
100
111
2252 62 return 1;
2253 }
2254 2 $self->_problem("Can't create $path: $!");
2255 2 unlink $tmp;
2256 2 return 0;
2257 }
2258  
2259 # Make a string safe to put into an HTML attribute
2260 61 ▶sub _escape_attribute {
Subroutine _escape_attribute: called CC=1 SCAR=0.0
2261 61 my $string = shift;
2262  
2263 61 $string =~ s/&/&amp;/g;
2264 61 $string =~ s/"/&quot;/g;
2265 61 $string =~ s/'/&#39;/g;
2266 61 $string =~ s/</&lt;/g;
2267 61 $string =~ s/>/&gt;/g;
2268 61 return $string;
2269 }
2270  
2271 # The name of the virtual host that this request is for
2272 99 ▶sub _save_to_host {
Subroutine _save_to_host: called CC=3 SCAR=11.7
2273 99 my $self = shift;
2274  
2275 99 ▶ my $host = $self->{info}->can('domain_name') ? $self->{info}->domain_name() : undef;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'info'}->can('domain_name') ? : 99 0 99
2276 99 ▶ return defined($host) ? $host : 'default';
Branch: 1 branch
BranchTrueFalseTotal
defined $host ? : 99 0 99
2277 }
2278  
2279 # What the database holds for a URI. The same URI on another virtual host is a
2280 # different page, and this needs no change to the database's schema.
2281 # The order of the arguments doesn't make a different page, a link can give them
2282 # in any order
2283 98 ▶sub _save_to_uri {
Subroutine _save_to_uri: called CC=2 SCAR=6.9
2284 98 my ($self, $uri) = @_;
2285  
2286 98 ▶ if($uri =~ /^([^?]*)\?(.*)$/s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($uri =~ /^([^?]*)\?(.*)$/s) 96 2 98
2287 96 $uri = "$1?" . join('&', sort split(/[&;]/, $2));
2288 }
2289 98 return $self->_save_to_host() . $uri;
2290 }
2291  
2292 # replace dynamic links with static links
2293 231 ▶sub _save_to {
Subroutine _save_to: called CC=2 SCAR=6.9
2294 231 my ($self, $unzipped_body, $dbh) = @_;
2295  
2296 # The links can be changed later, the page can still be sent
2297 231 ▶ return $self->_try('save_to', sub { $self->_rewrite_links($unzipped_body, $dbh) }) || 0;
Subroutine __ANON__: called CC=1 SCAR=0.0
Condition100%2/2
$self->_try('save_to', sub { $self->_rewrite_links($unzipped_body, $dbh); } ) || 0
l!l
27204
MC/DC100%1/1
$self->_try('save_to', sub { $self->_rewrite_links($unzipped_body, $dbh); } ) || 0
$self->_try('save_to', sub { $self->_rewrite_links($unzipped_body, $dbh); } )
Truth table100%2/2
A
A= $self->_try('save_to', sub { $self->_rewrite_links($unzipped_body, $dbh); } )
Aresult
11
00
2298 }
2299  
2300 231 ▶sub _rewrite_links {
Subroutine _rewrite_links: called CC=28 SCAR=37.2
2301 231 my ($self, $unzipped_body, $dbh) = @_;
2302  
2303 231 ▶ return 0 unless($dbh && $self->{info} && (my $request_uri = $ENV{'REQUEST_URI'}));
Branch: 1 branch
BranchTrueFalseTotal
unless $dbh and $self->{"info"} and my $request_uri = $ENV{"REQUEST_URI"} 134 97 231
Condition66%4/6
$dbh and $self->{"info"} and my $request_uri = $ENV{"REQUEST_URI"}
!ll&&!rl&&r
134097
$dbh and $self->{"info"}
!ll&&!rl&&r
134097
MC/DC33%1/3
$dbh and $self->{"info"} and my $request_uri = $ENV{"REQUEST_URI"}
$dbh $self->{"info"} my $request_uri = $ENV{"REQUEST_URI"}
Truth table50%2/4
A and B and C
A= $dbhB= $self->{"info"}C= my $request_uri = $ENV{"REQUEST_URI"}
ABCresult
0XX0
10X0
1100
1111
2304 97 ▶ return 0 if(!defined($unzipped_body));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $unzipped_body 1 96 97
2305 96 ▶ return 0 unless($self->_is_html());
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_is_html 2 94 96
2306  
2307 # Links can't be followed to a page that has expired, so take the
2308 # opportunity to clear those up
2309 94 $self->_purge_save_to($dbh);
2310  
2311 92 my $query;
2312 92 my $copy = $unzipped_body;
2313 92 my $changes = 0;
2314 92 my $creation;
2315 my %seen_links;
2316 92 my $language = $self->_save_to_language();
2317 92 my $browser_type = $self->{info}->browser_type();
2318 92 ▶ while($unzipped_body =~ /<a\s+href="([^"]+)"/gi) {
Branch: 1 branch
BranchTrueFalseTotal
if ($unzipped_body =~ /<a\s+href="([^"]+)"/gi) 38 92 130
2319 38 my $link = $1;
2320 38 ▶ next if($seen_links{$link}); # Already updated in the copy
Branch: 1 branch
BranchTrueFalseTotal
if $seen_links{$link} 0 38 38
2321 38 $seen_links{$link} = 1;
2322  
2323 # The link is as it appears in the HTML, the database holds
2324 # the REQUEST_URI
2325 38 my $search_uri = $link;
2326 38 $search_uri =~ s/&amp;/&/g;
2327 38 ▶ if($search_uri =~ /^\?/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($search_uri =~ /^\?/) { } 4 34 38
2328 # CGI script has links to itself
2329 # $search_uri = "${request_uri}${link}";
2330 4 my $r = $request_uri;
2331 4 $r =~ s/\?.*$//;
2332 4 $search_uri = "${r}$search_uri";
2333 } else {
2334 34 ▶ next if($link =~ /^https?:\/\//); # FIXME: skips full URLs to ourself
Branch: 1 branch
BranchTrueFalseTotal
if $link =~ m[^https?://] 0 34 34
2335 # Though optimise_content fixes that
2336 34 ▶ next if($link =~ /\.(?:html?|jpg|gif)$/i);
Branch: 1 branch
BranchTrueFalseTotal
if $link =~ /\.(?:html?|jpg|gif)$/i 0 34 34
2337 }
2338 38 ▶ if($self->{save_to}->{ttl}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'save_to'}{'ttl'}) { } 38 0 38
2339 38 $query = "SELECT DISTINCT path, creation FROM fcgi_buffer WHERE uri = ? AND language = ? AND browser_type = ? AND creation >= strftime('\%s','now') - ?";
2340 } else {
2341 0 $query = 'SELECT DISTINCT path, creation FROM fcgi_buffer WHERE uri = ? AND language = ? AND browser_type = ?';
2342 }
2343 38 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 1 37 38
2344 1 $self->{logger}->debug("$query: $search_uri, $language, $browser_type");
2345 }
2346 38 my $sth = $dbh->prepare($query);
2347 38 my $uri = $self->_save_to_uri($search_uri);
2348 38 ▶ if($self->{save_to}->{ttl}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'save_to'}{'ttl'}) { } 38 0 38
2349 38 $sth->execute($uri, $language, $browser_type, $self->{save_to}->{ttl});
2350 } else {
2351 0 $sth->execute($uri, $language, $browser_type);
2352 }
2353 38 ▶ if(my $href = $sth->fetchrow_hashref()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $href = $sth->fetchrow_hashref) 29 9 38
2354 29 ▶ if(my $path = $href->{'path'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $path = $href->{"path"}) 29 0 29
2355 29 ▶ if(-r $path) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $path) { } 28 1 29
2356 28 my $url = $self->_path_to_url($path);
2357 28 ▶ if(!defined($url)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $url) 0 28 28
2358 0 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 0 0 0
2359 0 $self->{logger}->warn("$path is not under the document root, can't link to it");
2360 }
2361 0 next;
2362 }
2363 28 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 0 28 28
2364 0 $self->{logger}->debug("Changing links from $link to $url");
2365 }
2366 28 $changes += ($copy =~ s/((?i:<a\s+href="))\Q$link\E"/$1$url"/g);
2367 # Find the first link that will expire and use that
2368 28 ▶ if((!defined($creation)) || ($href->{'creation'} < $creation)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $creation or $href->{"creation"} < $creation) 27 1 28
Condition66%2/3
not defined $creation or $href->{"creation"} < $creation
l!l&&r!l&&!r
2701
MC/DC50%1/2
not defined $creation or $href->{"creation"} < $creation
not defined $creation $href->{"creation"} < $creation
Truth table66%2/3
not(A) or B
A= not defined $creationB= $href->{"creation"} < $creation
ABresult
1X1
011
000
2369 27 $creation = $href->{'creation'};
2370 }
2371 } else {
2372 1 $sth->finish();
2373 1 $query = 'DELETE FROM fcgi_buffer WHERE path = ?';
2374 1 $dbh->do($query, undef, $path);
2375 1 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 1 0 1
2376 1 $self->{logger}->warn("Remove entry for non-existant file $path");
2377 }
2378 }
2379 }
2380 }
2381 }
2382 92 ▶ if($changes) {
Branch: 1 branch
BranchTrueFalseTotal
if ($changes) 27 65 92
2383 27 my $ttl = $self->{save_to}->{ttl};
2384 27 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 0 27 27
2385 # $self->{logger}->debug("$changes links now point to static pages");
2386 0 ▶ if($changes == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($changes == 1) { } 0 0 0
2387 0 ▶ if($ttl) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ttl) { } 0 0 0
2388 0 $self->{logger}->info('1 link now points to a static page for ', $creation + $ttl - time, 's');
2389 } else {
2390 0 $self->{logger}->info('1 link now points to a static page');
2391 }
2392 } else {
2393 0 $self->{logger}->info("$changes links now point to static pages");
2394 }
2395 }
2396 27 $self->{'body'} = $copy;
2397 27 ▶ if($ttl) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ttl) 27 0 27
2398 27 push @{$self->{o}}, 'Expires: ' . HTTP::Date::time2str($creation + $ttl);
2399 }
2400 }
2401 92 return $changes;
2402 }
2403  
2404 # Delete the static pages that have passed their ttl
2405 94 ▶sub _purge_save_to {
Subroutine _purge_save_to: called CC=5 SCAR=16.2
2406 94 my ($self, $dbh) = @_;
2407  
2408 94 my $ttl = $self->{save_to}->{ttl};
2409 94 ▶ return unless($ttl);
Branch: 1 branch
BranchTrueFalseTotal
unless $ttl 2 92 94
2410  
2411 92 my $paths = $dbh->selectcol_arrayref("SELECT path FROM fcgi_buffer WHERE creation < strftime('\%s','now') - ?", undef, $ttl);
2412 90 ▶ return unless(scalar(@{$paths}));
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @{$paths;} 87 3 90
2413  
2414 3 foreach my $path(@{$paths}) {
2415 7 ▶ if($self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"logger"}) 0 7 7
2416 0 $self->{logger}->debug("unlink $path");
2417 }
2418 7 unlink $path;
2419 }
2420 3 $dbh->do("DELETE FROM fcgi_buffer WHERE creation < strftime('\%s','now') - ?", undef, $ttl);
2421 }
2422  
2423 # The language as stored in the save_to database
2424 154 ▶sub _save_to_language {
Subroutine _save_to_language: called CC=4 SCAR=14.5
2425 154 my $self = shift;
2426  
2427 154 ▶ if($self->{'lingua'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"lingua"}) 91 63 154
2428 91 my $language = $self->{'lingua'}->language();
2429 91 ▶ return $language if(defined($language) && length($language));
Branch: 1 branch
BranchTrueFalseTotal
if defined $language and length $language 91 0 91
Condition33%1/3
defined $language and length $language
!ll&&!rl&&r
0091
MC/DC0%0/2
defined $language and length $language
defined $language length $language
Truth table33%1/3
A and B
A= defined $languageB= length $language
ABresult
0X0
100
111
2430 }
2431 63 return 'default';
2432 }
2433  
2434 # Make a string safe to use as a file or directory name, and in a URL.
2435 # If anything had to be changed, a digest of the original is appended so that
2436 # different strings don't map onto the same file
2437 248 ▶sub _safe_filename {
Subroutine _safe_filename: called CC=4 SCAR=13.9
2438 248 my $name = shift;
2439  
2440 248 require Encode;
2441  
2442 248 my $safe = $name;
2443 248 $safe =~ s/[^A-Za-z0-9=_.,+-]/_/g;
2444 248 $safe =~ s/^\./_/;
2445 248 ▶ if(($safe ne $name) || (length($safe) > 200)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($safe ne $name or length $safe > 200) 9 239 248
Condition66%2/3
$safe ne $name or length $safe > 200
l!l&&r!l&&!r
90239
MC/DC50%1/2
$safe ne $name or length $safe > 200
$safe ne $name length $safe > 200
Truth table66%2/3
A or B
A= $safe ne $nameB= length $safe > 200
ABresult
1X1
011
000
2446 9 $safe = substr($safe, 0, 200) . '-' . substr(Digest::MD5::md5_hex(Encode::encode_utf8($name)), 0, 8);
2447 }
2448 248 ▶ if($safe =~ /^(.+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($safe =~ /^(.+)$/) 248 0 248
2449 248 $safe = $1; # Untaint
2450 }
2451 248 return $safe;
2452 }
2453  
2454 # The basename of the static page for this request, optionally with a prefix
2455 62 ▶sub _save_to_filename {
Subroutine _save_to_filename: called CC=6 SCAR=18.0
2456 62 my ($self, $prefix) = @_;
2457  
2458 62 my $name = $self->{'info'}->as_string();
2459 62 ▶ if(defined($name) && length($name)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $name and length $name) { } 60 2 62
Condition66%2/3
defined $name and length $name
!ll&&!rl&&r
0260
MC/DC50%1/2
defined $name and length $name
defined $name length $name
Truth table66%2/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
2460 # Keep the historical "arg1=a_arg2=b" naming
2461 60 $name =~ s/;\s*/_/g;
2462 } else {
2463 # An empty name would give a hidden file
2464 2 $name = 'index';
2465 }
2466 62 ▶ if(defined($ENV{'PATH_INFO'}) && length($ENV{'PATH_INFO'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ENV{"PATH_INFO"} and length $ENV{"PATH_INFO"}) 1 61 62
Condition66%2/3
defined $ENV{"PATH_INFO"} and length $ENV{"PATH_INFO"}
!ll&&!rl&&r
6101
MC/DC50%1/2
defined $ENV{"PATH_INFO"} and length $ENV{"PATH_INFO"}
defined $ENV{"PATH_INFO"} length $ENV{"PATH_INFO"}
Truth table66%2/3
A and B
A= defined $ENV{"PATH_INFO"}B= length $ENV{"PATH_INFO"}
ABresult
0X0
100
111
2467 1 $name = "$ENV{PATH_INFO}_$name";
2468 }
2469 62 ▶ $name = "${prefix}_$name" if(defined($prefix));
Branch: 1 branch
BranchTrueFalseTotal
if defined $prefix 1 61 62
2470 62 return _safe_filename($name);
2471 }
2472  
2473 # Convert the filename of a static page into the URL used to reach it, or undef
2474 # if it isn't under the document root
2475 189 ▶sub _path_to_url {
Subroutine _path_to_url: called CC=11 SCAR=25.9
2476 189 my ($self, $path) = @_;
2477  
2478 189 my $rootdir = $self->{'info'}->rootdir();
2479 189 ▶ return unless(defined($rootdir) && length($rootdir));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rootdir and length $rootdir 0 189 189
Condition33%1/3
defined $rootdir and length $rootdir
!ll&&!rl&&r
00189
MC/DC0%0/2
defined $rootdir and length $rootdir
defined $rootdir length $rootdir
Truth table33%1/3
A and B
A= defined $rootdirB= length $rootdir
ABresult
0X0
100
111
2480  
2481 189 require Cwd;
2482 189 foreach my $p(\$rootdir, \$path) {
2483 378 my $real = Cwd::realpath(${$p});
2484 0 ▶ ${$p} = File::Spec->canonpath(defined($real) ? $real : ${$p});
Branch: 1 branch
BranchTrueFalseTotal
defined $real ? : 378 0 378
2485 }
2486  
2487 189 my @root = File::Spec->splitdir($rootdir);
2488 189 my @dirs = File::Spec->splitdir($path);
2489 189 ▶ pop @root if(@root && ($root[-1] eq ''));
Branch: 1 branch
BranchTrueFalseTotal
if @root and $root[-1] eq "" 0 189 189
Condition33%1/3
@root and $root[-1] eq ""
!ll&&!rl&&r
01890
MC/DC0%0/2
@root and $root[-1] eq ""
@root $root[-1] eq ""
Truth table33%1/3
A and B
A= @rootB= $root[-1] eq ""
ABresult
0X0
100
111
2490  
2491 189 ▶ return if(scalar(@dirs) <= scalar(@root));
Branch: 1 branch
BranchTrueFalseTotal
if scalar @dirs <= scalar @root 0 189 189
2492 189 foreach my $d(@root) {
2493 567 my $p = shift @dirs;
2494 567 ▶ return if(($^O eq 'MSWin32') ? (lc($d) ne lc($p)) : ($d ne $p));
Branch: 2 branches
BranchTrueFalseTotal
if $^O eq "MSWin32" ? lc $d ne lc $p : $d ne $p 3 564 567
$^O eq 'MSWin32' ? : 0 567 567
2495 }
2496  
2497 186 require Encode;
2498 return join('/', '', map {
2499 186 my $s = Encode::encode_utf8($_);
2500 0 $s =~ s/([^A-Za-z0-9\-._~=,+])/sprintf('%%%02X', ord($1))/ge;
2501 639 $s
2502 } @dirs);
2503 }
2504  
2505 =head1 HOW THE OUTPUT IS SENT
2506  
2507 =over 4
2508  
2509 =item * Compression
2510  
2511 The first encoding listed by the client (in Accept-Encoding, or TE) that
2512 FCGI::Buffer can produce is used.
2513 Encodings with q=0 are skipped.
2514  
2515 Premise 1: the client is happy with any of the encodings that it lists.
2516 Premise 2: an encoding can only be produced if its module is installed.
2517 Conclusion: an encoding whose module isn't installed is passed over for the
2518 next one, rather than failing the request.
2519 If none can be used, the output is sent uncompressed.
2520  
2521 Only text is compressed, and not output for which the script has given its own
2522 Content-Encoding.
2523 A Vary: Accept-Encoding header is sent with anything that could be compressed.
2524  
2525 =item * Character encoding
2526  
2527 The module works on what your script prints.
2528  
2529 If your script prints bytes, such as UTF-8 that hasn't been decoded,
2530 they are sent exactly as they are.
2531  
2532 If your script prints a string of characters,
2533 that is to say one with Perl's UTF-8 flag set,
2534 it's encoded as UTF-8.
2535 There's no need for you to set a layer on the file handle,
2536 and you should say so in your Content-Type header with a charset.
2537  
2538 So multibyte content is safe either way,
2539 but it's best not to join the two in one string,
2540 since Perl would then treat the bytes as Latin-1 characters.
2541  
2542 Offsets in a Range request, the Content-Length header and the ETag are all
2543 worked out from the bytes that are sent.
2544  
2545 =item * Range
2546  
2547 A single range of bytes, such as C<bytes=0-99>, C<bytes=100-> or
2548 C<bytes=-100> (the last 100 bytes), is honoured with a 206 status and a
2549 Content-Range header.
2550 A range which starts after the end of the page, or C<bytes=-0>,
2551 can't be satisfied and gets a 416 status with no body.
2552 Anything else, such as several ranges or a backwards range, is ignored and the
2553 whole page is sent.
2554  
2555 A range is only honoured for a GET request with a status of 200 and when no
2556 server-side cache has been given, otherwise the whole page is sent,
2557 which RFC 9110 allows.
2558 An If-Range header is honoured.
2559 A part of a page is never compressed, so it has the ETag of the uncompressed
2560 version.
2561 It is a part of the page after any links have been changed to point to static
2562 pages.
2563  
2564 =item * Conditional requests
2565  
2566 If-None-Match may be a list of ETags, weak ETags or "*".
2567 If it is given, If-Modified-Since isn't looked at.
2568 The ETag is of the page as it's sent, so it changes when a link is changed to
2569 point to a static page.
2570 Last-Modified is when the page was put into the cache and doesn't change,
2571 so a client that only sends If-Modified-Since can be given a 304 and keep the
2572 old links.
2573 Browsers send both.
2574 For methods other than GET and HEAD a match gives a 412 status, although the
2575 script will have already run,
2576 and If-Modified-Since is ignored.
2577  
2578 If there would be more than one Expires header,
2579 because the script gave one and there are links to static pages,
2580 only the earliest is sent.
2581  
2582 The ETag of compressed output ends with the name of the encoding,
2583 e.g. C<"0123456789abcdef0123456789abcdef-gzip">, since it isn't the same bytes
2584 as the uncompressed version.
2585 If-None-Match treats them as a match, but If-Range doesn't.
2586  
2587 =item * Headers
2588  
2589 The module sends one Status header, and works out Content-Length itself even
2590 if the script has given one, since the output may have changed.
2591 Header lines can end in either CRLF or LF.
2592  
2593 =item * Failures
2594  
2595 Nothing that goes wrong with the cache, the save_to database or the logger stops
2596 the page from being sent.
2597 A warning is given,
2598 and if the page can't be processed further it's sent as the script printed it.
2599 If the script printed nothing because it relied upon the cache,
2600 the status is 500.
2601  
2602 =item * Optimisation
2603  
2604 optimise_content leaves the contents of <pre> and <textarea> alone.
2605  
2606 =back
2607  
2608 =head1 AUTHOR
2609  
2610 Nigel Horne, C<< <njh at nigelhorne.com> >>
2611  
2612 =head1 BUGS
2613  
2614 FCGI::Buffer should be safe even in scripts that produce lots of different
2615 output, e.g. e-commerce situations.
2616 On such pages, however, I strongly urge setting generate_304 to 0 and
2617 sending the HTTP header "Cache-Control: no-cache".
2618  
2619 When using L<Template>, ensure that you don't use it to output to STDOUT,
2620 instead,
2621 you will need to capture into a variable and print that.
2622 For example:
2623  
2624 my $output;
2625 $template->process($input, $vars, \$output) || ($output = $template->error());
2626 print $output;
2627  
2628 Can produce buggy JavaScript if you use the <!-- HIDING technique.
2629 This is a bug in L<JavaScript::Packer>, not FCGI::Buffer.
2630  
2631 Mod_deflate can confuse this when compressing output.
2632 Ensure that deflation is off for .pl files:
2633  
2634 SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|pl)$ no-gzip dont-vary
2635  
2636 If you request compressed output then uncompressed output (or vice
2637 versa) on input that produces the same output, the status will be 304.
2638 The letter of the spec says that's wrong, so I'm noting it here, but
2639 in practice, you should not see this happen or have any difficulties
2640 because of it.
2641  
2642 FCGI::Buffer has not been tested against FastCGI.
2643  
2644 I advise adding FCGI::Buffer as the last use statement so that it is
2645 cleared up first. In particular, it should be loaded after
2646 L<Log::Log4perl>, if you're using that, so that any messages it
2647 produces are printed after the HTTP headers have been sent by
2648 FCGI::Buffer;
2649  
2650 Save_to doesn't understand links in JavaScript, which means that if you use self-calling
2651 CGIs loaded as a static page,
2652 they may point to the wrong place.
2653 The workaround is to avoid self-calling CGIs in JavaScript
2654  
2655 Please report any bugs or feature requests to C<bug-fcgi-buffer at rt.cpan.org>
2656 or through the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=FCGI-Buffer>.
2657 I will be notified, and then you'll automatically be notified of the progress on
2658 your bug as I make changes.
2659  
2660 The lint operation only works on HTML4, because of a restriction in L<HTML::Lint>.
2661  
2662 =head1 SEE ALSO
2663  
2664 L<CGI::Buffer>,
2665 L<HTML::Packer>,
2666 L<HTML::Lint>
2667  
2668 =head1 SUPPORT
2669  
2670 This module is provided as-is without any warranty.
2671  
2672 You can find documentation for this module with the perldoc command.
2673  
2674 perldoc FCGI::Buffer
2675  
2676 You can also look for information at:
2677  
2678 =over 4
2679  
2680 =item * RT: CPAN's request tracker
2681  
2682 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=FCGI-Buffer>
2683  
2684 =item * Search CPAN
2685  
2686 L<http://search.cpan.org/dist/FCGI-Buffer/>
2687  
2688 =back
2689  
2690 =head1 ACKNOWLEDGEMENTS
2691  
2692 The inspiration and code for some of this is cgi_buffer by Mark
2693 Nottingham: L<https://www.mnot.net/blog/2003/04/24/etags>.
2694  
2695 =head1 LICENSE AND COPYRIGHT
2696  
2697 The licence for cgi_buffer is:
2698  
2699 "(c) 2000 Copyright Mark Nottingham <mnot@pobox.com>
2700  
2701 This software may be freely distributed, modified and used,
2702 provided that this copyright notice remain intact.
2703  
2704 This software is provided 'as is' without warranty of any kind."
2705  
2706 The rest of the program is Copyright 2015-2026 Nigel Horne,
2707 and is released under the following licence: GPL2
2708  
2709 =cut
2710  
2711 15 1; # End of FCGI::Buffer
↑ Summary