blib/lib/CGI/Buffer.pm

filter: Statementstmt 77.9% 521 / 668 Branchbran 57.5% 221 / 384 Conditioncond 42.1% 155 / 368 MC/DCmcdc 15.9% 32 / 201 Subroutinesub 89.0% 73 / 82 Podpod 100% 4 / 4 totaltotal 58.9% 1006 / 1707 CC 331 SCAR 35.8
CC
331
Cov
63%
_apply_range
182.0
_serve_from_cache
167.5
_if_range_matches
110.0
CRAP 35.8
↑ Summary
1 package CGI::Buffer;
2  
3 # CGI::Buffer captures everything that a CGI script prints, and when the
4 # script ends (in the END block) verifies, optimises, compresses and caches
5 # it before sending it to the web server.
6  
7 28 ▶use 5.26.0; # CGI::Info's dependencies, e.g. Params::Validate::Strict, need it
Subroutine BEGIN: called CC=1 SCAR=0.0
8 28 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 28 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 28 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 28 ▶use Digest::MD5;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 28 ▶use IO::String;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 28 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 28 ▶use Scalar::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 # CGI::Info, HTTP::Date, HTTP::Status and Storable are only loaded when they're
18 # needed. A CGI program is compiled afresh for every request, and CGI::Info
19 # alone takes over 100ms to compile, which is far more than the rest of this
20 # module
21  
22 28 Readonly my $DEFAULT_GENERATE_304 => 1;
23 28 Readonly my $DEFAULT_GENERATE_LAST_MODIFIED => 1;
24 28 Readonly my $DEFAULT_COMPRESS_CONTENT => 1;
25 28 Readonly my $DEFAULT_OPTIMISE_CONTENT => 0;
26 28 Readonly my $DEFAULT_LINT_CONTENT => 0;
27 28 Readonly my $DEFAULT_CACHE_DURATION => '10 minutes';
28 28 Readonly my $DEFAULT_PROTOCOL => 'http';
29  
30 # Smaller bodies than this aren't worth compressing
31 28 Readonly my $MIN_GZIP_LEN => 32;
32  
33 # optimise_content at this level, or higher, repeats until the body stops
34 # shrinking and also optimises JavaScript
35 28 Readonly my $AGGRESSIVE_OPTIMISATION => 2;
36  
37 # The HTTP statuses that this module works with
38 28 Readonly my $HTTP_OK => 200;
39 28 Readonly my $HTTP_PARTIAL_CONTENT => 206;
40 28 Readonly my $HTTP_NOT_MODIFIED => 304;
41 28 Readonly my $HTTP_NOT_ACCEPTABLE => 406;
42 28 Readonly my $HTTP_PRECONDITION_FAILED => 412;
43 28 Readonly my $HTTP_RANGE_NOT_SATISFIABLE => 416;
44 28 Readonly my $HTTP_INTERNAL_SERVER_ERROR => 500;
45  
46 # The longest a client's Cache-Control: max-age may keep a page in the
47 # server-side cache, since one client's request affects all others
48 28 Readonly my $MAX_CLIENT_CACHE_SECONDS => 600;
49  
50 # The cookie that holds the token protecting forms, different for each client
51 # but it doesn't change the output
52 28 Readonly my $FORM_TOKEN_COOKIE => 'csrf_token';
53  
54 # Cache-Control directives which, in a request or a response, stop the cache
55 28 Readonly my %NO_CACHE_DIRECTIVES => map { $_ => 1 } qw(no-store no-cache private);
56  
57 # Request methods whose responses may be cached, or answered with a 304
58 28 Readonly my %SAFE_METHODS => map { $_ => 1 } qw(GET HEAD);
59  
60 # The protocols that understand ETag, If-None-Match and If-Modified-Since
61 28 Readonly my $CONDITIONAL_PROTOCOL => qr/^HTTP\/(?:1\.1|[23](?:\.0)?)$/;
62  
63 # The methods that CGI::Buffer calls on the logger
64 28 Readonly my @LOGGER_METHODS => qw(trace debug info warn error);
65  
66 # An ETag sent with compressed content ends in the name of the encoding
67 28 Readonly my $ENCODED_ETAG_SUFFIX => qr/-(?:gzip|br|zstd)"$/;
68  
69 # Content encodings that we can produce, and the module needed for each
70 28 Readonly my %ENCODING_MODULE => (
71 'gzip' => 'Compress::Zlib',
72 'x-gzip' => 'Compress::Zlib',
73 'br' => 'IO::Compress::Brotli',
74 'zstd' => 'Compress::Zstd',
75 );
76  
77 # A sprintf conversion, as used in the %{name}s placeholders of messages
78 28 Readonly my $SPRINTF_CONVERSION => qr/[-+ 0#]*\d*(?:\.\d+)?[sdfux]/;
79  
80 # Everything that CGI::Buffer says, keyed by message. A message is either a
81 # string, or a hash of plural forms chosen by the "count" argument.
82 # Placeholders are %{name} followed by a sprintf conversion. Each can be
83 # replaced, e.g. translated, with init(messages => { key => '...' })
84 28 Readonly my %DEFAULT_MESSAGES => (
85 too_late => {
86 one => 'Too late to call init, %{count}d character has been printed',
87 other => 'Too late to call init, %{count}d characters have been printed',
88 },
89 unknown_option => 'init: unknown option %{option}s ignored',
90 bad_option => 'init: %{option}s %{reason}s, ignored',
91 failed => '%{what}s failed: %{error}s',
92 no_cache_data => 'error retrieving data for key %{key}s',
93 no_cache_body => "Can't retrieve body for key %{key}s, the entry holds: %{fields}s",
94 logger_method => "The logger doesn't understand %{method}s()",
95 no_script_path => 'Failed to retrieve script path',
96 no_script_age => "Can't determine the age of %{path}s: %{error}s",
97 no_info => 'Failed to create CGI::Info object',
98 send_failed => 'Sending the output failed: %{error}s',
99 lint => '%{where}s: %{text}s',
100 );
101  
102 # What each option to init() must be: a "scalar", a non-negative "count",
103 # a "hash" reference, or an "object" which understands the methods listed
104 28 Readonly my %INIT_OPTIONS => (
105 generate_etag => ['scalar'],
106 generate_last_modified => ['scalar'],
107 generate_304 => ['scalar'],
108 compress_content => ['scalar'],
109 lint_content => ['scalar'],
110 optimise_content => ['count'],
111 cache => ['object', 'get_object', 'set'],
112 cache_key => ['scalar'],
113 cache_duration => ['scalar'],
114 cache_age => ['scalar'], # Legacy name for cache_duration
115 logger => ['object'], # _check_logger() looks at its methods
116 lingua => ['object', 'language'],
117 info => ['object', 'status', 'host_name'],
118 messages => ['hash'],
119 );
120  
121 =encoding utf8
122  
123 =head1 NAME
124  
125 CGI::Buffer - Verify, Cache and Optimise CGI Output
126  
127 =head1 VERSION
128  
129 Version 0.89
130  
131 =cut
132  
133 28 our $VERSION = '0.89';
134  
135 =head1 SYNOPSIS
136  
137 CGI::Buffer verifies the HTML that you produce by passing it through
138 C<HTML::Lint>.
139  
140 CGI::Buffer optimises CGI programs by reducing, filtering and compressing
141 output to speed up the transmission and by nearly seamlessly making use of
142 client and server caches.
143  
144 To make use of client caches, that is to say to reduce needless calls
145 to your server asking for the same data, all you need to do is to
146 include the package, and it does the rest.
147  
148 use CGI::Buffer;
149 # ...
150  
151 To also make use of server caches, that is to say to save regenerating
152 output when different clients ask you for the same data, you will need
153 to create a cache.
154 But that's simple:
155  
156 use CHI;
157 use CGI::Buffer;
158  
159 # Put this at the top before you output anything
160 if(CGI::Buffer::init(cache => CHI->new(driver => 'File'))->is_cached()) {
161 # Nothing has changed - use the version in the cache
162 exit;
163 }
164  
165 # ...
166  
167 To temporarily prevent the use of server-side caches, for example whilst
168 debugging before publishing a code change, set the NO_CACHE environment variable
169 to any non-zero value.
170 If you get errors about Wide characters in print it means that you've
171 forgotten to emit pure HTML on non-ASCII characters.
172 See L<HTML::Entities>.
173 As a hack work around you could also remove accents and the like by using
174 L<Text::Unidecode>,
175 which works well but isn't really what you want.
176  
177 =head2 HOW THE OUTPUT IS SENT
178  
179 When the script ends, CGI::Buffer:
180  
181 =over 4
182  
183 =item * optimises (C<optimise_content>) and checks (C<lint_content>) HTML;
184  
185 =item * answers conditional requests (If-None-Match, If-Modified-Since) with
186 304, or 412 for methods other than GET and HEAD;
187  
188 =item * answers a single byte Range with 206, or 416 if it can't be met, when
189 there's no server-side cache;
190  
191 =item * compresses with the first encoding in Accept-Encoding that it can
192 produce (gzip, br or zstd);
193  
194 =item * stores the output in, or sends it from, the server-side cache;
195  
196 =item * sends one Status header, and a Content-Length worked out from what is
197 actually sent.
198  
199 =back
200  
201 If any of that fails, a warning is given and the output is sent as the script
202 printed it.
203  
204 =head1 SUBROUTINES/METHODS
205  
206 =cut
207  
208 # Options. $generate_etag is undef until it's given, in which case it's decided
209 # from the protocol when the output is sent
210 28 our $generate_etag;
211 28 our $generate_304 = $DEFAULT_GENERATE_304;
212 28 our $generate_last_modified = $DEFAULT_GENERATE_LAST_MODIFIED;
213 28 our $compress_content = $DEFAULT_COMPRESS_CONTENT;
214 28 our $optimise_content = $DEFAULT_OPTIMISE_CONTENT;
215 28 our $lint_content = $DEFAULT_LINT_CONTENT;
216 28 our($cache, $cache_duration, $cache_key, $info, $logger, $lingua);
217  
218 # Messages given to init() to replace those in %DEFAULT_MESSAGES
219 28 our %messages;
220  
221 # The state of this request. $cacheable is the remembered answer of
222 # can_cache(). @o is the list of headers that CGI::Buffer adds to the script's
223 # own, which are in $headers
224 28 our($status, $script_mtime, $cobject, $cacheable, $headers, $body, @content_type,
225 $etag, $send_body, @o);
226  
227 # $raw is what the script printed, which is sent if processing it fails.
228 # $sent is set once output has started. $script_encoded is set if the script
229 # gave its own Content-Encoding. $content_encoding is the encoding that we've
230 # applied. $matched_etag is the client's ETag that If-None-Match matched
231 28 our($raw, $sent, $script_encoded, $content_encoding, $matched_etag);
232  
233 # $capture holds everything that the script prints, $old_buf is where it
234 # would otherwise have gone
235 28 our($capture, $old_buf);
236  
237 28 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
238 # Capture the output from now on, so that it can all be looked at
239 # before any of it is sent
240 28 $capture = IO::String->new();
241 28 $old_buf = select($capture);
242 }
243  
244 28 ▶END {
Subroutine END: called CC=4 SCAR=16.1
245 # Nothing can be sent while Perl is destroying everything
246 28 ▶ return if(${^GLOBAL_PHASE} eq 'DESTRUCT');
Branch: 1 branch
BranchTrueFalseTotal
if ${^GLOBAL_PHASE} eq "DESTRUCT" 0 28 28
247  
248 # Premise 1: anything from here on can fail, e.g. a logger or a cache
249 # Premise 2: until this is done, all that the process prints goes into
250 # the buffer, which is never sent
251 # Conclusion: this must be the first thing that is done
252 28 select($old_buf);
253  
254 # This can run while an eval is unwinding, and $? is the exit status
255 28 local($@, $!, $?);
256  
257 # Premise 1: Perl only gives a warning for an exception in an END block
258 # Premise 2: the client would be given an empty response
259 # Conclusion: catch it, and send the output as the script printed it
260 28 ▶ unless(eval { _send_output(); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { _send_output(); 1 } }) 0 28 28
261 0 _problem('send_failed', { error => $@ });
262 0 ▶ _send_raw() unless($sent);
Branch: 1 branch
BranchTrueFalseTotal
unless $CGI::Buffer::sent 0 0 0
263 }
264  
265 # This will cause everything to get flushed and prevent
266 # outputs to the logger. We need to do that now since
267 # if we leave it to Perl to delete later we may get
268 # a message that Log4perl::init() hasn't been called
269 28 $logger = undef;
270 }
271  
272 # Purpose: send what the script printed, untouched, after processing it failed
273 # Entry criteria: $raw holds the script's output, or is undef if it wasn't read
274 # Exit status: none
275 # Side effects: prints to the original output, sets $sent
276 0 ▶sub _send_raw {
Subroutine _send_raw: not called CC=3 SCAR=24.8
277 0 $sent = 1;
278 0 ▶ if(defined($raw) && length($raw)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $CGI::Buffer::raw and length $CGI::Buffer::raw) { } 0 0 0
Condition0%0/3
defined $CGI::Buffer::raw and length $CGI::Buffer::raw
!ll&&!rl&&r
000
MC/DC0%0/2
defined $CGI::Buffer::raw and length $CGI::Buffer::raw
defined $CGI::Buffer::raw length $CGI::Buffer::raw
Truth table0%0/3
A and B
A= defined $CGI::Buffer::rawB= length $CGI::Buffer::raw
ABresult
0X0
100
111
279 0 print _to_bytes($raw);
280 } else {
281 # The script relied upon a cache that has now failed
282 0 print _status_line($HTTP_INTERNAL_SERVER_ERROR), "\r\n\r\n";
283 }
284 }
285  
286 # Purpose: process everything that the script printed, and send it
287 # Entry criteria: the script has finished, and its output is in $capture
288 # Exit status: none, it dies if something unexpected fails, which END catches
289 # Side effects: prints the response, changes most of the request state
290 28 ▶sub _send_output {
Subroutine _send_output: called CC=19 SCAR=29.7
291 28 _read_output();
292  
293 # Premise 1: an ETag is only useful if the protocol supports If-None-Match
294 # Premise 2: an explicit generate_etag argument is the caller's decision
295 # Conclusion: default it from the protocol, but only when it isn't given
296 28 ▶ $generate_etag = _is_conditional_protocol() ? 1 : 0 unless(defined($generate_etag));
Branch: 2 branches
BranchTrueFalseTotal
unless defined $CGI::Buffer::generate_etag 26 2 28
_is_conditional_protocol() ? : 8 18 26
297 28 _log_request();
298  
299 # No headers and nothing in the cache: there's nothing to send but a status
300 28 ▶ unless($headers || is_cached()) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($CGI::Buffer::headers or is_cached()) 6 22 28
Condition100%3/3
$CGI::Buffer::headers or is_cached()
l!l&&r!l&&!r
2116
MC/DC100%2/2
$CGI::Buffer::headers or is_cached()
$CGI::Buffer::headers is_cached()
Truth table100%3/3
A or B
A= $CGI::Buffer::headersB= is_cached()
ABresult
1X1
011
000
301 6 _send_status_only();
302 6 return;
303 }
304 22 ▶ $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' ? : 1 21 22
Condition100%3/3
defined $ENV{"REQUEST_METHOD"} and $ENV{"REQUEST_METHOD"} eq "HEAD"
!ll&&!rl&&r
4171
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
305 22 ▶ _set_content_type($headers) if($headers);
Branch: 1 branch
BranchTrueFalseTotal
if $CGI::Buffer::headers 21 1 22
306  
307 22 ▶ if(defined($body) && ($body eq '')) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $CGI::Buffer::body and $CGI::Buffer::body eq '') { } 0 22 22
elsif (_is_html() and defined $CGI::Buffer::body and not $CGI::Buffer::script_encoded) { } 20 4 24
Condition66%2/3
defined $CGI::Buffer::body and $CGI::Buffer::body eq ""
!ll&&!rl&&r
2200
MC/DC0%0/2
defined $CGI::Buffer::body and $CGI::Buffer::body eq ""
defined $CGI::Buffer::body $CGI::Buffer::body eq ""
Truth table66%2/3
A and B
A= defined $CGI::Buffer::bodyB= $CGI::Buffer::body eq ""
ABresult
0X0
100
111
308 # E.g. if header of Location is given with no body, for
309 # redirection
310 0 $body = undef;
311 ▶ } elsif(_is_html() && defined($body) && !$script_encoded) {
Condition66%4/6
_is_html() and defined $CGI::Buffer::body and not $CGI::Buffer::script_encoded
!ll&&!rl&&r
2020
_is_html() and defined $CGI::Buffer::body
!ll&&!rl&&r
2020
MC/DC33%1/3
_is_html() and defined $CGI::Buffer::body and not $CGI::Buffer::script_encoded
_is_html() defined $CGI::Buffer::body not $CGI::Buffer::script_encoded
Truth table50%2/4
A and B and not(C)
A= _is_html()B= defined $CGI::Buffer::bodyC= not $CGI::Buffer::script_encoded
ABCresult
0XX0
10X0
1100
1111
312 20 ▶ _optimise_html() if($optimise_content);
Branch: 1 branch
BranchTrueFalseTotal
if $CGI::Buffer::optimise_content 16 4 20
313 20 ▶ _lint_html() if($lint_content);
Branch: 1 branch
BranchTrueFalseTotal
if $CGI::Buffer::lint_content 3 17 20
314 }
315 22 _initial_status();
316  
317 # Range, Content-Length, compression and the ETag all work in bytes.
318 # A script which printed bytes is left alone: encoding those would
319 # encode any UTF-8 in them a second time
320 22 $body = _to_bytes($body);
321  
322 22 my $unzipped_body = _prepare_body();
323  
324 22 ▶ if($cache) {
Branch: 1 branch
BranchTrueFalseTotal
if ($CGI::Buffer::cache) { } 3 19 22
325 3 _use_cache($unzipped_body);
326 } else {
327 19 push @o, @{_x_cache_headers('MISS', 'MISS')};
328 19 ▶ if($info && $generate_last_modified && (my $age = _my_age())) {
Branch: 1 branch
BranchTrueFalseTotal
if ($CGI::Buffer::info and $CGI::Buffer::generate_last_modified and my $age = _my_age()) 16 3 19
Condition66%4/6
$CGI::Buffer::info and $CGI::Buffer::generate_last_modified and my $age = _my_age()
!ll&&!rl&&r
3016
$CGI::Buffer::info and $CGI::Buffer::generate_last_modified
!ll&&!rl&&r
3016
MC/DC33%1/3
$CGI::Buffer::info and $CGI::Buffer::generate_last_modified and my $age = _my_age()
$CGI::Buffer::info $CGI::Buffer::generate_last_modified my $age = _my_age()
Truth table50%2/4
A and B and C
A= $CGI::Buffer::infoB= $CGI::Buffer::generate_last_modifiedC= my $age = _my_age()
ABCresult
0XX0
10X0
1100
1111
329 16 push @o, 'Last-Modified: ' . _http_date($age);
330 }
331 }
332  
333 22 _add_vary($headers);
334 22 _add_etag_header();
335 22 _emit();
336 }
337  
338 # Purpose: read what the script printed, and split it into headers and body
339 # Entry criteria: the script has finished printing
340 # Exit status: none
341 # Side effects: sets $raw, $headers and $body
342 28 ▶sub _read_output {
Subroutine _read_output: called CC=1 SCAR=0.0
343 28 my $pos = $capture->getpos();
344 28 $capture->setpos(0);
345 28 read($capture, my $output, $pos);
346  
347 # Keep this before anything else that can fail, it's what will be sent
348 # if something does
349 28 $raw = $output;
350 28 ($headers, $body) = split /\r?\n\r?\n/, $output, 2;
351 }
352  
353 # Purpose: log what was asked of us, to help with debugging
354 # Entry criteria: $generate_etag has been decided
355 # Exit status: none
356 # Side effects: writes to the logger, if there is one
357 28 ▶sub _log_request {
Subroutine _log_request: called CC=3 SCAR=11.0
358 28 foreach my $header('HTTP_IF_NONE_MATCH', 'HTTP_IF_MODIFIED_SINCE') {
359 56 ▶ _log('debug', "$header: $ENV{$header}") if($ENV{$header});
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{$header} 6 50 56
360 }
361 28 _log('debug', "Generate_etag = $generate_etag, ",
362 "Generate_304 = $generate_304, ",
363 "Generate_last_modified = $generate_last_modified");
364 }
365  
366 # Purpose: answer a request for which the script printed nothing
367 # Entry criteria: $headers is empty and the page isn't in the cache
368 # Exit status: none
369 # Side effects: prints a Status header if the script printed nothing at all
370 6 ▶sub _send_status_only {
Subroutine _send_status_only: called CC=4 SCAR=14.6
371 6 _log('debug', 'There was no output');
372  
373 # Headers that are defined but empty, i.e. the script only printed
374 # blank lines, are left as they are
375 6 ▶ return if(defined($headers));
Branch: 1 branch
BranchTrueFalseTotal
if defined $CGI::Buffer::headers 0 6 6
376  
377 6 ▶ $status = $info ? $info->status() : $HTTP_OK unless(defined($status));
Branch: 2 branches
BranchTrueFalseTotal
unless defined $CGI::Buffer::status 6 0 6
$CGI::Buffer::info ? : 0 6 6
378 6 $sent = 1;
379 6 print _status_line($status), "\n\n";
380 }
381  
382 # Purpose: work out the status that the script wants to send
383 # Entry criteria: $headers is the script's headers, if any
384 # Exit status: none
385 # Side effects: sets $status
386 22 ▶sub _initial_status {
Subroutine _initial_status: called CC=4 SCAR=13.9
387 22 ▶ if(defined($headers) && ($headers =~ /^Status:\s*(\d+)/mi)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $CGI::Buffer::headers and $CGI::Buffer::headers =~ /^Status:\s*(\d+)/imu) { } 1 21 22
Condition100%3/3
defined $CGI::Buffer::headers and $CGI::Buffer::headers =~ /^Status:\s*(\d+)/imu
!ll&&!rl&&r
1201
MC/DC100%2/2
defined $CGI::Buffer::headers and $CGI::Buffer::headers =~ /^Status:\s*(\d+)/imu
defined $CGI::Buffer::headers $CGI::Buffer::headers =~ /^Status:\s*(\d+)/imu
Truth table100%3/3
A and B
A= defined $CGI::Buffer::headersB= $CGI::Buffer::headers =~ /^Status:\s*(\d+)/imu
ABresult
0X0
100
111
388 1 $status = $1;
389 } else {
390 21 ▶ $status = $info ? $info->status() : $HTTP_OK;
Branch: 1 branch
BranchTrueFalseTotal
$CGI::Buffer::info ? : 16 5 21
391 }
392 22 _log('debug', "Initial status = $status");
393 }
394  
395 # Purpose: answer conditional and Range requests for output that the script has
396 # just generated, then compress it
397 # Entry criteria: $body is bytes or undef, $status is set
398 # Exit status: the uncompressed body, which is what the cache stores, or undef
399 # Side effects: may change $status, $send_body, $body, $etag and @o
400 22 ▶sub _prepare_body {
Subroutine _prepare_body: called CC=23 SCAR=38.6
401 22 my $encoding = _choose_encoding();
402 22 my $unzipped_body = $body;
403  
404 # Generate the eTag before compressing, since the compressed data
405 # includes the mtime field which changes thus causing a different
406 # Etag to be generated
407 22 ▶ if($generate_etag && defined($body) && _is_conditional_protocol()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($CGI::Buffer::generate_etag and defined $CGI::Buffer::body and _is_conditional_protocol()) 6 16 22
Condition66%4/6
$CGI::Buffer::generate_etag and defined $CGI::Buffer::body and _is_conditional_protocol()
!ll&&!rl&&r
1606
$CGI::Buffer::generate_etag and defined $CGI::Buffer::body
!ll&&!rl&&r
1606
MC/DC33%1/3
$CGI::Buffer::generate_etag and defined $CGI::Buffer::body and _is_conditional_protocol()
$CGI::Buffer::generate_etag defined $CGI::Buffer::body _is_conditional_protocol()
Truth table50%2/4
A and B and C
A= $CGI::Buffer::generate_etagB= defined $CGI::Buffer::bodyC= _is_conditional_protocol()
ABCresult
0XX0
10X0
1100
1111
408 6 _generate_etag();
409 6 ▶ _check_if_none_match() if($ENV{'HTTP_IF_NONE_MATCH'} && $generate_304 && ($status == $HTTP_OK));
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"HTTP_IF_NONE_MATCH"} and $CGI::Buffer::generate_304 and $CGI::Buffer::status == $HTTP_OK 2 4 6
Condition83%5/6
$ENV{"HTTP_IF_NONE_MATCH"} and $CGI::Buffer::generate_304 and $CGI::Buffer::status == $HTTP_OK
!ll&&!rl&&r
402
$ENV{"HTTP_IF_NONE_MATCH"} and $CGI::Buffer::generate_304
!ll&&!rl&&r
222
MC/DC66%2/3
$ENV{"HTTP_IF_NONE_MATCH"} and $CGI::Buffer::generate_304 and $CGI::Buffer::status == $HTTP_OK
$ENV{"HTTP_IF_NONE_MATCH"} $CGI::Buffer::generate_304 $CGI::Buffer::status == $HTTP_OK
Truth table75%3/4
A and B and C
A= $ENV{"HTTP_IF_NONE_MATCH"}B= $CGI::Buffer::generate_304C= $CGI::Buffer::status == $HTTP_OK
ABCresult
0XX0
10X0
1100
1111
410 }
411  
412 22 ▶ if(defined($unzipped_body)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $unzipped_body) 20 2 22
413 # Conditions are looked at before Range, and If-Modified-Since
414 # isn't looked at if If-None-Match was checked and failed.
415 # With a cache, _use_cache() looks at it instead
416 20 ▶ if((!$cache) && $info && $ENV{'HTTP_IF_MODIFIED_SINCE'} && ($status == $HTTP_OK) &&
Branch: 1 branch
BranchTrueFalseTotal
if (not $CGI::Buffer::cache and $CGI::Buffer::info and $ENV{"HTTP_IF_MODIFIED_SINCE"} and $CGI::Buffer::status == $HTTP_OK and not $ENV{"HTTP_IF_NONE_MATCH"} && defined $CGI::Buffer::etag) 2 18 20
Condition73%11/15
not $CGI::Buffer::cache and $CGI::Buffer::info and $ENV{"HTTP_IF_MODIFIED_SINCE"} and $CGI::Buffer::status == $HTTP_OK and not $ENV{"HTTP_IF_NONE_MATCH"} && defined $CGI::Buffer::etag
!ll&&!rl&&r
1802
not $CGI::Buffer::cache and $CGI::Buffer::info and $ENV{"HTTP_IF_MODIFIED_SINCE"} and $CGI::Buffer::status == $HTTP_OK
!ll&&!rl&&r
1802
not $CGI::Buffer::cache and $CGI::Buffer::info and $ENV{"HTTP_IF_MODIFIED_SINCE"}
!ll&&!rl&&r
4142
not $CGI::Buffer::cache and $CGI::Buffer::info
!ll&&!rl&&r
1316
$ENV{'HTTP_IF_NONE_MATCH'} && defined $CGI::Buffer::etag
!ll&&!rl&&r
200
MC/DC50%3/6
not $CGI::Buffer::cache and $CGI::Buffer::info and $ENV{"HTTP_IF_MODIFIED_SINCE"} and $CGI::Buffer::status == $HTTP_OK and not $ENV{"HTTP_IF_NONE_MATCH"} && defined $CGI::Buffer::etag
not $CGI::Buffer::cache $CGI::Buffer::info $ENV{"HTTP_IF_MODIFIED_SINCE"} $CGI::Buffer::status == $HTTP_OK $ENV{'HTTP_IF_NONE_MATCH'} defined $CGI::Buffer::etag
Truth table57%4/7
not(A) and B and C and D and not(E && F)
A= not $CGI::Buffer::cacheB= $CGI::Buffer::infoC= $ENV{"HTTP_IF_MODIFIED_SINCE"}D= $CGI::Buffer::status == $HTTP_OKE= $ENV{'HTTP_IF_NONE_MATCH'}F= defined $CGI::Buffer::etag
ABCDEFresult
0XXXXX0
10XXXX0
110XXX0
1110XX0
1111110
11110X1
1111101
417 !($ENV{'HTTP_IF_NONE_MATCH'} && defined($etag))) {
418 2 _check_modified_since(_my_age());
419 }
420  
421 # Only a successful GET can be cut up, and only if the client's
422 # copy, if it has given one, is still the current one
423 20 my $range = $ENV{'HTTP_RANGE'};
424 20 ▶ if($range && !$cache && ($status == $HTTP_OK) && _is_get() && _if_range_matches() &&
Branch: 1 branch
BranchTrueFalseTotal
if ($range and not $CGI::Buffer::cache and $CGI::Buffer::status == $HTTP_OK and _is_get() and _if_range_matches() and defined(my $partial = _apply_range($CGI::Buffer::body, $range))) 0 20 20
Condition33%5/15
$range and not $CGI::Buffer::cache and $CGI::Buffer::status == $HTTP_OK and _is_get() and _if_range_matches() and defined(my $partial = _apply_range($CGI::Buffer::body, $range))
!ll&&!rl&&r
2000
$range and not $CGI::Buffer::cache and $CGI::Buffer::status == $HTTP_OK and _is_get() and _if_range_matches()
!ll&&!rl&&r
2000
$range and not $CGI::Buffer::cache and $CGI::Buffer::status == $HTTP_OK and _is_get()
!ll&&!rl&&r
2000
$range and not $CGI::Buffer::cache and $CGI::Buffer::status == $HTTP_OK
!ll&&!rl&&r
2000
$range and not $CGI::Buffer::cache
!ll&&!rl&&r
2000
MC/DC0%0/6
$range and not $CGI::Buffer::cache and $CGI::Buffer::status == $HTTP_OK and _is_get() and _if_range_matches() and defined(my $partial = _apply_range($CGI::Buffer::body, $range))
$range not $CGI::Buffer::cache $CGI::Buffer::status == $HTTP_OK _is_get() _if_range_matches() defined(my $partial = _apply_range($CGI::Buffer::body, $range))
Truth table14%1/7
A and not(B) and C and D and E and F
A= $rangeB= not $CGI::Buffer::cacheC= $CGI::Buffer::status == $HTTP_OKD= _is_get()E= _if_range_matches()F= defined(my $partial = _apply_range($CGI::Buffer::body, $range))
ABCDEFresult
0XXXXX0
10XXXX0
110XXX0
1110XX0
11110X0
1111100
1111111
425 defined(my $partial = _apply_range($body, $range))) {
426 # Premise 1: Content-Range counts the bytes of what is sent
427 # Premise 2: the offsets the client gave are in the page,
428 # not in a compressed copy
429 # Conclusion: a part of a page is never compressed
430 0 $encoding = '';
431 0 _set_status($partial->{status});
432 0 push @o, "Content-Range: $partial->{content_range}";
433 0 ▶ if($partial->{status} == $HTTP_RANGE_NOT_SATISFIABLE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($partial->{'status'} == $HTTP_RANGE_NOT_SATISFIABLE) { } 0 0 0
434 # Range Not Satisfiable has no body
435 0 $body = $unzipped_body = undef;
436 0 $send_body = 0;
437 } else {
438 0 $body = $unzipped_body = $partial->{body};
439 }
440 }
441 # A 304 or 412 has no body to compress, and mustn't say that it has
442 20 ▶ _compress($encoding) if($send_body || ($status == $HTTP_OK));
Branch: 1 branch
BranchTrueFalseTotal
if $CGI::Buffer::send_body or $CGI::Buffer::status == $HTTP_OK 17 3 20
Condition66%2/3
$CGI::Buffer::send_body or $CGI::Buffer::status == $HTTP_OK
l!l&&r!l&&!r
1703
MC/DC50%1/2
$CGI::Buffer::send_body or $CGI::Buffer::status == $HTTP_OK
$CGI::Buffer::send_body $CGI::Buffer::status == $HTTP_OK
Truth table66%2/3
A or B
A= $CGI::Buffer::send_bodyB= $CGI::Buffer::status == $HTTP_OK
ABresult
1X1
011
000
443 }
444 22 return $unzipped_body;
445 }
446  
447 # Purpose: use the server-side cache for this request
448 # Entry criteria: $cache is set, $unzipped_body is from _prepare_body()
449 # Exit status: none
450 # Side effects: stores the page, or loads it from the cache. Releases $cache
451 3 ▶sub _use_cache {
Subroutine _use_cache: called CC=4 SCAR=13.9
452 3 my $unzipped_body = shift;
453  
454 3 require Storable;
455 3 my $key = _generate_key();
456  
457 3 ▶ if(defined($body)) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $CGI::Buffer::body) { } 1 2 3
elsif (not defined $CGI::Buffer::headers && length $CGI::Buffer::headers) { } 1 1 2
458 # The script generated the page
459 1 _store_in_cache($key, $unzipped_body);
460 ▶ } elsif((!defined($headers)) || !length($headers)) {
Condition66%2/3
defined $CGI::Buffer::headers && length $CGI::Buffer::headers
!ll&&!rl&&r
101
MC/DC50%1/2
defined $CGI::Buffer::headers && length $CGI::Buffer::headers
defined $CGI::Buffer::headers length $CGI::Buffer::headers
Truth table66%2/3
A && B
A= defined $CGI::Buffer::headersB= length $CGI::Buffer::headers
ABresult
0X0
100
111
461 # The script printed nothing because is_cached() said the page
462 # is in the cache
463 1 _serve_from_cache($key);
464 } else {
465 # Headers with no body, e.g. a redirection. There's nothing to
466 # store, and the cache mustn't replace them
467 1 push @o, @{_x_cache_headers('MISS', 'MISS')}, _buffer_header('Miss');
468 }
469  
470 # We don't need it any more, so give Perl a chance to
471 # tidy it up seeing as we're in the destructor
472 3 $cache = undef;
473 }
474  
475 # Purpose: send the copy of the page that is in the server-side cache
476 # Entry criteria: the script printed nothing, $key is the cache key
477 # Exit status: none
478 # Side effects: sets $headers, $body, $status, $send_body, $etag and @o
479 1 ▶sub _serve_from_cache {
Subroutine _serve_from_cache: called CC=29 SCAR=51.2
480 1 my $key = shift;
481  
482 # is_cached() has already looked, and it mustn't have expired since then
483 1 ▶ $cobject ||= _cache_lookup($key);
Condition33%1/3
$CGI::Buffer::cobject ||= _cache_lookup($key)
l!l&&r!l&&!r
100
MC/DC0%0/2
$CGI::Buffer::cobject ||= _cache_lookup($key)
$CGI::Buffer::cobject _cache_lookup($key)
Truth table33%1/3
A ||= B
A= $CGI::Buffer::cobjectB= _cache_lookup($key)
ABresult
1X1
011
000
484 1 my $cache_hash;
485 1 ▶ if(defined($cobject)) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $CGI::Buffer::cobject) { } 1 0 1
elsif ($CGI::Buffer::send_body) { } 0 0 0
486 1 $cache_hash = Storable::thaw($cobject->value());
487 1 $headers = $cache_hash->{'headers'};
488 1 ▶ _set_content_type($headers) if(defined($headers));
Branch: 1 branch
BranchTrueFalseTotal
if defined $CGI::Buffer::headers 1 0 1
489 1 @o = (_buffer_header('Hit'), @{_x_cache_headers('HIT', 'HIT')});
490 } elsif($send_body) {
491 0 _problem('no_cache_data', { key => $key });
492 }
493  
494 1 ▶ if($send_body && ($status == $HTTP_OK) && defined($cache_hash)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($CGI::Buffer::send_body and $CGI::Buffer::status == $HTTP_OK and defined $cache_hash) 1 0 1
Condition33%2/6
$CGI::Buffer::send_body and $CGI::Buffer::status == $HTTP_OK and defined $cache_hash
!ll&&!rl&&r
001
$CGI::Buffer::send_body and $CGI::Buffer::status == $HTTP_OK
!ll&&!rl&&r
001
MC/DC0%0/3
$CGI::Buffer::send_body and $CGI::Buffer::status == $HTTP_OK and defined $cache_hash
$CGI::Buffer::send_body $CGI::Buffer::status == $HTTP_OK defined $cache_hash
Truth table25%1/4
A and B and C
A= $CGI::Buffer::send_bodyB= $CGI::Buffer::status == $HTTP_OKC= defined $cache_hash
ABCresult
0XX0
10X0
1100
1111
495 1 $body = _to_bytes($cache_hash->{'body'});
496 1 ▶ unless(defined($body)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $CGI::Buffer::body) 0 1 1
497 # The entry is damaged, remove it so that the next request
498 # makes a new one
499 0 _problem('no_cache_body', { key => $key, fields => join(', ', sort keys %{$cache_hash}) });
500 0 ▶ _try('removing a bad entry', sub { $cache->remove($key) });
Subroutine __ANON__: not called CC=1 SCAR=6.9
501 0 $headers = _status_line($HTTP_INTERNAL_SERVER_ERROR);
502 0 @o = ('Content-type: text/plain');
503 0 $send_body = 0;
504 0 _set_status($HTTP_INTERNAL_SERVER_ERROR);
505 }
506 }
507 1 ▶ if($send_body && ($status == $HTTP_OK) && $generate_etag && ((!defined($headers)) || ($headers !~ /^ETag:/mi))) {
Branch: 1 branch
BranchTrueFalseTotal
if ($CGI::Buffer::send_body and $CGI::Buffer::status == $HTTP_OK and $CGI::Buffer::generate_etag and not defined $CGI::Buffer::headers && $CGI::Buffer::headers =~ /^ETag:/imu) 0 1 1
Condition25%3/12
$CGI::Buffer::send_body and $CGI::Buffer::status == $HTTP_OK and $CGI::Buffer::generate_etag and not defined $CGI::Buffer::headers && $CGI::Buffer::headers =~ /^ETag:/imu
!ll&&!rl&&r
100
$CGI::Buffer::send_body and $CGI::Buffer::status == $HTTP_OK and $CGI::Buffer::generate_etag
!ll&&!rl&&r
010
$CGI::Buffer::send_body and $CGI::Buffer::status == $HTTP_OK
!ll&&!rl&&r
001
defined $CGI::Buffer::headers && $CGI::Buffer::headers =~ /^ETag:/imu
!ll&&!rl&&r
000
MC/DC0%0/5
$CGI::Buffer::send_body and $CGI::Buffer::status == $HTTP_OK and $CGI::Buffer::generate_etag and not defined $CGI::Buffer::headers && $CGI::Buffer::headers =~ /^ETag:/imu
$CGI::Buffer::send_body $CGI::Buffer::status == $HTTP_OK $CGI::Buffer::generate_etag defined $CGI::Buffer::headers $CGI::Buffer::headers =~ /^ETag:/imu
Truth table16%1/6
A and B and C and not(D && E)
A= $CGI::Buffer::send_bodyB= $CGI::Buffer::status == $HTTP_OKC= $CGI::Buffer::generate_etagD= defined $CGI::Buffer::headersE= $CGI::Buffer::headers =~ /^ETag:/imu
ABCDEresult
0XXXX0
10XXX0
110XX0
111110
1110X1
111101
508 0 _generate_etag();
509 }
510 1 ▶ unless($etag) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($CGI::Buffer::etag) 1 0 1
511 # Keep the quotes, they're part of the ETag and If-None-Match
512 # includes them
513 1 ▶ if(defined($headers) && ($headers =~ /^ETag:\s*("[^"]*")/mi)) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $CGI::Buffer::headers and $CGI::Buffer::headers =~ /^ETag:\s*("[^"]*")/imu) { } 0 1 1
elsif ($cache_hash) { } 1 0 1
Condition33%1/3
defined $CGI::Buffer::headers and $CGI::Buffer::headers =~ /^ETag:\s*("[^"]*")/imu
!ll&&!rl&&r
010
MC/DC0%0/2
defined $CGI::Buffer::headers and $CGI::Buffer::headers =~ /^ETag:\s*("[^"]*")/imu
defined $CGI::Buffer::headers $CGI::Buffer::headers =~ /^ETag:\s*("[^"]*")/imu
Truth table33%1/3
A and B
A= defined $CGI::Buffer::headersB= $CGI::Buffer::headers =~ /^ETag:\s*("[^"]*")/imu
ABresult
0X0
100
111
514 0 $etag = $1;
515 } elsif($cache_hash) {
516 1 $etag = $cache_hash->{'etag'};
517 }
518 }
519  
520 # Nothing has been output yet, so we can check if it's OK to send 304.
521 # RFC 9110 13.1.3 says not to look at the date if there's an
522 # If-None-Match
523 1 ▶ if($status == $HTTP_OK) {
Branch: 1 branch
BranchTrueFalseTotal
if ($CGI::Buffer::status == $HTTP_OK) 1 0 1
524 1 ▶ if($ENV{'HTTP_IF_NONE_MATCH'} && defined($etag)) {
Branch: 2 branches
BranchTrueFalseTotal
if ($ENV{'HTTP_IF_NONE_MATCH'} and defined $CGI::Buffer::etag) { } 0 1 1
elsif ($ENV{'HTTP_IF_MODIFIED_SINCE'} and $CGI::Buffer::cobject) { } 0 2 2
Condition33%1/3
$ENV{"HTTP_IF_NONE_MATCH"} and defined $CGI::Buffer::etag
!ll&&!rl&&r
100
MC/DC0%0/2
$ENV{"HTTP_IF_NONE_MATCH"} and defined $CGI::Buffer::etag
$ENV{"HTTP_IF_NONE_MATCH"} defined $CGI::Buffer::etag
Truth table33%1/3
A and B
A= $ENV{"HTTP_IF_NONE_MATCH"}B= defined $CGI::Buffer::etag
ABresult
0X0
100
111
525 0 ▶ _check_if_none_match() if($generate_304);
Branch: 1 branch
BranchTrueFalseTotal
if $CGI::Buffer::generate_304 0 0 0
526 ▶ } elsif($ENV{'HTTP_IF_MODIFIED_SINCE'} && $cobject) {
Condition33%1/3
$ENV{"HTTP_IF_MODIFIED_SINCE"} and $CGI::Buffer::cobject
!ll&&!rl&&r
100
MC/DC0%0/2
$ENV{"HTTP_IF_MODIFIED_SINCE"} and $CGI::Buffer::cobject
$ENV{"HTTP_IF_MODIFIED_SINCE"} $CGI::Buffer::cobject
Truth table33%1/3
A and B
A= $ENV{"HTTP_IF_MODIFIED_SINCE"}B= $CGI::Buffer::cobject
ABresult
0X0
100
111
527 0 _check_modified_since($cobject->created_at());
528 }
529 }
530  
531 # A 304 has no body to compress, and mustn't say that it has
532 1 ▶ _compress(_choose_encoding()) if(($status == $HTTP_OK) && $send_body);
Branch: 1 branch
BranchTrueFalseTotal
if $CGI::Buffer::status == $HTTP_OK and $CGI::Buffer::send_body 1 0 1
Condition33%1/3
$CGI::Buffer::status == $HTTP_OK and $CGI::Buffer::send_body
!ll&&!rl&&r
001
MC/DC0%0/2
$CGI::Buffer::status == $HTTP_OK and $CGI::Buffer::send_body
$CGI::Buffer::status == $HTTP_OK $CGI::Buffer::send_body
Truth table33%1/3
A and B
A= $CGI::Buffer::status == $HTTP_OKB= $CGI::Buffer::send_body
ABresult
0X0
100
111
533  
534 1 ▶ if($cobject && ($status == $HTTP_OK) && $generate_last_modified) {
Branch: 1 branch
BranchTrueFalseTotal
if ($CGI::Buffer::cobject and $CGI::Buffer::status == $HTTP_OK and $CGI::Buffer::generate_last_modified) 1 0 1
Condition33%2/6
$CGI::Buffer::cobject and $CGI::Buffer::status == $HTTP_OK and $CGI::Buffer::generate_last_modified
!ll&&!rl&&r
001
$CGI::Buffer::cobject and $CGI::Buffer::status == $HTTP_OK
!ll&&!rl&&r
001
MC/DC0%0/3
$CGI::Buffer::cobject and $CGI::Buffer::status == $HTTP_OK and $CGI::Buffer::generate_last_modified
$CGI::Buffer::cobject $CGI::Buffer::status == $HTTP_OK $CGI::Buffer::generate_last_modified
Truth table25%1/4
A and B and C
A= $CGI::Buffer::cobjectB= $CGI::Buffer::status == $HTTP_OKC= $CGI::Buffer::generate_last_modified
ABCresult
0XX0
10X0
1100
1111
535 1 _log('debug', 'Set Last-Modified to ', _http_date($cobject->created_at()));
536 1 push @o, 'Last-Modified: ' . _http_date($cobject->created_at());
537 }
538 }
539  
540 # Purpose: store the page that the script generated in the server-side cache
541 # Entry criteria: $key is the cache key, $unzipped_body the page to store
542 # Exit status: none
543 # Side effects: writes to the cache, adds Last-Modified and X-Cache headers to @o
544 1 ▶sub _store_in_cache {
Subroutine _store_in_cache: called CC=12 SCAR=29.2
545 1 my ($key, $unzipped_body) = @_;
546  
547 1 ▶ if($status == $HTTP_OK) {
Branch: 1 branch
BranchTrueFalseTotal
if ($CGI::Buffer::status == $HTTP_OK) 1 0 1
548 # It would be great if CHI::set() allowed the time to be 'lru'
549 # for least recently used.
550 1 ▶ $cache_duration ||= $DEFAULT_CACHE_DURATION;
Condition33%1/3
$CGI::Buffer::cache_duration ||= $DEFAULT_CACHE_DURATION
l!l&&r!l&&!r
010
MC/DC0%0/2
$CGI::Buffer::cache_duration ||= $DEFAULT_CACHE_DURATION
$CGI::Buffer::cache_duration $DEFAULT_CACHE_DURATION
Truth table33%1/3
A ||= B
A= $CGI::Buffer::cache_durationB= $DEFAULT_CACHE_DURATION
ABresult
1X1
011
000
551  
552 1 my $storable = _is_storable($headers, $unzipped_body);
553 1 ▶ if($storable) {
Branch: 1 branch
BranchTrueFalseTotal
if ($storable) 1 0 1
554 1 my $cache_hash = { body => $unzipped_body };
555  
556 # Remember, we're storing the UNzipped version in the
557 # cache, so leave out what's about this response's
558 # encoding and length. Blank lines would end the headers
559 my @stored = grep {
560 1 ▶ length && !/^(?:Content-Encoding|Content-Length|Content-Range):/i &&
Branch: 1 branch
BranchTrueFalseTotal
defined $CGI::Buffer::headers ? : 1 0 1
Condition33%2/6
length $_ && !/^(?:Content-Encoding|Content-Length|Content-Range):/iu && !/^Vary:\s*Accept-Encoding\s*$/iu
!ll&&!rl&&r
001
length $_ and not /^(?:Content-Encoding|Content-Length|Content-Range):/iu
!ll&&!rl&&r
001
MC/DC0%0/3
length $_ && !/^(?:Content-Encoding|Content-Length|Content-Range):/iu && !/^Vary:\s*Accept-Encoding\s*$/iu
length $_ not /^(?:Content-Encoding|Content-Length|Content-Range):/iu !/^Vary:\s*Accept-Encoding\s*$/iu
Truth table25%1/4
A and not(B) && not(C)
A= length $_B= not /^(?:Content-Encoding|Content-Length|Content-Range):/iuC= !/^Vary:\s*Accept-Encoding\s*$/iu
ABCresult
0XX0
10X0
1100
1111
561 !/^Vary:\s*Accept-Encoding\s*$/i
562 } ((defined($headers) ? split(/\r?\n/, $headers) : ()), @o);
563 1 ▶ $cache_hash->{'headers'} = join("\r\n", @stored) if(scalar(@stored));
Branch: 1 branch
BranchTrueFalseTotal
if scalar @stored 1 0 1
564  
565 1 ▶ if($generate_etag) {
Branch: 1 branch
BranchTrueFalseTotal
if ($CGI::Buffer::generate_etag) 0 1 1
566 0 _generate_etag();
567 0 $cache_hash->{'etag'} = $etag;
568 }
569 1 _log('debug', "Store $key in the cache, age = $cache_duration ", length($cache_hash->{'body'}), ' bytes');
570 1 ▶ _try('storing in the cache', sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
571 1 $cache->set($key, Storable::freeze($cache_hash), $cache_duration);
572 1 });
573 }
574 1 ▶ if($generate_last_modified) {
Branch: 1 branch
BranchTrueFalseTotal
if ($CGI::Buffer::generate_last_modified) 1 0 1
575 # The time it was stored, or now if it wasn't
576 1 ▶ $cobject = $storable ? _cache_lookup($key) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$storable ? : 1 0 1
577 1 ▶ push @o, 'Last-Modified: ' . _http_date(defined($cobject) ? $cobject->created_at() : time);
Branch: 1 branch
BranchTrueFalseTotal
defined $CGI::Buffer::cobject ? : 1 0 1
578 }
579 }
580 1 push @o, @{_x_cache_headers('MISS', 'MISS')}, _buffer_header('Miss');
581 }
582  
583 # Purpose: add the ETag header, if there is one to send
584 # Entry criteria: $etag is the ETag of the uncompressed body, if one was made
585 # Exit status: none
586 # Side effects: adds to @o
587 22 ▶sub _add_etag_header {
Subroutine _add_etag_header: called CC=8 SCAR=21.6
588 22 ▶ if($generate_etag && defined($etag) && ((!defined($headers)) || ($headers !~ /^ETag:/mi))) {
Branch: 1 branch
BranchTrueFalseTotal
if ($CGI::Buffer::generate_etag and defined $CGI::Buffer::etag and not defined $CGI::Buffer::headers && $CGI::Buffer::headers =~ /^ETag:/imu) 6 16 22
Condition55%5/9
$CGI::Buffer::generate_etag and defined $CGI::Buffer::etag and not defined $CGI::Buffer::headers && $CGI::Buffer::headers =~ /^ETag:/imu
!ll&&!rl&&r
1606
$CGI::Buffer::generate_etag and defined $CGI::Buffer::etag
!ll&&!rl&&r
1606
defined $CGI::Buffer::headers && $CGI::Buffer::headers =~ /^ETag:/imu
!ll&&!rl&&r
060
MC/DC25%1/4
$CGI::Buffer::generate_etag and defined $CGI::Buffer::etag and not defined $CGI::Buffer::headers && $CGI::Buffer::headers =~ /^ETag:/imu
$CGI::Buffer::generate_etag defined $CGI::Buffer::etag defined $CGI::Buffer::headers $CGI::Buffer::headers =~ /^ETag:/imu
Truth table40%2/5
A and B and not(C && D)
A= $CGI::Buffer::generate_etagB= defined $CGI::Buffer::etagC= defined $CGI::Buffer::headersD= $CGI::Buffer::headers =~ /^ETag:/imu
ABCDresult
0XXX0
10XX0
11110
110X1
11101
589 # The compressed and the uncompressed versions aren't the same
590 # bytes, so can't have the same strong ETag.
591 # _check_if_none_match() removes the suffix again, and a 304 is
592 # about the copy that the client has so gives back its ETag
593 6 ▶ my $e = defined($matched_etag) ? $matched_etag : $etag;
Branch: 1 branch
BranchTrueFalseTotal
defined $CGI::Buffer::matched_etag ? : 2 4 6
594 6 ▶ $e =~ s/"$/-$content_encoding"/ if($content_encoding && !defined($matched_etag));
Branch: 1 branch
BranchTrueFalseTotal
if $CGI::Buffer::content_encoding and not defined $CGI::Buffer::matched_etag 1 5 6
Condition66%2/3
$CGI::Buffer::content_encoding and not defined $CGI::Buffer::matched_etag
!ll&&!rl&&r
501
MC/DC50%1/2
$CGI::Buffer::content_encoding and not defined $CGI::Buffer::matched_etag
$CGI::Buffer::content_encoding not defined $CGI::Buffer::matched_etag
Truth table66%2/3
A and not(B)
A= $CGI::Buffer::content_encodingB= not defined $CGI::Buffer::matched_etag
ABresult
0X0
100
111
595 6 push @o, "ETag: $e";
596 6 _log('debug', "Set ETag to $e");
597 }
598 }
599  
600 # Purpose: print the response
601 # Entry criteria: $headers, @o, $body and $send_body are final
602 # Exit status: none
603 # Side effects: prints to the original output, sets $sent
604 22 ▶sub _emit {
Subroutine _emit: called CC=9 SCAR=22.0
605 22 my $body_length = 0;
606 22 ▶ if(defined($body)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $CGI::Buffer::body) 21 1 22
607 21 $body = _to_bytes($body);
608 21 $body_length = length($body);
609 }
610 22 ▶ my $with_body = $body_length && $send_body;
Condition100%3/3
$body_length && $CGI::Buffer::send_body
!ll&&!rl&&r
2317
MC/DC100%2/2
$body_length && $CGI::Buffer::send_body
$body_length $CGI::Buffer::send_body
Truth table100%3/3
A && B
A= $body_lengthB= $CGI::Buffer::send_body
ABresult
0X0
100
111
611  
612 22 ▶ if(defined($headers) && length($headers)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $CGI::Buffer::headers and length $CGI::Buffer::headers) { } 21 1 22
Condition66%2/3
defined $CGI::Buffer::headers and length $CGI::Buffer::headers
!ll&&!rl&&r
0121
MC/DC50%1/2
defined $CGI::Buffer::headers and length $CGI::Buffer::headers
defined $CGI::Buffer::headers length $CGI::Buffer::headers
Truth table66%2/3
A and B
A= defined $CGI::Buffer::headersB= length $CGI::Buffer::headers
ABresult
0X0
100
111
613 # Put the original headers first, then those generated within
614 # CGI::Buffer. The script is free to end its lines with \n
615 21 unshift @o, grep { length } split(/\r?\n/, $headers);
616  
617 # The body may well have changed since the script worked out its
618 # length
619 21 ▶ @o = grep { !/^Content-Length:/i } @o if(defined($body));
Branch: 1 branch
BranchTrueFalseTotal
if defined $CGI::Buffer::body 20 1 21
620 21 ▶ push @o, "Content-Length: $body_length" if($with_body);
Branch: 1 branch
BranchTrueFalseTotal
if $with_body 17 4 21
621 21 _set_status_header();
622 } else {
623 1 push @o, _buffer_header('No headers');
624 }
625  
626 22 $sent = 1;
627 22 ▶ print join("\r\n", @o, ($with_body ? ('', $body) : ()));
Branch: 1 branch
BranchTrueFalseTotal
$with_body ? : 17 5 22
628  
629 # Without a body, a blank line must still end the headers
630 22 ▶ print "\r\n\r\n" unless($with_body);
Branch: 1 branch
BranchTrueFalseTotal
unless $with_body 5 17 22
631 }
632  
633 # Purpose: answer If-Modified-Since
634 # Entry criteria: $modified is when the page was last changed, the request has
635 # an If-Modified-Since header
636 # Exit status: none
637 # Side effects: may set a 304 status, see _answer_without_body()
638 2 ▶sub _check_modified_since {
Subroutine _check_modified_since: called CC=8 SCAR=24.5
639 2 my $modified = shift;
640  
641 2 _log('trace', 'In _check_modified_since');
642  
643 # RFC 9110 13.1.3: If-Modified-Since is ignored for other methods
644 2 ▶ return unless($generate_304 && _is_safe_method() && defined($modified));
Branch: 1 branch
BranchTrueFalseTotal
unless $CGI::Buffer::generate_304 and _is_safe_method() and defined $modified 0 2 2
Condition33%2/6
$CGI::Buffer::generate_304 and _is_safe_method() and defined $modified
!ll&&!rl&&r
002
$CGI::Buffer::generate_304 and _is_safe_method()
!ll&&!rl&&r
002
MC/DC0%0/3
$CGI::Buffer::generate_304 and _is_safe_method() and defined $modified
$CGI::Buffer::generate_304 _is_safe_method() defined $modified
Truth table25%1/4
A and B and C
A= $CGI::Buffer::generate_304B= _is_safe_method()C= defined $modified
ABCresult
0XX0
10X0
1100
1111
645  
646 # An invalid date is ignored
647 2 my $since = _parse_http_date($ENV{'HTTP_IF_MODIFIED_SINCE'});
648 2 ▶ return unless(defined($since));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $since 1 1 2
649  
650 # If the script has been updated since, it may produce different output
651 1 my $age = _my_age();
652 1 ▶ if(defined($age) && ($age <= $since) && ($modified <= $since)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $age and $age <= $since and $modified <= $since) 1 0 1
Condition33%2/6
defined $age and $age <= $since and $modified <= $since
!ll&&!rl&&r
001
defined $age and $age <= $since
!ll&&!rl&&r
001
MC/DC0%0/3
defined $age and $age <= $since and $modified <= $since
defined $age $age <= $since $modified <= $since
Truth table25%1/4
A and B and C
A= defined $ageB= $age <= $sinceC= $modified <= $since
ABCresult
0XX0
10X0
1100
1111
653 1 _answer_without_body($HTTP_NOT_MODIFIED);
654 }
655 }
656  
657 # Purpose: answer If-None-Match
658 # Entry criteria: $etag is the ETag of the page
659 # Exit status: true if a 304 or 412 is to be sent
660 # Side effects: may set a status, see _answer_without_body(). Sets $matched_etag
661 2 ▶sub _check_if_none_match {
Subroutine _check_if_none_match: called CC=9 SCAR=25.1
662 2 my $matched = 0;
663  
664 2 ▶ if($ENV{'HTTP_IF_NONE_MATCH'} && defined($etag)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{"HTTP_IF_NONE_MATCH"} and defined $CGI::Buffer::etag) 2 0 2
Condition33%1/3
$ENV{"HTTP_IF_NONE_MATCH"} and defined $CGI::Buffer::etag
!ll&&!rl&&r
002
MC/DC0%0/2
$ENV{"HTTP_IF_NONE_MATCH"} and defined $CGI::Buffer::etag
$ENV{"HTTP_IF_NONE_MATCH"} defined $CGI::Buffer::etag
Truth table33%1/3
A and B
A= $ENV{"HTTP_IF_NONE_MATCH"}B= defined $CGI::Buffer::etag
ABresult
0X0
100
111
665 2 _log('debug', "Compare $ENV{HTTP_IF_NONE_MATCH} with $etag");
666  
667 # The header is "*" or a list of entity tags, any of which may be
668 # weak. If-None-Match uses the weak comparison (RFC 9110 8.8.3.2),
669 # under which the compressed version of a page matches
670 2 foreach my $tag(split(/\s*,\s*/, $ENV{'HTTP_IF_NONE_MATCH'})) {
671 2 (my $client_etag = $tag) =~ s/^W\///;
672 2 (my $e = $client_etag) =~ s/$ENCODED_ETAG_SUFFIX/"/;
673 2 ▶ if($e eq $etag) {
Branch: 1 branch
BranchTrueFalseTotal
if ($e eq $CGI::Buffer::etag) 2 0 2
674 2 $matched_etag = $client_etag;
675 2 $matched = 1;
676 2 last;
677 }
678 0 ▶ $matched = 1 if($e eq '*');
Branch: 1 branch
BranchTrueFalseTotal
if $e eq "*" 0 0 0
679 }
680 # RFC 9110 13.1.2: 304 is only for GET and HEAD
681 2 ▶ _answer_without_body(_is_safe_method() ? $HTTP_NOT_MODIFIED : $HTTP_PRECONDITION_FAILED) if($matched);
Branch: 2 branches
BranchTrueFalseTotal
if $matched 2 0 2
_is_safe_method() ? : 2 0 2
682 }
683 2 ▶ _log_diffs() unless($matched);
Branch: 1 branch
BranchTrueFalseTotal
unless $matched 0 2 2
684 2 return $matched;
685 }
686  
687 # Purpose: when debugging, log how a page differs from its copy in the cache
688 # Entry criteria: none, it only does something if the logger is debugging
689 # Exit status: none
690 # Side effects: reads the cache, writes to the logger
691 0 ▶sub _log_diffs {
Subroutine _log_diffs: not called CC=6 SCAR=37.4
692 0 ▶ return unless($cache && $logger && $logger->can('is_debug') && $logger->is_debug() && _can_load('Text::Diff'));
Branch: 1 branch
BranchTrueFalseTotal
unless $CGI::Buffer::cache and $CGI::Buffer::logger and $CGI::Buffer::logger->can("is_debug") and $CGI::Buffer::logger->is_debug and _can_load("Text::Diff") 0 0 0
Condition0%0/12
$CGI::Buffer::cache and $CGI::Buffer::logger and $CGI::Buffer::logger->can("is_debug") and $CGI::Buffer::logger->is_debug and _can_load("Text::Diff")
!ll&&!rl&&r
000
$CGI::Buffer::cache and $CGI::Buffer::logger and $CGI::Buffer::logger->can("is_debug") and $CGI::Buffer::logger->is_debug
!ll&&!rl&&r
000
$CGI::Buffer::cache and $CGI::Buffer::logger and $CGI::Buffer::logger->can("is_debug")
!ll&&!rl&&r
000
$CGI::Buffer::cache and $CGI::Buffer::logger
!ll&&!rl&&r
000
MC/DC0%0/5
$CGI::Buffer::cache and $CGI::Buffer::logger and $CGI::Buffer::logger->can("is_debug") and $CGI::Buffer::logger->is_debug and _can_load("Text::Diff")
$CGI::Buffer::cache $CGI::Buffer::logger $CGI::Buffer::logger->can("is_debug") $CGI::Buffer::logger->is_debug _can_load("Text::Diff")
Truth table0%0/6
A and B and C and D and E
A= $CGI::Buffer::cacheB= $CGI::Buffer::loggerC= $CGI::Buffer::logger->can("is_debug")D= $CGI::Buffer::logger->is_debugE= _can_load("Text::Diff")
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
693  
694 0 ▶ _try('comparing with the cache', sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
695 0 my $cached_copy = $cache->get(_generate_key());
696  
697 0 ▶ if($cached_copy && $body) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cached_copy and $CGI::Buffer::body) { } 0 0 0
Condition0%0/3
$cached_copy and $CGI::Buffer::body
!ll&&!rl&&r
000
MC/DC0%0/2
$cached_copy and $CGI::Buffer::body
$cached_copy $CGI::Buffer::body
Truth table0%0/3
A and B
A= $cached_copyB= $CGI::Buffer::body
ABresult
0X0
100
111
698 0 require Storable;
699  
700 0 $cached_copy = Storable::thaw($cached_copy)->{body};
701 0 $logger->debug('diffs: ', Text::Diff::diff(\$body, \$cached_copy));
702 } else {
703 0 $logger->debug('Nothing to compare');
704 }
705 0 });
706 }
707  
708 # Purpose: send a status that has no body, e.g. 304
709 # Entry criteria: $code is the HTTP status
710 # Exit status: none
711 # Side effects: adds a Status header to @o, sets $status and $send_body
712 3 ▶sub _answer_without_body {
Subroutine _answer_without_body: called CC=1 SCAR=0.0
713 3 my $code = shift;
714  
715 3 push @o, _status_line($code);
716 3 _set_status($code);
717 3 $send_body = 0;
718 3 _log('debug', "Set status to $code");
719 }
720  
721 # Purpose: optimise HTML, i.e. make it smaller without changing what it shows
722 # Entry criteria: $body is HTML, $optimise_content is set
723 # Exit status: none
724 # Side effects: changes $body, loads HTML::Packer and maybe CGI::Info
725 16 ▶sub _optimise_html {
Subroutine _optimise_html: called CC=5 SCAR=16.1
726 16 require HTML::Packer; # Overkill using HTML::Clean and HTML::Packer...
727  
728 16 _log('trace', 'Packer');
729  
730 # Whitespace is significant in these, in a <textarea> it's the user's data
731 16 my $preformatted = _protect_preformatted();
732  
733 # Level 1 is one pass, higher levels repeat until the body stops
734 # shrinking
735 16 my $oldlength = length($body);
736 16 _optimise_content();
737 16 ▶ if($optimise_content >= $AGGRESSIVE_OPTIMISATION) {
Branch: 1 branch
BranchTrueFalseTotal
if ($CGI::Buffer::optimise_content >= $AGGRESSIVE_OPTIMISATION) 1 15 16
738 1 ▶ while(length($body) < $oldlength) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $CGI::Buffer::body < $oldlength) 2 1 3
739 2 $oldlength = length($body);
740 2 _optimise_content();
741 }
742 }
743 16 _shorten_links();
744  
745 # Don't use HTML::Clean because of RT402.
746 # Don't always do javascript 'best' since it's confused by the common
747 # <!-- HIDE technique.
748 # See https://github.com/nevesenin/javascript-packer-perl/issues/1#issuecomment-4356790
749 16 my $options = {
750 remove_comments => 1,
751 remove_newlines => 0,
752 do_stylesheet => 'minify'
753 };
754 16 ▶ if($optimise_content >= $AGGRESSIVE_OPTIMISATION) {
Branch: 1 branch
BranchTrueFalseTotal
if ($CGI::Buffer::optimise_content >= $AGGRESSIVE_OPTIMISATION) 1 15 16
755 1 $options->{do_javascript} = 'best';
756 # [^>] stops the tag running on into the rest of the page
757 1 $body =~ s/(<script[^>]*+>)\s*+<!--/$1/gi;
758 1 $body =~ s/\/\/-->\s*+<\/script>/<\/script>/gi;
759 1 $body =~ s/(<script[^>]*+>)\s++/$1/gi;
760 }
761 16 $body = HTML::Packer->init()->minify(\$body, $options);
762 16 ▶ _merge_document_writes() if($optimise_content >= $AGGRESSIVE_OPTIMISATION);
Branch: 1 branch
BranchTrueFalseTotal
if $CGI::Buffer::optimise_content >= $AGGRESSIVE_OPTIMISATION 1 15 16
763  
764 16 _restore_preformatted($preformatted);
765 }
766  
767 # Purpose: make links to this site local, e.g. on http://www.example.com change
768 # http://www.example.com/foo/bar.htm to /foo/bar.htm
769 # Entry criteria: $body is HTML
770 # Exit status: none
771 # Side effects: changes $body, may create $info
772 16 ▶sub _shorten_links {
Subroutine _shorten_links: called CC=2 SCAR=7.0
773 16 my $site_info = _info();
774 16 my $host = $site_info->host_name();
775 16 ▶ my $protocol = $site_info->protocol() || $DEFAULT_PROTOCOL;
Condition66%2/3
$site_info->protocol || $DEFAULT_PROTOCOL
l!l&&r!l&&!r
790
MC/DC0%0/2
$site_info->protocol || $DEFAULT_PROTOCOL
$site_info->protocol $DEFAULT_PROTOCOL
Truth table66%2/3
A || B
A= $site_info->protocolB= $DEFAULT_PROTOCOL
ABresult
1X1
011
000
776  
777 # The attribute can be anywhere in the tag, e.g. <img border=0 src=...>.
778 # [^<>] keeps each match inside one tag, so hostile input can't make it
779 # search the rest of the page for each tag
780 16 my $attribute = qr/(<(?:a|img)\b[^<>]*?\s(?:href|src)\s*=\s*")/i;
781  
782 # The host name must be followed by the end of the link, or the start of
783 # its path, query or fragment, otherwise www.example.com.evil.org would
784 # become local
785 16 $body =~ s/$attribute\Q$protocol\E:\/\/\Q$host\E"/$1\/"/gi;
786 16 $body =~ s/$attribute\Q$protocol\E:\/\/\Q$host\E(?=[\/?#])/$1/gi;
787 }
788  
789 # Purpose: change document.write("a"); document.write("b") into
790 # document.write("a"+"b");
791 # Entry criteria: $body is HTML that HTML::Packer has minified
792 # Exit status: none
793 # Side effects: changes $body
794 1 ▶sub _merge_document_writes {
Subroutine _merge_document_writes: called CC=2 SCAR=6.9
795 # Every substitution shortens the body, so this always terminates.
796 # Nothing may cross a </script>, otherwise writes in different scripts
797 # get merged
798 1 ▶ 1 while($body =~ s{
Branch: 1 branch
BranchTrueFalseTotal
$CGI::Buffer::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)]gisux and do { 1 } 2 1 3
799 (<script\s+type\s*=\s*"text/javascript"\s*>) # $1: opening tag, kept as written
800 ((?:(?!</script>).)*?) # $2: code before the writes, within this script
801 document\.write\(((?:(?!</script>)[^;])*?)\);\s*+ # $3: first argument
802 document\.write\(((?:(?!</script>)[^;])*?)\) # $4: second argument
803 }{$1${2}document.write($3+$4)}gisx);
804 }
805  
806 # Purpose: check HTML with HTML::Lint, and send the errors instead of the page
807 # Entry criteria: $body is HTML, $lint_content is set
808 # Exit status: none
809 # Side effects: on errors, replaces $headers, @o and $body with a 500 and the
810 # list of errors, and gives a warning for each
811 3 ▶sub _lint_html {
Subroutine _lint_html: called CC=3 SCAR=11.0
812 3 require HTML::Lint;
813 3 HTML::Lint->import;
814  
815 3 _log('trace', 'Lint');
816 3 my $lint = HTML::Lint->new();
817 3 $lint->parse($body);
818 3 $lint->eof();
819  
820 3 ▶ if($lint->errors) {
Branch: 1 branch
BranchTrueFalseTotal
if ($lint->errors) 1 2 3
821 1 $headers = _status_line($HTTP_INTERNAL_SERVER_ERROR);
822 1 @o = ('Content-type: text/plain');
823 1 $body = '';
824 1 foreach my $error ($lint->errors) {
825 3 my $args = { where => $error->where(), text => $error->errtext() };
826 3 _problem('lint', $args);
827 3 $body .= "$args->{where}: $args->{text}\n";
828 }
829 }
830 }
831  
832 # Purpose: reduce output, e.g. remove superfluous white-space
833 # Entry criteria: $body is HTML, with <pre> and <textarea> protected
834 # Exit status: none
835 # Side effects: changes $body
836 18 ▶sub _optimise_content {
Subroutine _optimise_content: called CC=1 SCAR=0.0
837 # Remove whitespace around newlines. Possessive quantifiers and only
838 # starting at the beginning of a run of whitespace keep it linear.
839 # A "+" at the start of a line is JavaScript, so is left alone
840 18 $body =~ s{
841 (?<![^\S\n]) # start only at the beginning of a whitespace run
842 [^\S\n]*+ # trailing spaces, tabs and \r before the newline
843 \n
844 \s*+ # blank lines and indentation after it
845 }{\n}gx;
846 18 $body =~ s/\<\/div\>\s+\<div/\<\/div\>\<div/gis;
847  
848 # In these, (?<!\s) and possessive quantifiers stop each alternation
849 # being retried at every position inside a long run of whitespace
850 18 $body =~ s/(?:<div>\s++|(?<!\s)\s++<div>)/<div>/gi;
851 18 $body =~ s/\s+<\/div\>/\<\/div\>/gis; # Remove spaces before </div>
852  
853 # Whitespace around a paragraph, which may have attributes, isn't
854 # shown. \b stops <pre> and <param> matching, [^<>] stops the tag
855 # running on into the rest of the page
856 18 $body =~ s/(?<!\s)\s++(<p\b[^<>]*+>)/$1/gi;
857 18 $body =~ s/(<p\b[^<>]*+>)\s++/$1/gi;
858 18 $body =~ s/(?:(?<!\s)\s++<\/p>|<\/p>\s++)/<\/p>/gi;
859  
860 # The structure of the page
861 18 $body =~ s/<html>\s+<head>/<html><head>/is;
862 18 $body =~ s/(?<!\s)\s*+<\/head>\s++<body>\s*+/<\/head><body>/i;
863 18 $body =~ s/<html>\s+<body>/<html><body>/is;
864 18 $body =~ s/<body>\s+/<body>/is;
865 18 $body =~ s/\s+\<\/html/\<\/html/is;
866 18 $body =~ s/\s+\<\/body/\<\/body/is;
867  
868 # Spaces between tags can be visible, e.g. "Hello <b>a</b> <i>b</i>",
869 # so they're only removed around the block elements below
870 18 $body =~ s/\<\/tr\>\s\<tr\>/\<\/tr\>\<tr\>/gi;
871 18 $body =~ s/\<\/td\>\s\<\/tr\>/\<\/td\>\<\/tr\>/gi;
872 18 $body =~ s/\<\/td\>\s*\<td\>/\<\/td\>\<td\>/gis;
873 18 $body =~ s/\<\/tr\>\s\<\/table\>/\<\/tr\>\<\/table\>/gi;
874 18 $body =~ s/\<td\>\s/\<td\>/gi;
875 18 $body =~ s/\<br\s?\/?\>\s?\<p\>/\<p\>/gi;
876 18 $body =~ s/\<br\>\s+/\<br\>/gi;
877 18 $body =~ s/\s+\<br/\<br/gi;
878 18 $body =~ s/\<br\s?\/\>\s/\<br \/\>/gi;
879 18 $body =~ s/[ \t]+/ /gs; # Remove duplicate space, don't use \s+ it breaks JavaScript
880 18 $body =~ s/\s\<script/\<script/gi;
881 18 $body =~ s/(<script>\s|\s<script>)/<script>/gis;
882 18 $body =~ s/(<\/script>\s|\s<\/script>)/<\/script>/gis;
883  
884 # A link can't leave its quotes, so these can't span tags or backtrack
885 # across the rest of the page
886 18 $body =~ s{
887 (?<!\s)\s++ # a whole run of whitespace, starting at its first character
888 <a\shref="([^"]*+)"> # $1: the link
889 \s?
890 }{ <a href="$1">}gix;
891 18 $body =~ s{
892 \s?
893 <a\shref=\s"([^"]*+)"> # $1: the link
894 }{ <a href="$1">}gix;
895 18 $body =~ s/\s+<\/a\>\s+/<\/a> /gis;
896 18 $body =~ s/(?:\s?<hr>\s++|(?<!\s)\s++<hr>\s?)/<hr>/gi;
897  
898 # Lists
899 18 $body =~ s/<\/li>\s+<li>/<\/li><li>/gis;
900 18 $body =~ s/<\/li>\s+<\/ul>/<\/li><\/ul>/gis;
901 18 $body =~ s/<ul>\s+<li>/<ul><li>/gis;
902 18 $body =~ s/\s+<\/li>/<\/li>/gis;
903 18 $body =~ s/\<\/option\>\s+\<option/\<\/option\>\<option/gis;
904  
905 # A title can't contain a tag. [^<] and the possessive quantifiers stop
906 # each unterminated <title> from being searched to the end of the page
907 18 $body =~ s{<title>\s*+([^<]*+)</title>}{
908 2 my $title = $1;
909 2 $title =~ s/(?<!\s)\s++\z//;
910 2 "<title>$title</title>"
911 }eix;
912 18 $body =~ s/<\/center>\s+<center>/ /gis;
913 }
914  
915 # Purpose: create a key for the cache, unless the caller gave one
916 # Entry criteria: none
917 # Exit status: the key
918 # Side effects: sets $cache_key, may create $info
919 7 ▶sub _generate_key {
Subroutine _generate_key: called CC=6 SCAR=33.7
920 7 ▶ unless($cache_key) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($CGI::Buffer::cache_key) 0 7 7
921 0 my $i = _info();
922 0 my $key = join('::', __PACKAGE__, $i->browser_type(), $i->domain_name(), $i->script_name(), $i->as_string());
923  
924 # /cgi-bin/foo.cgi/bar and /cgi-bin/foo.cgi/baz are different pages
925 0 ▶ $key .= "::PATH_INFO=$ENV{PATH_INFO}" if(defined($ENV{'PATH_INFO'}) && length($ENV{'PATH_INFO'}));
Branch: 1 branch
BranchTrueFalseTotal
if defined $ENV{"PATH_INFO"} and length $ENV{"PATH_INFO"} 0 0 0
Condition0%0/3
defined $ENV{"PATH_INFO"} and length $ENV{"PATH_INFO"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $ENV{"PATH_INFO"} and length $ENV{"PATH_INFO"}
defined $ENV{"PATH_INFO"} length $ENV{"PATH_INFO"}
Truth table0%0/3
A and B
A= defined $ENV{"PATH_INFO"}B= length $ENV{"PATH_INFO"}
ABresult
0X0
100
111
926 0 ▶ $key .= '::' . $lingua->language() if($lingua);
Branch: 1 branch
BranchTrueFalseTotal
if $CGI::Buffer::lingua 0 0 0
927  
928 # Different states of the client are stored in different caches
929 0 $key .= "::$_" foreach(@{_client_cookies()});
930  
931 # The key is needed before the script has given its headers, so a
932 # Vary header can't be part of it. _is_storable() doesn't store
933 # those pages
934 0 $key =~ s/\//::/g;
935 0 $key =~ s/(?:::){2,}/::/g;
936 0 $key =~ s/::$//;
937 0 _log('trace', "Returning $key");
938 0 $cache_key = $key;
939 }
940 7 return $cache_key;
941 }
942  
943 =head2 init
944  
945 Set various options and override default values.
946  
947 =head3 Purpose
948  
949 Configures CGI::Buffer. Options which affect the server-side cache must be given
950 before anything is printed; the others can be given at any time before the
951 script ends.
952  
953 =head3 Arguments
954  
955 A hash or a hash reference of options, any of which may be left out:
956  
957 =over 4
958  
959 =item * C<generate_etag> - send an ETag, and answer If-None-Match with 304.
960 By default, on if the protocol is HTTP/1.1 or later.
961  
962 =item * C<generate_last_modified> - send a Last-Modified header, default on.
963 It needs a cache or an C<info> object.
964  
965 =item * C<generate_304> - answer conditional requests with 304, default on.
966  
967 =item * C<compress_content> - compress the output if the client accepts it,
968 default on.
969  
970 =item * C<optimise_content> - 0 (default) leaves HTML alone, 1 optimises the
971 HTML and CSS, 2 also does aggressive JavaScript optimisations which may fail.
972  
973 =item * C<lint_content> - check the HTML with L<HTML::Lint>, default off.
974 Errors are sent to the client as a 500, so only use this when developing.
975  
976 =item * C<cache> - a server-side cache: an object that understands get_object(),
977 set(), get() and remove(), whose objects understand value() and created_at(),
978 such as a L<CHI> object. Undef turns the cache off.
979  
980 =item * C<cache_key> - the key for this page in the cache. If not given, one
981 is generated which may not be unique. It should be a unique value dependent
982 upon the values set by the browser.
983  
984 =item * C<cache_duration> - how long to keep pages in the cache, default
985 '10 minutes'. C<cache_age> is an old name for this.
986  
987 =item * C<logger> - an object that understands trace(), debug(), info(),
988 warn() and error(), such as a L<Log::Log4perl> logger.
989  
990 =item * C<lingua> - a L<CGI::Lingua> object; the language becomes part of the
991 generated cache key.
992  
993 =item * C<info> - a L<CGI::Info> object. One is created when needed if it isn't
994 given. It's only taken from the first call.
995  
996 =item * C<messages> - a hash of message keys to replacement text, e.g. to
997 translate the messages, see L</MESSAGES>.
998  
999 =back
1000  
1001 Items stay in the server-side cache by default for 10 minutes.
1002 This can be overridden by the max-age directive of the Cache-Control HTTP header
1003 in the request, if it's a number no larger than 600 seconds, and
1004 the default can be changed by the cache_duration argument to init().
1005  
1006 Responses aren't stored in the server-side cache if their headers include
1007 Set-Cookie,
1008 a Cache-Control of no-store, no-cache or private,
1009 or a Vary on anything other than Accept-Encoding
1010 (or Accept-Language when lingua is given),
1011 since they would be given to clients that they weren't meant for.
1012 Neither are HTML pages with no </html>,
1013 which suggests that the script died.
1014 A page that includes the value of the client's C<csrf_token> cookie is never
1015 stored.
1016 The C<csrf_token> and Google Analytics cookies aren't part of the generated
1017 cache key, other cookies and PATH_INFO are.
1018  
1019 =head3 Returns
1020  
1021 The string 'CGI::Buffer', so that calls can be chained, e.g.
1022 C<< CGI::Buffer::init(...)->is_cached() >>.
1023  
1024 =head3 Side Effects
1025  
1026 Sets the options for the rest of the request.
1027 Gives a warning for each unknown or invalid option, which is ignored,
1028 and if the cache is given after output has started.
1029  
1030 =head3 EXAMPLE
1031  
1032 # Put this toward the top of your program before you do anything
1033 use CHI;
1034 use CGI::Lingua;
1035 use CGI::Buffer;
1036  
1037 CGI::Buffer::init(
1038 generate_etag => 1, # make good use of client's cache
1039 generate_last_modified => 1, # more use of client's cache
1040 compress_content => 1, # gzip the output
1041 optimise_content => 0, # optimise your program's HTML, CSS and JavaScript
1042 cache => CHI->new(driver => 'File'), # cache requests
1043 cache_key => 'string', # key for the cache
1044 cache_duration => '10 minutes', # how long to store responses in the cache
1045 logger => $logger,
1046 lint_content => 0, # Pass through HTML::Lint
1047 generate_304 => 1, # Generate 304: Not modified
1048 lingua => CGI::Lingua->new(supported => ['en']),
1049 );
1050  
1051 Init allows a reference of the options to be passed. So both of these work:
1052  
1053 CGI::Buffer::init(generate_etag => 1);
1054 CGI::Buffer::init({ generate_etag => 1, info => CGI::Info->new() });
1055  
1056 Generally speaking, passing by reference is better since it copies less on to
1057 the stack.
1058  
1059 Alternatively you can give the options when loading the package:
1060  
1061 use CGI::Buffer { optimise_content => 1 };
1062  
1063 =head3 API SPECIFICATION
1064  
1065 =head4 INPUT
1066  
1067 {
1068 generate_etag => { type => 'boolean', optional => 1 },
1069 generate_last_modified => { type => 'boolean', optional => 1 },
1070 generate_304 => { type => 'boolean', optional => 1 },
1071 compress_content => { type => 'boolean', optional => 1 },
1072 lint_content => { type => 'boolean', optional => 1 },
1073 optimise_content => { type => 'integer', min => 0, optional => 1 },
1074 cache => { type => 'object', can => ['get_object', 'set'], optional => 1 },
1075 cache_key => { type => 'string', optional => 1 },
1076 cache_duration => { type => 'string', optional => 1 },
1077 cache_age => { type => 'string', optional => 1 },
1078 logger => { type => 'object', can => ['trace', 'debug', 'info', 'warn', 'error'], optional => 1 },
1079 lingua => { type => 'object', can => 'language', optional => 1 },
1080 info => { type => 'object', can => ['status', 'host_name'], optional => 1 },
1081 messages => { type => 'hashref', optional => 1 },
1082 }
1083  
1084 =head4 OUTPUT
1085  
1086 { type => 'string', value => 'CGI::Buffer' }
1087  
1088 =head3 MESSAGES
1089  
1090 Key Meaning Resolution
1091 -------------- ---------------------------------------- ---------------------------------
1092 unknown_option An option that init() doesn't know about Check the spelling, see above
1093 bad_option An option of the wrong type Pass the type listed above
1094 logger_method The logger lacks a method, so is ignored Use a logger with all five methods
1095 too_late The cache was set up after printing Call init() before printing
1096  
1097 =head3 FORMAL SPECIFICATION
1098  
1099 ┌─ Init ──────────────────────────────────────────────┐
1100 │ ΔOptions │
1101 │ params? : OPTION ⇸ VALUE │
1102 │ printed : ℕ │
1103 │ result! : STRING │
1104 ├─────────────────────────────────────────────────────┤
1105 │ valid == { o : dom params? | o ∈ dom INIT_OPTIONS ∧ │
1106 │ params?(o) ∈ INIT_OPTIONS(o) } │
1107 │ ∀ o : valid \ {cache} • options'(o) = params?(o) │
1108 │ cache ∈ valid ∧ params?(cache) = ⊥ ⇒ │
1109 │ options'(cache) = ⊥ │
1110 │ cache ∈ valid ∧ params?(cache) ≠ ⊥ ∧ can_cache ⇒ │
1111 │ options'(cache) = params?(cache) │
1112 │ result! = "CGI::Buffer" │
1113 └─────────────────────────────────────────────────────┘
1114  
1115 =head3 PSEUDOCODE
1116  
1117 get the options from a hash or a hash reference
1118 for each option
1119 warn about, and drop, those that are unknown or of the wrong type
1120 replace any messages first, so that the warnings below use them
1121 set each option that can be changed at any time
1122 if anything has been printed, warn that it's too late
1123 if the cache option was given
1124 if it's undef, turn the cache off
1125 else if this request may use the cache
1126 work out how long to keep pages for
1127 remember the cache and its key
1128 return 'CGI::Buffer'
1129  
1130 =cut
1131  
1132 # The options that can be changed at any time, and where they're kept. This
1133 # isn't Readonly, since that would also make the variables read only
1134 28 my %SAFE_OPTIONS = (
1135 generate_etag => \$generate_etag,
1136 generate_last_modified => \$generate_last_modified,
1137 generate_304 => \$generate_304,
1138 compress_content => \$compress_content,
1139 optimise_content => \$optimise_content,
1140 lint_content => \$lint_content,
1141 lingua => \$lingua,
1142 );
1143  
1144 20 ▶sub init {
Subroutine init: called CC=18 SCAR=34.6
Pod documented
1145 20 ▶ my %params = (ref($_[0]) eq 'HASH') ? %{$_[0]} : @_;
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 10 10 20
1146  
1147 # Messages go first, since they're used for the warnings that follow
1148 20 ▶ if(ref($params{messages}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params{"messages"} eq "HASH") 0 20 20
1149 0 %messages = (%messages, %{$params{messages}});
1150 }
1151 20 _check_options(\%params);
1152  
1153 # Safe options - can be given at any time
1154 20 foreach my $option(keys %SAFE_OPTIONS) {
1155 140 ▶ ${$SAFE_OPTIONS{$option}} = $params{$option} if(defined($params{$option}));
Branch: 1 branch
BranchTrueFalseTotal
if defined $params{$option} 25 115 140
1156 }
1157 20 ▶ if(defined($params{logger})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params{"logger"}) 1 19 20
1158 1 $logger = $params{logger};
1159 1 _check_logger();
1160 }
1161 20 ▶ $info = $params{info} if(defined($params{info}) && !defined($info));
Branch: 1 branch
BranchTrueFalseTotal
if defined $params{"info"} and not defined $CGI::Buffer::info 0 20 20
Condition33%1/3
defined $params{"info"} and not defined $CGI::Buffer::info
!ll&&!rl&&r
2000
MC/DC0%0/2
defined $params{"info"} and not defined $CGI::Buffer::info
defined $params{"info"} not defined $CGI::Buffer::info
Truth table33%1/3
A and not(B)
A= defined $params{"info"}B= not defined $CGI::Buffer::info
ABresult
0X0
100
111
1162  
1163 # Unsafe options - must be given before output has been started
1164 20 my $pos = $capture->getpos();
1165 20 ▶ _problem('too_late', { count => $pos }) if($pos > 0);
Branch: 1 branch
BranchTrueFalseTotal
if $pos > 0 1 19 20
1166  
1167 20 ▶ if(exists($params{cache})) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"cache"}) 3 17 20
1168 3 ▶ if(!defined($params{cache})) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $params{'cache'}) { } 0 3 3
elsif (can_cache()) { } 3 0 3
1169 0 ▶ _log('debug', 'disabling cache', ($cache_key ? " $cache_key" : ''));
Branch: 1 branch
BranchTrueFalseTotal
$CGI::Buffer::cache_key ? : 0 0 0
1170 0 $cache = undef;
1171 } elsif(can_cache()) {
1172 # There is an argument not to do this since one client will
1173 # affect others, so it's limited
1174 3 my $max_age = _client_max_age();
1175 3 ▶ 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) 0 3 3
Condition33%1/3
defined $max_age and $max_age <= $MAX_CLIENT_CACHE_SECONDS
!ll&&!rl&&r
300
MC/DC0%0/2
defined $max_age and $max_age <= $MAX_CLIENT_CACHE_SECONDS
defined $max_age $max_age <= $MAX_CLIENT_CACHE_SECONDS
Truth table33%1/3
A and B
A= defined $max_ageB= $max_age <= $MAX_CLIENT_CACHE_SECONDS
ABresult
0X0
100
111
1176 0 $cache_duration = "$max_age seconds";
1177 0 _log('debug', "cache_duration = $cache_duration");
1178 }
1179 3 ▶ $cache_duration ||= $params{'cache_duration'} || $params{'cache_age'};
Condition33%2/6
$CGI::Buffer::cache_duration ||= $params{"cache_duration"} || $params{"cache_age"}
l!l&&r!l&&!r
003
$params{'cache_duration'} || $params{'cache_age'}
l!l&&r!l&&!r
003
MC/DC0%0/3
$CGI::Buffer::cache_duration ||= $params{"cache_duration"} || $params{"cache_age"}
$CGI::Buffer::cache_duration $params{'cache_duration'} $params{'cache_age'}
Truth table0%0/4
A ||= B || C
A= $CGI::Buffer::cache_durationB= $params{'cache_duration'}C= $params{'cache_age'}
ABCresult
1XX1
01X1
0011
0000
1180 3 $cache = $params{cache};
1181 3 ▶ $cache_key = $params{cache_key} if(defined($params{cache_key}));
Branch: 1 branch
BranchTrueFalseTotal
if defined $params{"cache_key"} 3 0 3
1182 }
1183 }
1184 20 return __PACKAGE__;
1185 }
1186  
1187 # Purpose: check the options given to init()
1188 # Entry criteria: $params is a hashref of the options
1189 # Exit status: none
1190 # Side effects: gives a warning for, and deletes, each option that is unknown
1191 # or invalid
1192 20 ▶sub _check_options {
Subroutine _check_options: called CC=4 SCAR=16.6
1193 20 my $params = shift;
1194  
1195 20 foreach my $option(sort keys %{$params}) {
1196 32 my $rule = $INIT_OPTIONS{$option};
1197 32 ▶ if(!defined($rule)) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $rule) { } 0 32 32
elsif (defined(my $reason = _option_problem($params->{$option}, @{$rule;}))) { } 0 32 32
1198 0 _problem('unknown_option', { option => $option });
1199 0 delete $params->{$option};
1200 32 } elsif(defined(my $reason = _option_problem($params->{$option}, @{$rule}))) {
1201 0 _problem('bad_option', { option => $option, reason => $reason });
1202 0 delete $params->{$option};
1203 }
1204 }
1205 }
1206  
1207 # Purpose: check one value against a rule from %INIT_OPTIONS
1208 # Entry criteria: $value is the value, $type and @methods the rule. Undef is
1209 # always allowed, it means "leave this as it is", or no cache
1210 # Exit status: why the value isn't allowed, or undef if it is
1211 # Side effects: none
1212 32 ▶sub _option_problem {
Subroutine _option_problem: called CC=10 SCAR=30.0
1213 32 my ($value, $type, @methods) = @_;
1214  
1215 32 my $reason;
1216 32 ▶ if(!defined($value)) {
Branch: 5 branches
BranchTrueFalseTotal
if (not defined $value) { } 0 32 32
elsif ($type eq 'hash') { } 0 32 32
elsif ($type eq 'object') { } 4 28 32
elsif (ref $value) { } 0 28 28
elsif ($type eq 'count' and not $value =~ /^\d+$/u) { } 0 39 39
1217 # Allowed
1218 } elsif($type eq 'hash') {
1219 0 ▶ $reason = 'must be a hash reference' unless(ref($value) eq 'HASH');
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "HASH" 0 0 0
1220 } elsif($type eq 'object') {
1221 4 ▶ if(!Scalar::Util::blessed($value)) {
Branch: 2 branches
BranchTrueFalseTotal
if (not builtin::blessed($value)) { } 0 4 4
elsif (my(@missing) = grep({not $value->can($_);} @methods)) { } 0 4 4
1222 0 $reason = 'must be an object';
1223 6 } elsif(my @missing = grep { !$value->can($_) } @methods) {
1224 0 $reason = 'must understand ' . join(', ', @missing);
1225 }
1226 } elsif(ref($value)) {
1227 0 $reason = 'must be a scalar';
1228 ▶ } elsif(($type eq 'count') && ($value !~ /^\d+$/)) {
Condition66%2/3
$type eq "count" and not $value =~ /^\d+$/u
!ll&&!rl&&r
11170
MC/DC0%0/2
$type eq "count" and not $value =~ /^\d+$/u
$type eq "count" not $value =~ /^\d+$/u
Truth table66%2/3
A and not(B)
A= $type eq "count"B= not $value =~ /^\d+$/u
ABresult
0X0
100
111
1229 0 $reason = 'must be a number, 0 or more';
1230 }
1231 32 return $reason;
1232 }
1233  
1234 27 ▶sub import {
Subroutine import: called CC=2 SCAR=6.9
1235 # The class name, "CGI::Buffer"
1236 27 shift;
1237  
1238 # use CGI::Buffer { optimise_content => 1 } gives the options to init()
1239 27 ▶ init(@_) if(@_);
Branch: 1 branch
BranchTrueFalseTotal
if @_ 4 23 27
1240 }
1241  
1242 =head2 set_options
1243  
1244 Synonym for init, kept for historical reasons.
1245  
1246 =head3 Purpose, Arguments, Returns and Side Effects
1247  
1248 As for L</init>.
1249  
1250 =head3 EXAMPLE
1251  
1252 CGI::Buffer::set_options(optimise_content => 1);
1253  
1254 =head3 API SPECIFICATION
1255  
1256 =head4 INPUT
1257  
1258 As for L</init>.
1259  
1260 =head4 OUTPUT
1261  
1262 { type => 'string', value => 'CGI::Buffer' }
1263  
1264 =head3 MESSAGES
1265  
1266 As for L</init>.
1267  
1268 =head3 FORMAL SPECIFICATION
1269  
1270 SetOptions ≙ Init
1271  
1272 =cut
1273  
1274 14 ▶sub set_options {
Subroutine set_options: called CC=1 SCAR=0.0
Pod documented
1275 14 return init(@_);
1276 }
1277  
1278 =head2 can_cache
1279  
1280 Returns true if the server is allowed to store the results locally.
1281  
1282 =head3 Purpose
1283  
1284 Says whether this request may use the server-side cache.
1285 The cache isn't used if the NO_CACHE or NO_STORE environment variables are set,
1286 if the request method isn't GET or HEAD,
1287 if the client has logged in (the Authorization header or REMOTE_USER is set),
1288 or if the client's Cache-Control header includes any of no-store, no-cache,
1289 private or max-age=0.
1290  
1291 =head3 Arguments
1292  
1293 None.
1294  
1295 =head3 Returns
1296  
1297 1 if the cache may be used, otherwise 0.
1298  
1299 =head3 Side Effects
1300  
1301 The answer is decided on the first call, and doesn't change for the rest of the
1302 request.
1303  
1304 =head3 EXAMPLE
1305  
1306 if(CGI::Buffer::can_cache()) {
1307 CGI::Buffer::init(cache => CHI->new(driver => 'File'));
1308 }
1309  
1310 =head3 API SPECIFICATION
1311  
1312 =head4 INPUT
1313  
1314 None.
1315  
1316 =head4 OUTPUT
1317  
1318 { type => 'boolean' }
1319  
1320 =head3 MESSAGES
1321  
1322 None.
1323  
1324 =head3 FORMAL SPECIFICATION
1325  
1326 ┌─ CanCache ──────────────────────────────────────────┐
1327 │ ΞEnvironment │
1328 │ result! : 𝔹 │
1329 ├─────────────────────────────────────────────────────┤
1330 │ result! = true ⇔ │
1331 │ {NO_CACHE, NO_STORE, HTTP_AUTHORIZATION, │
1332 │ REMOTE_USER} ∩ dom env = ∅ ∧ │
1333 │ (REQUEST_METHOD ∉ dom env ∨ │
1334 │ env(REQUEST_METHOD) ∈ {GET, HEAD}) ∧ │
1335 │ directives(env(HTTP_CACHE_CONTROL)) ∩ │
1336 │ {no-store, no-cache, private, max-age=0} = ∅ │
1337 └─────────────────────────────────────────────────────┘
1338  
1339 =cut
1340  
1341 6 ▶sub can_cache {
Subroutine can_cache: called CC=10 SCAR=30.1
Pod documented
1342 6 ▶ unless(defined($cacheable)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $CGI::Buffer::cacheable) 4 2 6
1343 4 ▶ _log('debug', "cache_control = $ENV{HTTP_CACHE_CONTROL}") if(defined($ENV{'HTTP_CACHE_CONTROL'}));
Branch: 1 branch
BranchTrueFalseTotal
if defined $ENV{"HTTP_CACHE_CONTROL"} 0 4 4
1344  
1345 # A request may give several directives, e.g. "no-cache, max-age=0",
1346 # and any one of them forbids the cache
1347 4 my $max_age = _client_max_age();
1348 my $forbidden = defined($ENV{'NO_CACHE'}) || defined($ENV{'NO_STORE'}) ||
1349 (!_is_safe_method()) || _is_logged_in() ||
1350 0 ▶ (grep { $NO_CACHE_DIRECTIVES{$_} } keys %{_cache_control()}) ||
Condition33%6/18
defined $ENV{'NO_CACHE'} || defined $ENV{'NO_STORE'} || !_is_safe_method() || _is_logged_in() || grep({$NO_CACHE_DIRECTIVES{$_};} keys %{_cache_control();}) || defined $max_age && $max_age == 0
l!l&&r!l&&!r
004
defined $ENV{"NO_CACHE"} or defined $ENV{"NO_STORE"} or not _is_safe_method() or _is_logged_in() or grep {$NO_CACHE_DIRECTIVES{$_};} keys %{_cache_control();}
l!l&&r!l&&!r
004
defined $ENV{"NO_CACHE"} or defined $ENV{"NO_STORE"} or not _is_safe_method() or _is_logged_in()
l!l&&r!l&&!r
004
defined $ENV{"NO_CACHE"} or defined $ENV{"NO_STORE"} or not _is_safe_method()
l!l&&r!l&&!r
004
defined $ENV{"NO_CACHE"} or defined $ENV{"NO_STORE"}
l!l&&r!l&&!r
004
defined $max_age and $max_age == 0
!ll&&!rl&&r
400
MC/DC0%0/7
defined $ENV{'NO_CACHE'} || defined $ENV{'NO_STORE'} || !_is_safe_method() || _is_logged_in() || grep({$NO_CACHE_DIRECTIVES{$_};} keys %{_cache_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 %{_cache_control();} defined $max_age $max_age == 0
Truth table12%1/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 %{_cache_control();}F= defined $max_ageG= $max_age == 0
ABCDEFGresult
1XXXXXX1
01XXXXX1
001XXXX1
0001XXX1
00001XX1
00000111
000000X0
00000100
1351 (defined($max_age) && ($max_age == 0));
1352 4 ▶ $cacheable = $forbidden ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$forbidden ? : 0 4 4
1353 }
1354 6 return $cacheable;
1355 }
1356  
1357 =head2 is_cached
1358  
1359 Returns true if the output is cached. If it is then it means that all of the
1360 expensive routines in the CGI script can be by-passed because we already have
1361 the result stored in the cache.
1362  
1363 =head3 Purpose
1364  
1365 Says whether the page is in the server-side cache, in which case the script can
1366 exit without printing anything, and the cached copy is sent.
1367  
1368 =head3 Arguments
1369  
1370 None. Any that are given, e.g. the class name when chained after init(), are
1371 ignored.
1372  
1373 =head3 Returns
1374  
1375 1 if the page is in the cache, otherwise 0.
1376  
1377 An entry that has expired isn't cached,
1378 and neither is any entry if the script's file has changed since,
1379 or if the age of the script can't be determined.
1380 If the cache fails, a warning is given and the output isn't cached.
1381  
1382 =head3 Side Effects
1383  
1384 Remembers the cache entry for when the output is sent.
1385 An entry made before the script was last changed is removed from the cache.
1386  
1387 =head3 EXAMPLE
1388  
1389 # Put this toward the top of your program before you do anything
1390  
1391 # Example key generation - use whatever you want as something
1392 # unique for this call, so that subsequent calls with the same
1393 # values match something in the cache
1394 use CGI::Info;
1395 use CGI::Lingua;
1396 use CGI::Buffer;
1397  
1398 my $i = CGI::Info->new();
1399 my $l = CGI::Lingua->new(supported => ['en']);
1400  
1401 # To use server side caching you must give the cache argument, however
1402 # the cache_key argument is optional - if you don't give one then one will
1403 # be generated for you
1404 if(CGI::Buffer::can_cache()) {
1405 CGI::Buffer::init(
1406 cache => CHI->new(driver => 'File'),
1407 cache_key => $i->domain_name() . '/' . $i->script_name() . '/' . $i->as_string() . '/' . $l->language()
1408 );
1409 if(CGI::Buffer::is_cached()) {
1410 # Output will be retrieved from the cache and sent automatically
1411 exit;
1412 }
1413 }
1414 # Not in the cache, so now do our expensive computing to generate the
1415 # results
1416 print "Content-type: text/html\n";
1417 # ...
1418  
1419 =head3 API SPECIFICATION
1420  
1421 =head4 INPUT
1422  
1423 None.
1424  
1425 =head4 OUTPUT
1426  
1427 { type => 'boolean' }
1428  
1429 =head3 MESSAGES
1430  
1431 Key Meaning Resolution
1432 -------------- ---------------------------------------- ---------------------------------
1433 failed The cache couldn't be read Check the cache's configuration
1434 no_script_path CGI::Info can't find the script (fatal) Check SCRIPT_FILENAME/SCRIPT_NAME
1435 no_script_age The script's file can't be read (logged) Check the script's permissions
1436  
1437 =head3 FORMAL SPECIFICATION
1438  
1439 ┌─ IsCached ──────────────────────────────────────────┐
1440 │ ΞCache │
1441 │ key : KEY │
1442 │ script_mtime : TIME │
1443 │ now : TIME │
1444 │ result! : 𝔹 │
1445 ├─────────────────────────────────────────────────────┤
1446 │ result! = true ⇔ │
1447 │ key ∈ dom cache ∧ │
1448 │ cache(key).value ≠ ⊥ ∧ │
1449 │ cache(key).expires_at > now ∧ │
1450 │ script_mtime ≤ cache(key).created_at │
1451 └─────────────────────────────────────────────────────┘
1452  
1453 =head3 PSEUDOCODE
1454  
1455 if there's no cache, the page isn't cached
1456 look up the key, ignoring expired entries and a failing cache
1457 if there's no entry, or it has no data, the page isn't cached
1458 if the script's age can't be found, the page isn't cached
1459 if the script has changed since the entry was made
1460 remove the entry, the page isn't cached
1461 otherwise the page is cached
1462  
1463 =cut
1464  
1465 14 ▶sub is_cached {
Subroutine is_cached: called CC=6 SCAR=19.3
Pod documented
1466 14 my $found = 0;
1467  
1468 14 ▶ if(!$cache) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $CGI::Buffer::cache) { } 10 4 14
1469 10 _log('debug', "is_cached: cache hasn't been enabled");
1470 } else {
1471 4 my $key = _generate_key();
1472 4 _log('debug', "is_cached: looking for key = $key");
1473  
1474 4 $cobject = _cache_lookup($key);
1475 4 ▶ if((!$cobject) || !defined($cobject->value())) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $CGI::Buffer::cobject && defined $CGI::Buffer::cobject->value) { } 2 2 4
Condition66%2/3
$CGI::Buffer::cobject && defined $CGI::Buffer::cobject->value
!ll&&!rl&&r
202
MC/DC50%1/2
$CGI::Buffer::cobject && defined $CGI::Buffer::cobject->value
$CGI::Buffer::cobject defined $CGI::Buffer::cobject->value
Truth table66%2/3
A && B
A= $CGI::Buffer::cobjectB= defined $CGI::Buffer::cobject->value
ABresult
0X0
100
111
1476 2 _log('debug', 'not found in cache');
1477 2 $cobject = undef;
1478 } else {
1479 # If the script has changed, don't use the cache since we
1480 # may produce different output
1481 2 my $age = _my_age();
1482 2 ▶ if(!defined($age)) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $age) { } 0 2 2
elsif ($age > $CGI::Buffer::cobject->created_at) { } 0 2 2
1483 # Can't determine the age. Play it safe and assume
1484 # we're not cached
1485 0 _log('debug', "Can't determine script's age");
1486 0 $cobject = undef;
1487 } elsif($age > $cobject->created_at()) {
1488 # Remove only this entry. Clearing the whole cache
1489 # would also lose other scripts' pages (RT104471)
1490 0 _log('debug', 'Script has been updated');
1491 0 ▶ _try('removing an old entry', sub { $cache->remove($key) });
Subroutine __ANON__: not called CC=1 SCAR=6.9
1492 0 $cobject = undef;
1493 } else {
1494 2 _log('debug', 'Script is in the cache');
1495 2 $found = 1;
1496 }
1497 }
1498 }
1499 14 return $found;
1500 }
1501  
1502 # Purpose: find when the script was last changed
1503 # Entry criteria: none
1504 # Exit status: the script's modification time, or undef if it can't be read
1505 # Side effects: remembers the answer, may create $info. Croaks if CGI::Info
1506 # can't find the script
1507 21 ▶sub _my_age {
Subroutine _my_age: called CC=4 SCAR=14.3
1508 21 ▶ unless(defined($script_mtime)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $CGI::Buffer::script_mtime) 17 4 21
1509 17 my $path = _info()->script_path();
1510 17 ▶ croak(_i18n('no_script_path')) unless(defined($path));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 0 17 17
1511  
1512 17 ▶ if(my @statb = stat($path)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@statb) = stat $path) { } 17 0 17
1513 17 $script_mtime = $statb[9];
1514 } else {
1515 0 _log('debug', _i18n('no_script_age', { path => $path, error => "$!" }));
1516 }
1517 }
1518 21 return $script_mtime;
1519 }
1520  
1521 # Purpose: choose the content encoding to use
1522 # Entry criteria: @content_type and $script_encoded are set from the headers
1523 # Exit status: the encoding, or '' for none
1524 # Side effects: may load a compression module
1525 #
1526 # Premise 1: _compress() fails the request with a 406 if it can't load the
1527 # module for the encoding
1528 # Premise 2: the client is happy with any of the encodings it lists
1529 # Conclusion: choose the first listed encoding that can be loaded, then the 406
1530 # can't happen
1531 23 ▶sub _choose_encoding {
Subroutine _choose_encoding: called CC=12 SCAR=27.4
1532 23 ▶ my $accept = $ENV{'HTTP_ACCEPT_ENCODING'} || $ENV{'HTTP_TE'};
Condition100%3/3
$ENV{'HTTP_ACCEPT_ENCODING'} || $ENV{'HTTP_TE'}
l!l&&r!l&&!r
1121
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
1533 23 my $chosen = '';
1534  
1535 # Only text is compressed, and not if the script already has (twice is
1536 # pointless)
1537 23 ▶ if($compress_content && $accept && !$script_encoded &&
Branch: 1 branch
BranchTrueFalseTotal
if ($CGI::Buffer::compress_content and $accept and not $CGI::Buffer::script_encoded and not defined $CGI::Buffer::content_type[0] && lc $CGI::Buffer::content_type[0] ne "text") 2 21 23
Condition58%7/12
$CGI::Buffer::compress_content and $accept and not $CGI::Buffer::script_encoded and not defined $CGI::Buffer::content_type[0] && lc $CGI::Buffer::content_type[0] ne "text"
!ll&&!rl&&r
2102
$CGI::Buffer::compress_content and $accept and not $CGI::Buffer::script_encoded
!ll&&!rl&&r
2102
$CGI::Buffer::compress_content and $accept
!ll&&!rl&&r
0212
defined $CGI::Buffer::content_type[0] && lc $CGI::Buffer::content_type[0] ne 'text'
!ll&&!rl&&r
020
MC/DC20%1/5
$CGI::Buffer::compress_content and $accept and not $CGI::Buffer::script_encoded and not defined $CGI::Buffer::content_type[0] && lc $CGI::Buffer::content_type[0] ne "text"
$CGI::Buffer::compress_content $accept not $CGI::Buffer::script_encoded defined $CGI::Buffer::content_type[0] lc $CGI::Buffer::content_type[0] ne 'text'
Truth table33%2/6
A and B and not(C) and not(D && E)
A= $CGI::Buffer::compress_contentB= $acceptC= not $CGI::Buffer::script_encodedD= defined $CGI::Buffer::content_type[0]E= lc $CGI::Buffer::content_type[0] ne 'text'
ABCDEresult
0XXXX0
10XXX0
110XX0
111110
1110X1
111101
1538 !(defined($content_type[0]) && (lc($content_type[0]) ne 'text'))) {
1539 2 foreach my $method(split(/\s*,\s*/, lc($accept))) {
1540 # e.g. "gzip;q=0.8", where q=0 means "not acceptable"
1541 2 my ($name, @params) = split(/\s*;\s*/, $method);
1542 2 ▶ next unless(defined($name) && $ENCODING_MODULE{$name});
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and $ENCODING_MODULE{$name} 0 2 2
Condition33%1/3
defined $name and $ENCODING_MODULE{$name}
!ll&&!rl&&r
002
MC/DC0%0/2
defined $name and $ENCODING_MODULE{$name}
defined $name $ENCODING_MODULE{$name}
Truth table33%1/3
A and B
A= defined $nameB= $ENCODING_MODULE{$name}
ABresult
0X0
100
111
1543 0 ▶ next if(grep { /^q=0(?:\.0*)?$/ } @params);
Branch: 1 branch
BranchTrueFalseTotal
if grep {/^q=0(?:\.0*)?$/u;} @params 0 2 2
1544 2 ▶ if(_can_load($ENCODING_MODULE{$name})) {
Branch: 1 branch
BranchTrueFalseTotal
if (_can_load($ENCODING_MODULE{$name})) 2 0 2
1545 2 $chosen = $name;
1546 2 last;
1547 }
1548 }
1549 }
1550 23 return $chosen;
1551 }
1552  
1553 # Purpose: say whether a module can be loaded
1554 # Entry criteria: $module is a module name, from a fixed list
1555 # Exit status: true if it can be
1556 # Side effects: loads the module, and remembers the answer
1557 {
1558 28 my %loadable;
1559  
1560 sub _can_load
1561 4 ▶ {
Subroutine _can_load: called CC=3 SCAR=11.1
1562 4 my $module = shift;
1563  
1564 4 ▶ $loadable{$module} = (eval "require $module; 1") ? 1 : 0 unless(exists($loadable{$module}));
Branch: 2 branches
BranchTrueFalseTotal
unless exists $loadable{$module} 2 2 4
eval "require $module; 1" ? : 2 0 2
1565 4 return $loadable{$module};
1566 }
1567 }
1568  
1569 # Purpose: find the content type and content encoding in a block of headers
1570 # Entry criteria: $headers is the block of headers
1571 # Exit status: none
1572 # Side effects: sets @content_type, and $script_encoded if there's an encoding
1573 sub _set_content_type
1574 28 ▶{
Subroutine _set_content_type: called CC=7 SCAR=20.5
1575 22 my $headers = shift;
1576  
1577 22 foreach my $header (split(/\r?\n/, $headers)) {
1578 23 my ($header_name, $header_value) = split /\:\s*/, $header, 2;
1579 23 ▶ next unless(defined($header_name) && defined($header_value));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $header_name and defined $header_value 1 22 23
Condition66%2/3
defined $header_name and defined $header_value
!ll&&!rl&&r
0122
MC/DC50%1/2
defined $header_name and defined $header_value
defined $header_name defined $header_value
Truth table66%2/3
A and B
A= defined $header_nameB= defined $header_value
ABresult
0X0
100
111
1580 22 ▶ if(lc($header_name) eq 'content-type') {
Branch: 2 branches
BranchTrueFalseTotal
if (lc $header_name eq 'content-type') { } 20 2 22
elsif (lc $header_name eq 'content-encoding' and not lc($header_value) =~ /^\s*identity\s*$/u) { } 0 4 4
1581 20 @content_type = split /\//, $header_value, 2;
1582 ▶ } elsif((lc($header_name) eq 'content-encoding') && (lc($header_value) !~ /^\s*identity\s*$/)) {
Condition33%1/3
lc $header_name eq "content-encoding" and not lc($header_value) =~ /^\s*identity\s*$/u
!ll&&!rl&&r
200
MC/DC0%0/2
lc $header_name eq "content-encoding" and not lc($header_value) =~ /^\s*identity\s*$/u
lc $header_name eq "content-encoding" not lc($header_value) =~ /^\s*identity\s*$/u
Truth table33%1/3
A and not(B)
A= lc $header_name eq "content-encoding"B= not lc($header_value) =~ /^\s*identity\s*$/u
ABresult
0X0
100
111
1583 0 $script_encoded = 1;
1584 }
1585 }
1586 }
1587  
1588 # Purpose: compress the body
1589 # Entry criteria: $encoding is from _choose_encoding(), or '' for none
1590 # Exit status: none
1591 # Side effects: may change $body, $content_encoding and @o. Sets a 406 status
1592 # if the encoding can't be produced
1593 18 ▶sub _compress {
Subroutine _compress: called CC=14 SCAR=28.9
1594 18 my $encoding = shift;
1595  
1596 # This can be called again, by which time the body is no longer compressed
1597 18 $content_encoding = undef;
1598 18 @o = grep { !/^Content-Encoding:/ } @o;
1599  
1600 18 ▶ return unless(defined($body) && defined($encoding) && length($encoding));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $CGI::Buffer::body and defined $encoding and length $encoding 16 2 18
Condition50%3/6
defined $CGI::Buffer::body and defined $encoding and length $encoding
!ll&&!rl&&r
0162
defined $CGI::Buffer::body and defined $encoding
!ll&&!rl&&r
0018
MC/DC33%1/3
defined $CGI::Buffer::body and defined $encoding and length $encoding
defined $CGI::Buffer::body defined $encoding length $encoding
Truth table50%2/4
A and B and C
A= defined $CGI::Buffer::bodyB= defined $encodingC= length $encoding
ABCresult
0XX0
10X0
1100
1111
1601 2 ▶ return if(length($body) < $MIN_GZIP_LEN);
Branch: 1 branch
BranchTrueFalseTotal
if length $CGI::Buffer::body < $MIN_GZIP_LEN 0 2 2
1602  
1603 # Premise: _choose_encoding() only returns encodings whose module loads
1604 # Conclusion: if one can't be loaded here, the request can't be met
1605 2 my $module = $ENCODING_MODULE{$encoding};
1606 2 ▶ if((!defined($module)) || !_can_load($module)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $module and _can_load($module)) 0 2 2
Condition33%1/3
defined $module and _can_load($module)
!ll&&!rl&&r
002
MC/DC0%0/2
defined $module and _can_load($module)
defined $module _can_load($module)
Truth table33%1/3
A and B
A= defined $moduleB= _can_load($module)
ABresult
0X0
100
111
1607 0 _set_status($HTTP_NOT_ACCEPTABLE);
1608 0 return;
1609 }
1610  
1611 # Avoid 'Wide character in memGzip'
1612 2 my $bytes = _to_bytes($body);
1613 2 my $compressed;
1614 2 ▶ if($module eq 'Compress::Zlib') {
Branch: 2 branches
BranchTrueFalseTotal
if ($module eq 'Compress::Zlib') { } 1 1 2
elsif ($module eq 'Compress::Zstd') { } 0 1 1
1615 1 $compressed = Compress::Zlib::memGzip(\$bytes);
1616 } elsif($module eq 'Compress::Zstd') {
1617 # Facebook
1618 0 $compressed = Compress::Zstd::compress(\$bytes);
1619 } else {
1620 1 $compressed = IO::Compress::Brotli::bro($bytes);
1621 }
1622  
1623 # Don't send it compressed if that makes it larger
1624 2 ▶ return unless(defined($compressed) && (length($compressed) < length($bytes)));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $compressed and length $compressed < length $bytes 1 1 2
Condition66%2/3
defined $compressed and length $compressed < length $bytes
!ll&&!rl&&r
011
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
1625  
1626 1 $body = $compressed;
1627 1 ▶ $encoding = 'gzip' if($encoding eq 'x-gzip');
Branch: 1 branch
BranchTrueFalseTotal
if $encoding eq "x-gzip" 0 1 1
1628 1 $content_encoding = $encoding;
1629 1 foreach my $header("Content-Encoding: $encoding", 'Vary: Accept-Encoding') {
1630 2 ▶ push @o, $header unless(grep { $_ eq $header } @o);
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $header;} @CGI::Buffer::o 2 0 2
1631 }
1632 }
1633  
1634 # Purpose: work out the ETag of the body
1635 # Entry criteria: $body is the uncompressed body, or undef
1636 # Exit status: none
1637 # Side effects: sets $etag, unless it's already set
1638 6 ▶sub _generate_etag {
Subroutine _generate_etag: called CC=3 SCAR=12.5
1639 6 ▶ if((!defined($etag)) && defined($body)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $CGI::Buffer::etag and defined $CGI::Buffer::body) 6 0 6
Condition33%1/3
not defined $CGI::Buffer::etag and defined $CGI::Buffer::body
!ll&&!rl&&r
006
MC/DC0%0/2
not defined $CGI::Buffer::etag and defined $CGI::Buffer::body
not defined $CGI::Buffer::etag defined $CGI::Buffer::body
Truth table33%1/3
not(A) and B
A= not defined $CGI::Buffer::etagB= defined $CGI::Buffer::body
ABresult
0X0
100
111
1640 # bytes to avoid "Wide character in subroutine entry"
1641 6 $etag = '"' . Digest::MD5::md5_hex(_to_bytes($body)) . '"';
1642 6 _log('debug', "Etag = $etag");
1643 }
1644 }
1645  
1646 # Purpose: run some code which isn't essential to sending the page, e.g.
1647 # something using the cache
1648 # Entry criteria: $what describes the code, for the warning
1649 # Exit status: what the code returns, or undef if it fails
1650 # Side effects: those of the code, and a warning if it fails
1651 6 ▶sub _try {
Subroutine _try: called CC=2 SCAR=7.5
1652 6 my ($what, $code) = @_;
1653  
1654 6 my $rc;
1655 6 ▶ unless(eval { $rc = $code->(); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { $rc = &$code(); 1 } }) 0 6 6
1656 0 _problem('failed', { what => $what, error => $@ });
1657 0 $rc = undef;
1658 }
1659 6 return $rc;
1660 }
1661  
1662 # Purpose: report something which has gone wrong. This can be called from
1663 # anywhere, so the logger itself may be the thing that's failing
1664 # Entry criteria: $key and $args are a message, see _i18n()
1665 # Exit status: none
1666 # Side effects: writes to the logger, or gives a warning
1667 4 ▶sub _problem {
Subroutine _problem: called CC=3 SCAR=14.2
1668 4 my $message = _i18n(@_);
1669  
1670 # Carp::shortmess says where the caller of CGI::Buffer is. Must be
1671 # Carp::carp instead of carp for Test::Carp
1672 0 ▶ unless($logger && eval { $logger->warn(Carp::shortmess($message)); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($CGI::Buffer::logger and eval { do { $CGI::Buffer::logger->warn(Carp::shortmess($message)); 1 } }) 4 0 4
Condition33%1/3
$CGI::Buffer::logger and eval { do { $CGI::Buffer::logger->warn(Carp::shortmess($message)); 1 } }
!ll&&!rl&&r
400
MC/DC0%0/2
$CGI::Buffer::logger and eval { do { $CGI::Buffer::logger->warn(Carp::shortmess($message)); 1 } }
$CGI::Buffer::logger eval { do { $CGI::Buffer::logger->warn(Carp::shortmess($message)); 1 } }
Truth table33%1/3
A and B
A= $CGI::Buffer::loggerB= eval { do { $CGI::Buffer::logger->warn(Carp::shortmess($message)); 1 } }
ABresult
0X0
100
111
1673 4 Carp::carp($message);
1674 }
1675 }
1676  
1677 # Purpose: write to the logger, if there is one
1678 # Entry criteria: $level is one of @LOGGER_METHODS, @message is the message
1679 # Exit status: none
1680 # Side effects: writes to the logger
1681 120 ▶sub _log {
Subroutine _log: called CC=2 SCAR=6.9
1682 120 my ($level, @message) = @_;
1683  
1684 120 ▶ $logger->$level(@message) if($logger);
Branch: 1 branch
BranchTrueFalseTotal
if $CGI::Buffer::logger 9 111 120
1685 }
1686  
1687 # Purpose: find the text of a message
1688 # Entry criteria: $key is a key of %DEFAULT_MESSAGES, $args a hashref of the
1689 # values for its placeholders. A count argument chooses the plural form
1690 # Exit status: the text, starting with the package name
1691 # Side effects: none
1692 4 ▶sub _i18n {
Subroutine _i18n: called CC=10 SCAR=25.3
1693 4 my ($key, $args) = @_;
1694  
1695 4 ▶ $args ||= {};
Condition50%1/2
$args ||= {}
l!l
40
MC/DC0%0/1
$args ||= {}
$args
Truth table50%1/2
A
A= $args
Aresult
11
00
1696 4 ▶ my $format = exists($messages{$key}) ? $messages{$key} : $DEFAULT_MESSAGES{$key};
Branch: 1 branch
BranchTrueFalseTotal
exists $CGI::Buffer::messages{$key} ? : 0 4 4
1697  
1698 # An unknown key is shown as itself rather than being lost
1699 4 ▶ $format = $key unless(defined($format));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $format 0 4 4
1700 4 ▶ if(ref($format) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $format eq "HASH") 1 3 4
1701 # Plural forms: "one" for a count of 1, "other" for the rest
1702 1 ▶ my $form = (defined($args->{count}) && ($args->{count} == 1) && defined($format->{one})) ? 'one' : 'other';
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{'count'} && $args->{'count'} == 1 && defined $format->{'one'} ? : 0 1 1
Condition33%2/6
defined $args->{"count"} and $args->{"count"} == 1 and defined $format->{"one"}
!ll&&!rl&&r
100
defined $args->{"count"} and $args->{"count"} == 1
!ll&&!rl&&r
010
MC/DC0%0/3
defined $args->{"count"} and $args->{"count"} == 1 and defined $format->{"one"}
defined $args->{"count"} $args->{"count"} == 1 defined $format->{"one"}
Truth table25%1/4
A and B and C
A= defined $args->{"count"}B= $args->{"count"} == 1C= defined $format->{"one"}
ABCresult
0XX0
10X0
1100
1111
1703 1 $format = $format->{$form};
1704 1 ▶ $format = $key unless(defined($format));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $format 0 1 1
1705 }
1706  
1707 # A missing value is shown as empty, rather than as a warning
1708 28 ▶ no warnings 'numeric';
Subroutine BEGIN: called CC=1 SCAR=0.0
1709 4 ▶ $format =~ s/%\{(\w+)\}($SPRINTF_CONVERSION)/sprintf("%$2", defined($args->{$1}) ? $args->{$1} : '')/ge;
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{$1} ? : 7 0 7
1710 4 return __PACKAGE__ . ": $format";
1711 }
1712  
1713 # Purpose: check that the logger can do what will be asked of it, otherwise
1714 # forget it. AUTOLOAD is taken on trust
1715 # Entry criteria: $logger is set
1716 # Exit status: none
1717 # Side effects: may set $logger to undef, and give a warning
1718 1 ▶sub _check_logger {
Subroutine _check_logger: called CC=4 SCAR=18.7
1719 my ($missing) = grep {
1720 1 ▶ !(Scalar::Util::blessed($logger) && ($logger->can($_) || $logger->can('AUTOLOAD')))
Condition33%2/6
builtin::blessed($CGI::Buffer::logger) && ($CGI::Buffer::logger->can($_) || $CGI::Buffer::logger->can('AUTOLOAD'))
!ll&&!rl&&r
005
$CGI::Buffer::logger->can($_) or $CGI::Buffer::logger->can("AUTOLOAD")
l!l&&r!l&&!r
500
MC/DC0%0/3
builtin::blessed($CGI::Buffer::logger) && ($CGI::Buffer::logger->can($_) || $CGI::Buffer::logger->can('AUTOLOAD'))
builtin::blessed($CGI::Buffer::logger) $CGI::Buffer::logger->can($_) $CGI::Buffer::logger->can("AUTOLOAD")
Truth table25%1/4
A && B or C
A= builtin::blessed($CGI::Buffer::logger)B= $CGI::Buffer::logger->can($_)C= $CGI::Buffer::logger->can("AUTOLOAD")
ABCresult
0XX0
1000
11X1
1011
1721 } @LOGGER_METHODS;
1722  
1723 1 ▶ if(defined($missing)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $missing) 0 1 1
1724 0 $logger = undef;
1725 0 _problem('logger_method', { method => $missing });
1726 }
1727 }
1728  
1729 # Purpose: look for an entry in the cache that can still be used. A failing
1730 # cache is the same as an empty one. CHI's get_object() returns an object
1731 # even if it has expired
1732 # Entry criteria: $key is the cache key, $cache is set
1733 # Exit status: the cache object, or undef
1734 # Side effects: none
1735 5 ▶sub _cache_lookup {
Subroutine _cache_lookup: called CC=4 SCAR=15.2
1736 5 my $key = shift;
1737  
1738 5 ▶ my $object = _try('reading the cache', sub { return $cache->get_object($key) });
Subroutine __ANON__: called CC=1 SCAR=0.0
1739 5 ▶ if($object && $object->can('is_expired') && $object->is_expired()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($object and $object->can("is_expired") and $object->is_expired) 0 5 5
Condition66%4/6
$object and $object->can("is_expired") and $object->is_expired
!ll&&!rl&&r
230
$object and $object->can("is_expired")
!ll&&!rl&&r
203
MC/DC0%0/3
$object and $object->can("is_expired") and $object->is_expired
$object $object->can("is_expired") $object->is_expired
Truth table50%2/4
A and B and C
A= $objectB= $object->can("is_expired")C= $object->is_expired
ABCresult
0XX0
10X0
1100
1111
1740 0 _log('debug', "$key has expired");
1741 0 $object = undef;
1742 }
1743 5 return $object;
1744 }
1745  
1746 # Purpose: a string as bytes: a string of characters is encoded, bytes are left
1747 # alone
1748 # Entry criteria: $string is a string, or undef
1749 # Exit status: the bytes, or undef
1750 # Side effects: none
1751 52 ▶sub _to_bytes {
Subroutine _to_bytes: called CC=3 SCAR=11.4
1752 52 my $string = shift;
1753  
1754 52 ▶ utf8::encode($string) if(defined($string) && utf8::is_utf8($string));
Branch: 1 branch
BranchTrueFalseTotal
if defined $string and utf8::is_utf8($string) 0 52 52
Condition66%2/3
defined $string and utf8::is_utf8($string)
!ll&&!rl&&r
2500
MC/DC0%0/2
defined $string and utf8::is_utf8($string)
defined $string utf8::is_utf8($string)
Truth table66%2/3
A and B
A= defined $stringB= utf8::is_utf8($string)
ABresult
0X0
100
111
1755 52 return $string;
1756 }
1757  
1758 # Purpose: say whether the output is an HTML page
1759 # Entry criteria: @content_type is set from the headers
1760 # Exit status: 1 if it is, otherwise 0
1761 # Side effects: none
1762 23 ▶sub _is_html {
Subroutine _is_html: called CC=5 SCAR=16.8
1763 23 ▶ return (defined($content_type[0]) && defined($content_type[1]) &&
Branch: 1 branch
BranchTrueFalseTotal
defined $CGI::Buffer::content_type[0] && defined $CGI::Buffer::content_type[1] && lc $CGI::Buffer::content_type[0] eq 'text' && lc($CGI::Buffer::content_type[1]) =~ /^html/u ? : 21 2 23
Condition66%6/9
defined $CGI::Buffer::content_type[0] and defined $CGI::Buffer::content_type[1] and lc $CGI::Buffer::content_type[0] eq "text" and lc($CGI::Buffer::content_type[1]) =~ /^html/u
!ll&&!rl&&r
2021
defined $CGI::Buffer::content_type[0] and defined $CGI::Buffer::content_type[1] and lc $CGI::Buffer::content_type[0] eq "text"
!ll&&!rl&&r
2021
defined $CGI::Buffer::content_type[0] and defined $CGI::Buffer::content_type[1]
!ll&&!rl&&r
2021
MC/DC25%1/4
defined $CGI::Buffer::content_type[0] and defined $CGI::Buffer::content_type[1] and lc $CGI::Buffer::content_type[0] eq "text" and lc($CGI::Buffer::content_type[1]) =~ /^html/u
defined $CGI::Buffer::content_type[0] defined $CGI::Buffer::content_type[1] lc $CGI::Buffer::content_type[0] eq "text" lc($CGI::Buffer::content_type[1]) =~ /^html/u
Truth table40%2/5
A and B and C and D
A= defined $CGI::Buffer::content_type[0]B= defined $CGI::Buffer::content_type[1]C= lc $CGI::Buffer::content_type[0] eq "text"D= lc($CGI::Buffer::content_type[1]) =~ /^html/u
ABCDresult
0XXX0
10XX0
110X0
11100
11111
1764 (lc($content_type[0]) eq 'text') && (lc($content_type[1]) =~ /^html/)) ? 1 : 0;
1765 }
1766  
1767 # Purpose: stop the regular expressions from changing the contents of <pre>
1768 # and <textarea> by swapping them for a marker. The end of a tag is only
1769 # looked for once if it isn't there, so that hostile input can't make this
1770 # quadratic
1771 # Entry criteria: $body is HTML
1772 # Exit status: a hashref of what's needed to put them back
1773 # Side effects: changes $body
1774 16 ▶sub _protect_preformatted {
Subroutine _protect_preformatted: called CC=4 SCAR=22.3
1775 16 my $marker = 'CGIBUFFERPRESERVED' . int(rand(1_000_000_000)) . 'N';
1776 16 my (@saved, %no_end);
1777 16 my $out = '';
1778 16 my $last = 0;
1779  
1780 16 ▶ while($body =~ /<(pre|textarea)\b/gi) {
Branch: 1 branch
BranchTrueFalseTotal
if ($CGI::Buffer::body =~ /<(pre|textarea)\b/giu) 0 16 16
1781 0 my $tag = lc($1);
1782 0 my $start = $-[0];
1783 0 my $after = pos($body);
1784  
1785 0 ▶ next if($no_end{$tag});
Branch: 1 branch
BranchTrueFalseTotal
if $no_end{$tag} 0 0 0
1786 0 ▶ unless($body =~ /<\/$tag\s*+>/gi) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($CGI::Buffer::body =~ m[</$tag\s*+>]giu) 0 0 0
1787 # Unterminated, so there's no point looking again
1788 0 $no_end{$tag} = 1;
1789 0 pos($body) = $after;
1790 0 next;
1791 }
1792 0 my $end = $+[0];
1793 0 push @saved, substr($body, $start, $end - $start);
1794 0 $out .= substr($body, $last, $start - $last) . $marker . $#saved . 'X';
1795 0 $last = $end;
1796 0 pos($body) = $end;
1797 }
1798 16 $body = $out . substr($body, $last);
1799 16 return { marker => $marker, saved => \@saved };
1800 }
1801  
1802 # Purpose: put back what _protect_preformatted() took out
1803 # Entry criteria: $preformatted is what _protect_preformatted() returned
1804 # Exit status: none
1805 # Side effects: changes $body
1806 16 ▶sub _restore_preformatted {
Subroutine _restore_preformatted: called CC=2 SCAR=7.0
1807 16 my $preformatted = shift;
1808  
1809 16 my $saved = $preformatted->{'saved'};
1810 16 ▶ $body =~ s/\Q$preformatted->{marker}\E(\d+)X/$saved->[$1]/g if(scalar(@{$saved}));
Branch: 1 branch
BranchTrueFalseTotal
if scalar @{$saved;} 0 16 16
1811 }
1812  
1813 # Purpose: tell caches that what's sent depends on what the client accepts.
1814 # This is also needed when the output isn't compressed, or that's what a
1815 # cache would then give to clients that can take it compressed
1816 # Entry criteria: $headers is the script's headers
1817 # Exit status: none
1818 # Side effects: may add to @o
1819 22 ▶sub _add_vary {
Subroutine _add_vary: called CC=10 SCAR=24.2
1820 22 my $headers = shift;
1821  
1822 22 ▶ return unless(defined($headers) && length($headers));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $headers and length $headers 1 21 22
Condition66%2/3
defined $headers and length $headers
!ll&&!rl&&r
0121
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
1823 21 ▶ return unless($compress_content && defined($body) && !$script_encoded);
Branch: 1 branch
BranchTrueFalseTotal
unless $CGI::Buffer::compress_content and defined $CGI::Buffer::body and not $CGI::Buffer::script_encoded 1 20 21
Condition66%4/6
$CGI::Buffer::compress_content and defined $CGI::Buffer::body and not $CGI::Buffer::script_encoded
!ll&&!rl&&r
1020
$CGI::Buffer::compress_content and defined $CGI::Buffer::body
!ll&&!rl&&r
0120
MC/DC33%1/3
$CGI::Buffer::compress_content and defined $CGI::Buffer::body and not $CGI::Buffer::script_encoded
$CGI::Buffer::compress_content defined $CGI::Buffer::body not $CGI::Buffer::script_encoded
Truth table50%2/4
A and B and not(C)
A= $CGI::Buffer::compress_contentB= defined $CGI::Buffer::bodyC= not $CGI::Buffer::script_encoded
ABCresult
0XX0
10X0
1100
1111
1824 20 ▶ return if(defined($content_type[0]) && (lc($content_type[0]) ne 'text'));
Branch: 1 branch
BranchTrueFalseTotal
if defined $CGI::Buffer::content_type[0] and lc $CGI::Buffer::content_type[0] ne "text" 0 20 20
Condition33%1/3
defined $CGI::Buffer::content_type[0] and lc $CGI::Buffer::content_type[0] ne "text"
!ll&&!rl&&r
0200
MC/DC0%0/2
defined $CGI::Buffer::content_type[0] and lc $CGI::Buffer::content_type[0] ne "text"
defined $CGI::Buffer::content_type[0] lc $CGI::Buffer::content_type[0] ne "text"
Truth table33%1/3
A and B
A= defined $CGI::Buffer::content_type[0]B= lc $CGI::Buffer::content_type[0] ne "text"
ABresult
0X0
100
111
1825 20 ▶ return if($headers =~ /^Vary:.*\baccept-encoding\b/mi);
Branch: 1 branch
BranchTrueFalseTotal
if $headers =~ /^Vary:.*\baccept-encoding\b/imu 0 20 20
1826 20 ▶ return if(grep { /^Vary:.*\baccept-encoding\b/i } @o);
Branch: 1 branch
BranchTrueFalseTotal
if grep {/^Vary:.*\baccept-encoding\b/iu;} @CGI::Buffer::o 1 19 20
1827 19 push @o, 'Vary: Accept-Encoding';
1828 }
1829  
1830 # Purpose: send one Status header, that of the status we've ended up with,
1831 # keeping the script's one if it's the same since it may have its own
1832 # wording
1833 # Entry criteria: @o holds all of the headers, $status is final
1834 # Exit status: none
1835 # Side effects: changes @o
1836 21 ▶sub _set_status_header {
Subroutine _set_status_header: called CC=5 SCAR=16.5
1837 21 my $found = 0;
1838 @o = grep {
1839 21 my $keep = 1;
1840 132 ▶ if(/^Status:\s*(\d+)/i) {
Branch: 1 branch
BranchTrueFalseTotal
if (/^Status:\s*(\d+)/iu) 4 128 132
1841 4 ▶ $keep = (!$found) && ($1 == $status);
Condition33%1/3
!$found && $1 == $CGI::Buffer::status
!ll&&!rl&&r
004
MC/DC0%0/2
!$found && $1 == $CGI::Buffer::status
!$found $1 == $CGI::Buffer::status
Truth table33%1/3
not(A) && B
A= !$foundB= $1 == $CGI::Buffer::status
ABresult
0X0
100
111
1842 4 ▶ $found ||= $keep;
Condition33%1/3
$found ||= $keep
l!l&&r!l&&!r
040
MC/DC0%0/2
$found ||= $keep
$found $keep
Truth table33%1/3
A ||= B
A= $foundB= $keep
ABresult
1X1
011
000
1843 }
1844 $keep
1845 132 } @o;
1846  
1847 21 ▶ unless($found) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($found) 17 4 21
1848 17 push @o, _status_line($status);
1849 17 _set_status($status);
1850 }
1851 }
1852  
1853 # Purpose: the Status header for a status
1854 # Entry criteria: $code is an HTTP status
1855 # Exit status: the header, e.g. "Status: 304 Not Modified"
1856 # Side effects: loads HTTP::Status
1857 27 ▶sub _status_line {
Subroutine _status_line: called CC=1 SCAR=0.0
1858 27 my $code = shift;
1859  
1860 27 require HTTP::Status;
1861 27 return "Status: $code " . HTTP::Status::status_message($code);
1862 }
1863  
1864 # Purpose: the header that says what CGI::Buffer did
1865 # Entry criteria: $what is e.g. "Hit"
1866 # Exit status: the header
1867 # Side effects: none
1868 4 ▶sub _buffer_header {
Subroutine _buffer_header: called CC=1 SCAR=0.0
1869 4 my $what = shift;
1870  
1871 4 return "X-CGI-Buffer-$VERSION: $what";
1872 }
1873  
1874 # Purpose: say whether If-Range asks for a part, which it does only if the
1875 # client's copy is the current one (RFC 9110 14.5), which needs an exact
1876 # match of a strong validator
1877 # Entry criteria: $body is the uncompressed body
1878 # Exit status: 1 if a part may be sent, otherwise 0
1879 # Side effects: may set $etag
1880 0 ▶sub _if_range_matches {
Subroutine _if_range_matches: not called CC=10 SCAR=47.0
1881 0 my $if_range = $ENV{'HTTP_IF_RANGE'};
1882 0 my $matches = 1;
1883  
1884 0 ▶ if(defined($if_range) && length($if_range)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $if_range and length $if_range) 0 0 0
Condition0%0/3
defined $if_range and length $if_range
!ll&&!rl&&r
000
MC/DC0%0/2
defined $if_range and length $if_range
defined $if_range length $if_range
Truth table0%0/3
A and B
A= defined $if_rangeB= length $if_range
ABresult
0X0
100
111
1885 0 ▶ if($if_range =~ /^(?:W\/)?"/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($if_range =~ m[^(?:W/)?"]u) { } 0 0 0
1886 0 _generate_etag();
1887 0 ▶ $matches = (defined($etag) && ($if_range eq $etag)) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $CGI::Buffer::etag && $if_range eq $CGI::Buffer::etag ? : 0 0 0
Condition0%0/3
defined $CGI::Buffer::etag and $if_range eq $CGI::Buffer::etag
!ll&&!rl&&r
000
MC/DC0%0/2
defined $CGI::Buffer::etag and $if_range eq $CGI::Buffer::etag
defined $CGI::Buffer::etag $if_range eq $CGI::Buffer::etag
Truth table0%0/3
A and B
A= defined $CGI::Buffer::etagB= $if_range eq $CGI::Buffer::etag
ABresult
0X0
100
111
1888 } else {
1889 0 my $since = _parse_http_date($if_range);
1890 0 ▶ my $age = (defined($since) && $info) ? _my_age() : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $since && $CGI::Buffer::info ? : 0 0 0
Condition0%0/3
defined $since and $CGI::Buffer::info
!ll&&!rl&&r
000
MC/DC0%0/2
defined $since and $CGI::Buffer::info
defined $since $CGI::Buffer::info
Truth table0%0/3
A and B
A= defined $sinceB= $CGI::Buffer::info
ABresult
0X0
100
111
1891 0 ▶ $matches = (defined($age) && ($age == $since)) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $age && $age == $since ? : 0 0 0
Condition0%0/3
defined $age and $age == $since
!ll&&!rl&&r
000
MC/DC0%0/2
defined $age and $age == $since
defined $age $age == $since
Truth table0%0/3
A and B
A= defined $ageB= $age == $since
ABresult
0X0
100
111
1892 }
1893 }
1894 0 return $matches;
1895 }
1896  
1897 # Purpose: the CGI::Info object, which is created if it wasn't given
1898 # Entry criteria: none
1899 # Exit status: the object
1900 # Side effects: may load CGI::Info and set $info. Croaks if it can't
1901 33 ▶sub _info {
Subroutine _info: called CC=4 SCAR=13.9
1902 33 ▶ unless(defined($info)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $CGI::Buffer::info) 17 16 33
1903 17 require CGI::Info;
1904 17 ▶ $info = CGI::Info->new($cache ? { cache => $cache } : ())
Branch: 2 branches
BranchTrueFalseTotal
$CGI::Buffer::info = "CGI::Info"->new($CGI::Buffer::cache ? {"cache", $CGI::Buffer::cache} : ()) or croak(_i18n("no_info")) 17 0 17
$CGI::Buffer::cache ? : 1 16 17
1905 or croak(_i18n('no_info'));
1906 }
1907 33 return $info;
1908 }
1909  
1910 # Purpose: set the HTTP status, and tell CGI::Info if we have one
1911 # Entry criteria: $code is an HTTP status
1912 # Exit status: none
1913 # Side effects: sets $status
1914 20 ▶sub _set_status {
Subroutine _set_status: called CC=2 SCAR=6.9
1915 20 $status = shift;
1916 20 ▶ $info->status($status) if($info);
Branch: 1 branch
BranchTrueFalseTotal
if $CGI::Buffer::info 15 5 20
1917 }
1918  
1919 # Purpose: format a time for an HTTP header
1920 # Entry criteria: $time is seconds since the epoch
1921 # Exit status: the date, e.g. "Mon, 02 Nov 2026 12:00:00 GMT"
1922 # Side effects: loads HTTP::Date
1923 19 ▶sub _http_date {
Subroutine _http_date: called CC=1 SCAR=0.0
1924 19 require HTTP::Date;
1925 19 return HTTP::Date::time2str(shift);
1926 }
1927  
1928 # Purpose: read a date from an HTTP header
1929 # Entry criteria: $date is the header's value
1930 # Exit status: seconds since the epoch, or undef if it isn't a valid date
1931 # Side effects: loads HTTP::Date
1932 2 ▶sub _parse_http_date {
Subroutine _parse_http_date: called CC=1 SCAR=0.0
1933 2 require HTTP::Date;
1934 2 return HTTP::Date::str2time(shift);
1935 }
1936  
1937 # Purpose: say whether the protocol supports conditional requests (ETag etc.)
1938 # Entry criteria: none
1939 # Exit status: true if it does
1940 # Side effects: none
1941 32 ▶sub _is_conditional_protocol {
Subroutine _is_conditional_protocol: called CC=2 SCAR=7.2
1942 32 ▶ return defined($ENV{'SERVER_PROTOCOL'}) && ($ENV{'SERVER_PROTOCOL'} =~ $CONDITIONAL_PROTOCOL);
Condition66%2/3
defined $ENV{'SERVER_PROTOCOL'} && $ENV{'SERVER_PROTOCOL'} =~ /$CONDITIONAL_PROTOCOL/u
!ll&&!rl&&r
18014
MC/DC50%1/2
defined $ENV{'SERVER_PROTOCOL'} && $ENV{'SERVER_PROTOCOL'} =~ /$CONDITIONAL_PROTOCOL/u
defined $ENV{'SERVER_PROTOCOL'} $ENV{'SERVER_PROTOCOL'} =~ /$CONDITIONAL_PROTOCOL/u
Truth table66%2/3
A && B
A= defined $ENV{'SERVER_PROTOCOL'}B= $ENV{'SERVER_PROTOCOL'} =~ /$CONDITIONAL_PROTOCOL/u
ABresult
0X0
100
111
1943 }
1944  
1945 # Purpose: say whether this is a GET request. There is no method when running
1946 # from the command line, which is treated as GET
1947 # Entry criteria: none
1948 # Exit status: true if it is
1949 # Side effects: none
1950 0 ▶sub _is_get {
Subroutine _is_get: not called CC=2 SCAR=17.9
1951 0 ▶ return (!defined($ENV{'REQUEST_METHOD'})) || ($ENV{'REQUEST_METHOD'} eq 'GET');
Condition0%0/3
!defined($ENV{'REQUEST_METHOD'}) || $ENV{'REQUEST_METHOD'} eq 'GET'
l!l&&r!l&&!r
000
MC/DC0%0/2
!defined($ENV{'REQUEST_METHOD'}) || $ENV{'REQUEST_METHOD'} eq 'GET'
!defined($ENV{'REQUEST_METHOD'}) $ENV{'REQUEST_METHOD'} eq 'GET'
Truth table0%0/3
not(A) || B
A= !defined($ENV{'REQUEST_METHOD'})B= $ENV{'REQUEST_METHOD'} eq 'GET'
ABresult
1X1
011
000
1952 }
1953  
1954 # Purpose: the X-Cache and X-Cache-Lookup headers
1955 # Entry criteria: $cached and $lookup are "HIT" or "MISS"
1956 # Exit status: an arrayref of the two headers
1957 # Side effects: none
1958 22 ▶sub _x_cache_headers {
Subroutine _x_cache_headers: called CC=2 SCAR=6.9
1959 22 my ($cached, $lookup) = @_;
1960  
1961 22 ▶ my $from = $info ? ' from ' . $info->host_name() : '';
Branch: 1 branch
BranchTrueFalseTotal
$CGI::Buffer::info ? : 17 5 22
1962 22 return [ "X-Cache: $cached$from", "X-Cache-Lookup: $lookup$from" ];
1963 }
1964  
1965 # Purpose: work out the response to a Range header. Only a single range of
1966 # bytes is supported
1967 # Entry criteria: $b is the body, $range the Range header
1968 # Exit status: a hashref of the new status, body and Content-Range header, or
1969 # undef if the range isn't one that we support, in which case the header is
1970 # ignored and the whole body is sent.
1971 # 206: the part of the body asked for
1972 # 416: a valid range which is outside of the body, so has no body
1973 # Side effects: none
1974 0 ▶sub _apply_range {
Subroutine _apply_range: not called CC=13 SCAR=52.0
1975 0 my ($b, $range) = @_;
1976  
1977 0 ▶ return unless($range =~ /^bytes=(\d*)-(\d*)$/);
Branch: 1 branch
BranchTrueFalseTotal
unless $range =~ /^bytes=(\d*)-(\d*)$/u 0 0 0
1978 0 my ($first, $last) = ($1, $2);
1979 0 my $length = length($b);
1980  
1981 # "bytes=-" says nothing
1982 0 ▶ return if(($first eq '') && ($last eq ''));
Branch: 1 branch
BranchTrueFalseTotal
if $first eq "" and $last eq "" 0 0 0
Condition0%0/3
$first eq "" and $last eq ""
!ll&&!rl&&r
000
MC/DC0%0/2
$first eq "" and $last eq ""
$first eq "" $last eq ""
Truth table0%0/3
A and B
A= $first eq ""B= $last eq ""
ABresult
0X0
100
111
1983  
1984 # A backwards range is invalid, so is ignored (RFC 7233 2.1)
1985 0 ▶ return if(($first ne '') && ($last ne '') && ($first > $last));
Branch: 1 branch
BranchTrueFalseTotal
if $first ne "" and $last ne "" and $first > $last 0 0 0
Condition0%0/6
$first ne "" and $last ne "" and $first > $last
!ll&&!rl&&r
000
$first ne "" and $last ne ""
!ll&&!rl&&r
000
MC/DC0%0/3
$first ne "" and $last ne "" and $first > $last
$first ne "" $last ne "" $first > $last
Truth table0%0/4
A and B and C
A= $first ne ""B= $last ne ""C= $first > $last
ABCresult
0XX0
10X0
1100
1111
1986  
1987 0 ▶ if($first eq '') {
Branch: 2 branches
BranchTrueFalseTotal
if ($first eq '') { } 0 0 0
elsif ($last eq '' or $last >= $length) { } 0 0 0
1988 # "bytes=-n" is the last n bytes, all of it if there are
1989 # fewer than n. The last 0 bytes can't be satisfied
1990 0 ▶ $first = ($last >= $length) ? 0 : $length - $last;
Branch: 1 branch
BranchTrueFalseTotal
$last >= $length ? : 0 0 0
1991 0 $last = $length - 1;
1992 ▶ } elsif(($last eq '') || ($last >= $length)) {
Condition0%0/3
$last eq "" or $last >= $length
l!l&&r!l&&!r
000
MC/DC0%0/2
$last eq "" or $last >= $length
$last eq "" $last >= $length
Truth table0%0/3
A or B
A= $last eq ""B= $last >= $length
ABresult
1X1
011
000
1993 # A range past the end stops at the end
1994 0 $last = $length - 1;
1995 }
1996  
1997 # A range starting at or after the end can't be satisfied
1998 0 ▶ if(($first >= $length) || ($first > $last)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($first >= $length or $first > $last) 0 0 0
Condition0%0/3
$first >= $length or $first > $last
l!l&&r!l&&!r
000
MC/DC0%0/2
$first >= $length or $first > $last
$first >= $length $first > $last
Truth table0%0/3
A or B
A= $first >= $lengthB= $first > $last
ABresult
1X1
011
000
1999 0 return { status => $HTTP_RANGE_NOT_SATISFIABLE, content_range => "bytes */$length" };
2000 }
2001  
2002 return {
2003 0 status => $HTTP_PARTIAL_CONTENT,
2004 body => substr($b, $first, $last - $first + 1),
2005 content_range => "bytes $first-$last/$length",
2006 };
2007 }
2008  
2009 # Purpose: the values of a header in a block of headers
2010 # Entry criteria: $headers is the block, $name the header's name
2011 # Exit status: an arrayref of the values, which may be empty
2012 # Side effects: none
2013 4 ▶sub _header_values {
Subroutine _header_values: called CC=3 SCAR=14.2
2014 4 my ($headers, $name) = @_;
2015  
2016 return [ defined($headers) ?
2017 0 ▶ (map { /^[^:]+:\s*(.*?)\s*$/ ? $1 : () } grep { /^\Q$name\E:/i } split(/\r?\n/, $headers)) :
Branch: 2 branches
BranchTrueFalseTotal
defined $headers ? : 4 0 4
/^[^:]+:\s*(.*?)\s*$/u ? : 0 0 0
2018 () ];
2019 }
2020  
2021 # Purpose: say whether this response may be kept and given to other clients
2022 # Entry criteria: $headers and $body are the script's headers and body
2023 # Exit status: 1 if it may, otherwise 0
2024 # Side effects: none
2025 1 ▶sub _is_storable {
Subroutine _is_storable: called CC=16 SCAR=43.3
2026 1 my ($headers, $body) = @_;
2027  
2028 # It would log the next client in as this one
2029 1 ▶ 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");} 0 1 1
Condition33%1/3
@{_header_values($headers, "Set-Cookie");} or @{_header_values($headers, "Set-Cookie2");}
l!l&&r!l&&!r
001
MC/DC0%0/2
@{_header_values($headers, "Set-Cookie");} or @{_header_values($headers, "Set-Cookie2");}
@{_header_values($headers, "Set-Cookie");} @{_header_values($headers, "Set-Cookie2");}
Truth table33%1/3
A or B
A= @{_header_values($headers, "Set-Cookie");}B= @{_header_values($headers, "Set-Cookie2");}
ABresult
1X1
011
000
2030  
2031 # It would give this client's form token to the next one
2032 1 ▶ return 0 if(_has_form_token($body));
Branch: 1 branch
BranchTrueFalseTotal
if _has_form_token($body) 0 1 1
2033  
2034 1 foreach my $control(@{_header_values($headers, 'Cache-Control')}) {
2035 0 foreach my $directive(split(/\s*,\s*/, lc($control))) {
2036 0 (my $name = $directive) =~ s/\s*=.*$//;
2037 0 ▶ return 0 if($NO_CACHE_DIRECTIVES{$name});
Branch: 1 branch
BranchTrueFalseTotal
if $NO_CACHE_DIRECTIVES{$name} 0 0 0
2038 }
2039 }
2040  
2041 # Accept-Encoding is dealt with here, and lingua is part of the key.
2042 # Anything else isn't part of the key, so the page would be given to
2043 # clients that it wasn't meant for
2044 1 foreach my $vary(@{_header_values($headers, 'Vary')}) {
2045 0 foreach my $name(split(/\s*,\s*/, lc($vary))) {
2046 0 ▶ next if($name eq 'accept-encoding');
Branch: 1 branch
BranchTrueFalseTotal
if $name eq "accept-encoding" 0 0 0
2047 0 ▶ next if(($name eq 'accept-language') && $lingua);
Branch: 1 branch
BranchTrueFalseTotal
if $name eq "accept-language" and $CGI::Buffer::lingua 0 0 0
Condition0%0/3
$name eq "accept-language" and $CGI::Buffer::lingua
!ll&&!rl&&r
000
MC/DC0%0/2
$name eq "accept-language" and $CGI::Buffer::lingua
$name eq "accept-language" $CGI::Buffer::lingua
Truth table0%0/3
A and B
A= $name eq "accept-language"B= $CGI::Buffer::lingua
ABresult
0X0
100
111
2048 0 return 0;
2049 }
2050 }
2051  
2052 # An HTML page with no </html> suggests that the script died part way
2053 # through, so don't give the partial page to other clients
2054 1 ▶ if(_is_html() && defined($body) && ($body =~ /<html\b/i) && ($body !~ /<\/html\s*+>/i)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_is_html() and defined $body and $body =~ /<html\b/iu and not $body =~ m[</html\s*+>]iu) 0 1 1
Condition33%3/9
_is_html() and defined $body and $body =~ /<html\b/iu and not $body =~ m[</html\s*+>]iu
!ll&&!rl&&r
010
_is_html() and defined $body and $body =~ /<html\b/iu
!ll&&!rl&&r
001
_is_html() and defined $body
!ll&&!rl&&r
001
MC/DC0%0/4
_is_html() and defined $body and $body =~ /<html\b/iu and not $body =~ m[</html\s*+>]iu
_is_html() defined $body $body =~ /<html\b/iu not $body =~ m[</html\s*+>]iu
Truth table20%1/5
A and B and C and not(D)
A= _is_html()B= defined $bodyC= $body =~ /<html\b/iuD= not $body =~ m[</html\s*+>]iu
ABCDresult
0XXX0
10XX0
110X0
11100
11111
2055 0 _log('debug', 'Not storing an HTML page with no </html>');
2056 0 return 0;
2057 }
2058 1 return 1;
2059 }
2060  
2061 # Purpose: say whether the request method may be answered from a cache or with
2062 # a 304. There is no method when running from the command line
2063 # Entry criteria: none
2064 # Exit status: true if it may
2065 # Side effects: none
2066 8 ▶sub _is_safe_method {
Subroutine _is_safe_method: called CC=2 SCAR=7.2
2067 8 ▶ return (!defined($ENV{'REQUEST_METHOD'})) || $SAFE_METHODS{$ENV{'REQUEST_METHOD'}};
Condition66%2/3
!defined($ENV{'REQUEST_METHOD'}) || $SAFE_METHODS{$ENV{'REQUEST_METHOD'}}
l!l&&r!l&&!r
440
MC/DC0%0/2
!defined($ENV{'REQUEST_METHOD'}) || $SAFE_METHODS{$ENV{'REQUEST_METHOD'}}
!defined($ENV{'REQUEST_METHOD'}) $SAFE_METHODS{$ENV{'REQUEST_METHOD'}}
Truth table66%2/3
not(A) || B
A= !defined($ENV{'REQUEST_METHOD'})B= $SAFE_METHODS{$ENV{'REQUEST_METHOD'}}
ABresult
1X1
011
000
2068 }
2069  
2070 # Purpose: say whether the client has logged in
2071 # Entry criteria: none
2072 # Exit status: true if it has
2073 # Side effects: none
2074 4 ▶sub _is_logged_in {
Subroutine _is_logged_in: called CC=2 SCAR=9.2
2075 4 ▶ return $ENV{'HTTP_AUTHORIZATION'} || $ENV{'REMOTE_USER'};
Condition33%1/3
$ENV{'HTTP_AUTHORIZATION'} || $ENV{'REMOTE_USER'}
l!l&&r!l&&!r
004
MC/DC0%0/2
$ENV{'HTTP_AUTHORIZATION'} || $ENV{'REMOTE_USER'}
$ENV{'HTTP_AUTHORIZATION'} $ENV{'REMOTE_USER'}
Truth table33%1/3
A || B
A= $ENV{'HTTP_AUTHORIZATION'}B= $ENV{'REMOTE_USER'}
ABresult
1X1
011
000
2076 }
2077  
2078 # Purpose: the client's cookies, except for Google Analytics ones and the token
2079 # that protects forms, which are different for each client but don't change
2080 # the output. A page with a form is sent that token in a Set-Cookie header,
2081 # so _is_storable() doesn't store it
2082 # Entry criteria: none
2083 # Exit status: an arrayref of the cookies, as "name=value"
2084 # Side effects: none
2085 0 ▶sub _client_cookies {
Subroutine _client_cookies: not called CC=2 SCAR=17.9
2086 return [ $ENV{'HTTP_COOKIE'} ?
2087 0 ▶ (grep { !/^(?:__utm[abcz]|\Q$FORM_TOKEN_COOKIE\E=)/ } split(/;\s*/, $ENV{'HTTP_COOKIE'})) :
Branch: 1 branch
BranchTrueFalseTotal
$ENV{'HTTP_COOKIE'} ? : 0 0 0
2088 () ];
2089 }
2090  
2091 # Purpose: say whether this page includes the client's own form token.
2092 # _client_cookies() ignores the cookie that holds it, on the understanding
2093 # that it doesn't change the output. A script that puts its value into the
2094 # page has made the page per client
2095 # Entry criteria: $body is the page
2096 # Exit status: 1 if it does, otherwise 0
2097 # Side effects: none
2098 1 ▶sub _has_form_token {
Subroutine _has_form_token: called CC=8 SCAR=37.9
2099 1 my $body = shift;
2100  
2101 1 ▶ return 0 unless($ENV{'HTTP_COOKIE'} && defined($body));
Branch: 1 branch
BranchTrueFalseTotal
unless $ENV{"HTTP_COOKIE"} and defined $body 1 0 1
Condition33%1/3
$ENV{"HTTP_COOKIE"} and defined $body
!ll&&!rl&&r
100
MC/DC0%0/2
$ENV{"HTTP_COOKIE"} and defined $body
$ENV{"HTTP_COOKIE"} defined $body
Truth table33%1/3
A and B
A= $ENV{"HTTP_COOKIE"}B= defined $body
ABresult
0X0
100
111
2102  
2103 0 foreach my $cookie(split(/;\s*/, $ENV{'HTTP_COOKIE'})) {
2104 0 ▶ next unless($cookie =~ /^\Q$FORM_TOKEN_COOKIE\E=(.+)$/);
Branch: 1 branch
BranchTrueFalseTotal
unless $cookie =~ /^\Q$FORM_TOKEN_COOKIE\E=(.+)$/u 0 0 0
2105 0 my $token = $1;
2106 0 ▶ return 1 if(index($body, $token) >= 0);
Branch: 1 branch
BranchTrueFalseTotal
if (index($body, $token) != -1) 0 0 0
2107  
2108 # The cookie may be encoded, what's printed may not be
2109 0 ▶ 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;/egu) 0 0 0
2110 0 ▶ return 1 if(index($body, $token) >= 0);
Branch: 1 branch
BranchTrueFalseTotal
if (index($body, $token) != -1) 0 0 0
2111 }
2112 }
2113 0 return 0;
2114 }
2115  
2116 # Purpose: the directives in the request's Cache-Control header
2117 # Entry criteria: none
2118 # Exit status: a hashref of lower case name to value (undef when there is no
2119 # value)
2120 # Side effects: none
2121 11 ▶sub _cache_control {
Subroutine _cache_control: called CC=6 SCAR=31.0
2122 11 my %directives;
2123  
2124 11 ▶ if(defined(my $control = $ENV{'HTTP_CACHE_CONTROL'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $control = $ENV{"HTTP_CACHE_CONTROL"})) 0 11 11
2125 0 foreach my $directive(split(/\s*,\s*/, lc($control))) {
2126 0 my ($name, $value) = split(/\s*=\s*/, $directive, 2);
2127 0 ▶ next unless(defined($name) && length($name));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 0 0 0
Condition0%0/3
defined $name and length $name
!ll&&!rl&&r
000
MC/DC0%0/2
defined $name and length $name
defined $name length $name
Truth table0%0/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
2128 0 ▶ $value =~ s/^"(.*)"$/$1/ if(defined($value));
Branch: 1 branch
BranchTrueFalseTotal
if defined $value 0 0 0
2129 0 $directives{$name} = $value;
2130 }
2131 }
2132 11 return \%directives;
2133 }
2134  
2135 # Purpose: the max-age directive in the request. This comes from the client,
2136 # so it mustn't be trusted to be a number
2137 # Entry criteria: none
2138 # Exit status: the number of seconds, or undef if there isn't a valid one
2139 # Side effects: none
2140 7 ▶sub _client_max_age {
Subroutine _client_max_age: called CC=3 SCAR=13.1
2141 7 my $max_age = _cache_control()->{'max-age'};
2142  
2143 7 ▶ return (defined($max_age) && ($max_age =~ /^\d+$/)) ? $max_age : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $max_age && $max_age =~ /^\d+$/u ? : 0 7 7
Condition33%1/3
defined $max_age and $max_age =~ /^\d+$/u
!ll&&!rl&&r
700
MC/DC0%0/2
defined $max_age and $max_age =~ /^\d+$/u
defined $max_age $max_age =~ /^\d+$/u
Truth table33%1/3
A and B
A= defined $max_ageB= $max_age =~ /^\d+$/u
ABresult
0X0
100
111
2144 }
2145  
2146 =head1 MESSAGES
2147  
2148 Every message that CGI::Buffer gives starts with "CGI::Buffer: ".
2149 Each can be replaced, for example to translate it, by giving init() a
2150 C<messages> hash.
2151 Placeholders are written C<%{name}> followed by a sprintf conversion, e.g.
2152 C<%{key}s>.
2153 A message may instead be a hash of plural forms, C<one> and C<other>, chosen by
2154 its count.
2155  
2156 CGI::Buffer::init(messages => {
2157 unknown_option => 'init: option inconnue %{option}s ignoree',
2158 too_late => {
2159 one => 'Trop tard, %{count}d caractere a ete imprime',
2160 other => 'Trop tard, %{count}d caracteres ont ete imprimes',
2161 },
2162 });
2163  
2164 Key Placeholders Meaning
2165 -------------- ---------------- ------------------------------------------
2166 too_late count The cache was set up after printing
2167 unknown_option option init() was given an option it doesn't know
2168 bad_option option, reason init() was given an option of the wrong type
2169 failed what, error Something non-essential, e.g. the cache, failed
2170 no_cache_data key The page was cached, but now can't be read
2171 no_cache_body key, fields A cache entry has no body, so is removed
2172 logger_method method The logger lacks a method, so is ignored
2173 no_script_path - CGI::Info can't find the script (fatal)
2174 no_script_age path, error The script's file can't be read (logged)
2175 no_info - A CGI::Info object can't be created (fatal)
2176 send_failed error Processing the output failed; it's sent as is
2177 lint where, text An error found by HTML::Lint
2178  
2179 None of the messages refers to a person, so there are no gendered forms.
2180  
2181 =head1 LIMITATIONS
2182  
2183 =over 4
2184  
2185 =item * All of the state is in package variables, and the work is done in an
2186 END block.
2187 That fits CGI, where each request is a new process, but it means CGI::Buffer
2188 can't be used for more than one request, can't be reset, and can only be tested
2189 by running a script in another process.
2190 L<FCGI::Buffer> is the object-oriented version for persistent processes.
2191  
2192 =item * HTML is optimised with regular expressions, not an HTML parser.
2193 They are written to run in linear time and to leave C<< <pre> >> and
2194 C<< <textarea> >> alone, but HTML that's unusual enough can still be changed in
2195 ways that are visible, e.g. whitespace in an element styled with
2196 C<white-space: pre>.
2197 L<HTML::Packer> can take quadratic time on many unterminated C<< <script> >>
2198 tags.
2199  
2200 =item * Links to this site are shortened to absolute paths
2201 (C</foo/bar.htm>), not relative ones (C<../bar.htm>).
2202 Relative links would save a few more bytes, but break pages that use
2203 C<< <base href> >>, and pages reached through more than one path.
2204  
2205 =item * Only one byte range is supported, and Range is ignored when there's a
2206 server-side cache.
2207  
2208 =item * The server-side cache key can't include headers named by Vary, since
2209 it's needed before the script prints them; such pages aren't stored.
2210  
2211 =item * Only HTML is checked for having been cut short by the script dying.
2212  
2213 =item * lint_content sends HTML::Lint's errors to the client, and the
2214 X-CGI-Buffer header gives the version of CGI::Buffer.
2215 Neither should be relied upon in production.
2216  
2217 =item * init()'s options are checked by hand, rather than with
2218 L<Params::Validate::Strict>, and private routines are private by convention
2219 rather than enforced with L<Sub::Private>.
2220 Both add about 50ms to every request, since a CGI program is compiled afresh
2221 each time.
2222 For the same reason CGI::Info is only loaded when it's needed, so a script that
2223 uses CGI::Info must load it itself.
2224  
2225 =item * The server-side cache's duration isn't taken from the Expires or
2226 Cache-Control: max-age headers that the script gives.
2227  
2228 =back
2229  
2230 =head1 AUTHOR
2231  
2232 Nigel Horne, C<< <njh at bandsman.co.uk> >>
2233  
2234 =head1 BUGS
2235  
2236 CGI::Buffer should be safe even in scripts which produce lots of different
2237 output, e.g. e-commerce situations.
2238 On such pages, however, I strongly urge to setting generate_304 to 0 and
2239 sending the HTTP header "Cache-Control: no-cache".
2240  
2241 When using L<Template>, ensure that you don't use it to output to STDOUT,
2242 instead you will need to capture into a variable and print that.
2243 For example:
2244  
2245 my $output;
2246 $template->process($input, $vars, \$output) || ($output = $template->error());
2247 print $output;
2248  
2249 Can produce buggy JavaScript if you use the <!-- HIDING technique.
2250 This is a bug in L<JavaScript::Packer>, not CGI::Buffer.
2251 See https://github.com/nevesenin/javascript-packer-perl/issues/1#issuecomment-4356790
2252  
2253 Mod_deflate can confuse this when compressing output.
2254 Ensure that deflation is off for .pl files:
2255  
2256 SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|pl)$ no-gzip dont-vary
2257  
2258 If-None-Match uses the weak comparison of RFC 9110, so a client that has the
2259 compressed version of a page is sent a 304 when it asks for the uncompressed
2260 one, and vice versa.
2261  
2262 I advise adding CGI::Buffer as the last use statement so that it is
2263 cleared up first. In particular it should be loaded after
2264 L<Log::Log4perl>, if you're using that, so that any messages it
2265 produces are printed after the HTTP headers have been sent by
2266 CGI::Buffer;
2267  
2268 CGI::Buffer is not compatible with FastCGI, use L<FCGI::Buffer> instead.
2269  
2270 Please report any bugs or feature requests to C<bug-cgi-buffer at rt.cpan.org>,
2271 or through the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=CGI-Buffer>.
2272 I will be notified, and then you'll automatically be notified of progress on
2273 your bug as I make changes.
2274  
2275 =head1 SEE ALSO
2276  
2277 L<HTML::Packer>, L<HTML::Lint>, L<FCGI::Buffer>
2278  
2279 =head1 SUPPORT
2280  
2281 You can find documentation for this module with the perldoc command.
2282  
2283 perldoc CGI::Buffer
2284  
2285 You can also look for information at:
2286  
2287 =over 4
2288  
2289 =item * MetaCPAN
2290  
2291 L<https://metacpan.org/release/CGI-Buffer>
2292  
2293 =item * RT: CPAN's request tracker
2294  
2295 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=CGI-Buffer>
2296  
2297 =item * CPANTS
2298  
2299 L<http://cpants.cpanauthors.org/dist/CGI-Buffer>
2300  
2301 =item * CPAN Testers' Matrix
2302  
2303 L<http://matrix.cpantesters.org/?dist=CGI-Buffer>
2304  
2305 =item * CPAN Testers Dependencies
2306  
2307 L<http://deps.cpantesters.org/?module=CGI::Buffer>
2308  
2309 =back
2310  
2311 =head1 ACKNOWLEDGEMENTS
2312  
2313 The inspiration and code for some of this is cgi_buffer by Mark
2314 Nottingham: L<https://www.mnot.net/blog/2003/04/24/etags>.
2315  
2316 =head1 LICENSE AND COPYRIGHT
2317  
2318 The licence for cgi_buffer is:
2319  
2320 "(c) 2000 Copyright Mark Nottingham <mnot@pobox.com>
2321  
2322 This software may be freely distributed, modified and used,
2323 provided that this copyright notice remain intact.
2324  
2325 This software is provided 'as is' without warranty of any kind."
2326  
2327 The rest of the program is Copyright 2011-2026 Nigel Horne,
2328 and is released under the following licence: GPL2
2329  
2330 =cut
2331  
2332 28 1; # End of CGI::Buffer
↑ Summary