Net/Async/FastCGI/Request.pm

filter: Statementstmt 98.3% 238 / 242 Branchbran 76.8% 63 / 82 Conditioncond 71.4% 20 / 28 MC/DCmcdc 53.3% 8 / 15 Subroutinesub 100% 59 / 59 Podpod 82.1% 23 / 28 totaltotal 90.5% 411 / 454 CC 54 SCAR 12.0
CC
54
Cov
91%
as_http_request
9.8
read_stdin_line
6.2
read_stdin
5.0
CRAP 3.3
« Net/Async/FastCGI/PSGI.pm ↑ Summary Net/Async/FastCGI/ServerProtocol.pm »
1 # You may distribute under the terms of either the GNU General Public License
2 # or the Artistic License (the same terms as Perl itself)
3 #
4 # (C) Paul Evans, 2005-2024 -- leonerd@leonerd.org.uk
5  
6 package Net::Async::FastCGI::Request 0.26;
7  
8 18 ▶use v5.14;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 18 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 18 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 18 ▶use Net::FastCGI::Constant qw( :type :flag :protocol_status );
Subroutine BEGIN: called CC=1 SCAR=0.0
14 18 ▶use Net::FastCGI::Protocol qw(
Subroutine BEGIN: called CC=1 SCAR=0.0
15 parse_params
16 build_end_request_body
17 18 );
18  
19 # The largest amount of data we can fit in a FastCGI record - MUST NOT
20 # be greater than 2^16-1
21 18 ▶use constant MAXRECORDDATA => 65535;
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 18 ▶use Encode qw( find_encoding );
Subroutine BEGIN: called CC=1 SCAR=0.0
24 18 ▶use POSIX qw( EAGAIN );
Subroutine BEGIN: called CC=1 SCAR=0.0
25  
26 18 my $CRLF = "\x0d\x0a";
27  
28 =head1 NAME
29  
30 C<Net::Async::FastCGI::Request> - a single active FastCGI request
31  
32 =head1 SYNOPSIS
33  
34 use Net::Async::FastCGI;
35 use IO::Async::Loop;
36  
37 my $fcgi = Net::Async::FastCGI->new(
38 on_request => sub {
39 my ( $fcgi, $req ) = @_;
40  
41 my $path = $req->param( "PATH_INFO" );
42 $req->print_stdout( "Status: 200 OK\r\n" .
43 "Content-type: text/plain\r\n" .
44 "\r\n" .
45 "You requested $path" );
46 $req->finish();
47 }
48 );
49  
50 my $loop = IO::Async::Loop->new();
51  
52 $loop->add( $fcgi );
53  
54 $loop->run;
55  
56 =head1 DESCRIPTION
57  
58 Instances of this object class represent individual requests received from the
59 webserver that are currently in-progress, and have not yet been completed.
60 When given to the controlling program, each request will already have its
61 parameters (and, on servers without stdin streaming enabled, its STDIN data).
62 The program can then write response data to the STDOUT stream, messages to the
63 STDERR stream, and eventually finish it.
64  
65 This module would not be used directly by a program using
66 C<Net::Async::FastCGI>, but rather, objects in this class are passed into the
67 C<on_request> event of the containing C<Net::Async::FastCGI> object.
68  
69 =cut
70  
71 sub new
72 24 ▶{
Subroutine new: called CC=1 SCAR=0.0
Pod undocumented
73 24 my $class = shift;
74 24 my %args = @_;
75  
76 24 my $rec = $args{rec};
77  
78 my $self = bless {
79 conn => $args{conn},
80 fcgi => $args{fcgi},
81  
82 reqid => $rec->{reqid},
83 keepconn => $rec->{flags} & FCGI_KEEP_CONN,
84  
85 stdin => "",
86 stdindone => 0,
87 stream_stdin => $args{stream_stdin},
88  
89 24 params => {},
90 paramsdone => 0,
91  
92 stdout => "",
93 stderr => "",
94  
95 used_stderr => 0,
96 }, $class;
97  
98 24 $self->set_encoding( $args{fcgi}->_default_encoding );
99  
100 24 return $self;
101 }
102  
103 sub write_record
104 66 ▶{
Subroutine write_record: called CC=4 SCAR=14.8
Pod undocumented
105 66 my $self = shift;
106 66 my ( $rec ) = @_;
107  
108 66 ▶ return if $self->is_aborted;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_aborted 0 66 66
109  
110 66 my $content = $rec->{content};
111 66 my $contentlen = length( $content );
112 66 ▶ if( $contentlen > MAXRECORDDATA ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($contentlen > 65535) 0 66 66
113 0 warn __PACKAGE__."->write_record() called with content longer than ".MAXRECORDDATA." bytes - truncating";
114 0 $content = substr( $content, 0, MAXRECORDDATA );
115 }
116  
117 66 ▶ $rec->{reqid} = $self->{reqid} unless defined $rec->{reqid};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rec->{"reqid"} 66 0 66
118  
119 66 my $conn = $self->{conn};
120  
121 66 $conn->write_record( $rec, $content );
122  
123 }
124  
125 sub incomingrecord
126 73 ▶{
Subroutine incomingrecord: called CC=3 SCAR=11.2
Pod undocumented
127 73 my $self = shift;
128 73 my ( $rec ) = @_;
129  
130 73 my $type = $rec->{type};
131  
132 73 ▶ if( $type == FCGI_PARAMS ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($type == 4) { } 41 32 73
elsif ($type == 5) { } 32 0 32
133 41 $self->incomingrecord_params( $rec );
134 }
135 elsif( $type == FCGI_STDIN ) {
136 32 $self->incomingrecord_stdin( $rec );
137 }
138 else {
139 0 warn "$self just received unknown record type";
140 }
141 }
142  
143 sub _ready_check
144 52 ▶{
Subroutine _ready_check: called CC=4 SCAR=13.9
145 52 my $self = shift;
146  
147 52 ▶ if( $self->{paramsdone} and ( $self->{stdindone} || $self->{stream_stdin} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"paramsdone"} and $self->{"stdindone"} || $self->{"stream_stdin"}) 24 28 52
Condition83%5/6
$self->{"paramsdone"} and $self->{"stdindone"} || $self->{"stream_stdin"}
!ll&&!rl&&r
02824
$self->{"stdindone"} or $self->{"stream_stdin"}
l!l&&r!l&&!r
21328
MC/DC66%2/3
$self->{"paramsdone"} and $self->{"stdindone"} || $self->{"stream_stdin"}
$self->{"paramsdone"} $self->{"stdindone"} $self->{"stream_stdin"}
Truth table75%3/4
A and B or C
A= $self->{"paramsdone"}B= $self->{"stdindone"}C= $self->{"stream_stdin"}
ABCresult
0XX0
1000
11X1
1011
148 24 $self->{fcgi}->_request_ready( $self );
149 }
150 }
151  
152 sub incomingrecord_params
153 41 ▶{
Subroutine incomingrecord_params: called CC=2 SCAR=6.9
Pod undocumented
154 41 my $self = shift;
155 41 my ( $rec ) = @_;
156  
157 41 my $content = $rec->{content};
158 41 my $len = $rec->{len};
159  
160 41 ▶ if( $len ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($len) { } 17 24 41
161 18 ▶ no warnings 'uninitialized';
Subroutine BEGIN: called CC=1 SCAR=0.0
162 17 $self->{paramscontent} .= $content;
163 17 return;
164 }
165 else {
166 24 $self->{params} = parse_params( delete $self->{paramscontent} );
167 24 $self->{paramsdone} = 1;
168 }
169  
170 24 $self->_ready_check;
171 }
172  
173 sub incomingrecord_stdin
174 32 ▶{
Subroutine incomingrecord_stdin: called CC=3 SCAR=11.0
Pod undocumented
175 32 my $self = shift;
176 32 my ( $rec ) = @_;
177  
178 32 my $content = $rec->{content};
179 32 my $len = $rec->{len};
180  
181 32 ▶ if( $len ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($len) { } 10 22 32
182 10 $self->{stdin} .= $content;
183 }
184 else {
185 22 $self->{stdindone} = 1;
186 }
187  
188 32 ▶ if( $self->{stream_stdin} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'stream_stdin'}) { } 4 28 32
189 4 $self->_flush_stdin;
190 }
191 else {
192 28 $self->_ready_check;
193 }
194 }
195  
196 sub _start
197 24 ▶{
Subroutine _start: called CC=3 SCAR=11.0
198 24 my $self = shift;
199 24 $self->{started} = 1;
200  
201 24 ▶ $self->_flush_stdin if $self->{stream_stdin} and length $self->{stdin};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"stream_stdin"} and length $self->{"stdin"} 1 23 24
Condition100%3/3
$self->{"stream_stdin"} and length $self->{"stdin"}
!ll&&!rl&&r
2121
MC/DC100%2/2
$self->{"stream_stdin"} and length $self->{"stdin"}
$self->{"stream_stdin"} length $self->{"stdin"}
Truth table100%3/3
A and B
A= $self->{"stream_stdin"}B= length $self->{"stdin"}
ABresult
0X0
100
111
202 }
203  
204 sub _flush_stdin
205 5 ▶{
Subroutine _flush_stdin: called CC=5 SCAR=16.1
206 5 my $self = shift;
207  
208 5 my $on_stdin = $self->{on_stdin_read};
209 5 ▶ if( !$on_stdin ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($on_stdin) 1 4 5
210 1 ▶ warn "NaFastCGI::Request incoming STDIN data with on on_stdin_read\n" if $self->{started};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"started"} 0 1 1
211 1 return;
212 }
213  
214 {
215 4 my $ret = $self->$on_stdin( \$self->{stdin}, $self->{stdindone} );
216 13 ▶ redo if $ret and length $self->{stdin};
Branch: 1 branch
BranchTrueFalseTotal
if $ret and length $self->{"stdin"} 9 4 13
Condition100%3/3
$ret and length $self->{"stdin"}
!ll&&!rl&&r
319
MC/DC100%2/2
$ret and length $self->{"stdin"}
$ret length $self->{"stdin"}
Truth table100%3/3
A and B
A= $retB= length $self->{"stdin"}
ABresult
0X0
100
111
217 }
218 }
219  
220 =head1 METHODS
221  
222 =cut
223  
224 =head2 params
225  
226 $hashref = $req->params;
227  
228 This method returns a reference to a hash containing a copy of the request
229 parameters that had been sent by the webserver as part of the request.
230  
231 =cut
232  
233 sub params
234 18 ▶{
Subroutine params: called CC=1 SCAR=0.0
Pod documented
235 18 my $self = shift;
236  
237 18 my %p = %{$self->{params}};
238  
239 18 return \%p;
240 }
241  
242 =head2 param
243  
244 $p = $req->param( $key );
245  
246 This method returns the value of a single request parameter, or C<undef> if no
247 such key exists.
248  
249 =cut
250  
251 sub param
252 20 ▶{
Subroutine param: called CC=1 SCAR=0.0
Pod documented
253 20 my $self = shift;
254 20 my ( $key ) = @_;
255  
256 20 return $self->{params}{$key};
257 }
258  
259 =head2 method
260  
261 $method = $req->method;
262  
263 Returns the value of the C<REQUEST_METHOD> parameter, or C<GET> if there is no
264 value set for it.
265  
266 =cut
267  
268 sub method
269 2 ▶{
Subroutine method: called CC=2 SCAR=7.2
Pod documented
270 2 my $self = shift;
271 2 ▶ return $self->param( "REQUEST_METHOD" ) || "GET";
Condition50%1/2
$self->param('REQUEST_METHOD') || 'GET'
l!l
20
MC/DC0%0/1
$self->param('REQUEST_METHOD') || 'GET'
$self->param('REQUEST_METHOD')
Truth table50%1/2
A
A= $self->param('REQUEST_METHOD')
Aresult
11
00
272 }
273  
274 =head2 script_name
275  
276 $script_name = $req->script_name;
277  
278 Returns the value of the C<SCRIPT_NAME> parameter.
279  
280 =cut
281  
282 sub script_name
283 3 ▶{
Subroutine script_name: called CC=1 SCAR=0.0
Pod documented
284 3 my $self = shift;
285 3 return $self->param( "SCRIPT_NAME" );
286 }
287  
288 =head2 path_info
289  
290 $path_info = $req->path_info;
291  
292 Returns the value of the C<PATH_INFO> parameter.
293  
294 =cut
295  
296 sub path_info
297 3 ▶{
Subroutine path_info: called CC=1 SCAR=0.0
Pod documented
298 3 my $self = shift;
299 3 return $self->param( "PATH_INFO" );
300 }
301  
302 =head2 path
303  
304 $path = $req->path;
305  
306 Returns the full request path by reconstructing it from C<script_name> and
307 C<path_info>.
308  
309 =cut
310  
311 sub path
312 2 ▶{
Subroutine path: called CC=3 SCAR=12.0
Pod documented
313 2 my $self = shift;
314  
315 2 ▶ my $path = join "", grep defined && length,
Condition33%1/3
defined $_ && length $_
!ll&&!rl&&r
004
MC/DC0%0/2
defined $_ && length $_
defined $_ length $_
Truth table33%1/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
316 $self->script_name,
317 $self->path_info;
318 2 ▶ $path = "/" if !length $path;
Branch: 1 branch
BranchTrueFalseTotal
unless length $path 0 2 2
319  
320 2 return $path;
321 }
322  
323 =head2 query_string
324  
325 $query_string = $req->query_string;
326  
327 Returns the value of the C<QUERY_STRING> parameter.
328  
329 =cut
330  
331 sub query_string
332 2 ▶{
Subroutine query_string: called CC=2 SCAR=6.9
Pod documented
333 2 my $self = shift;
334 2 ▶ return $self->param( "QUERY_STRING" ) || "";
Condition100%2/2
$self->param('QUERY_STRING') || ''
l!l
11
MC/DC100%1/1
$self->param('QUERY_STRING') || ''
$self->param('QUERY_STRING')
Truth table100%2/2
A
A= $self->param('QUERY_STRING')
Aresult
11
00
335 }
336  
337 =head2 protocol
338  
339 $protocol = $req->protocol;
340  
341 Returns the value of the C<SERVER_PROTOCOL> parameter.
342  
343 =cut
344  
345 sub protocol
346 2 ▶{
Subroutine protocol: called CC=1 SCAR=0.0
Pod documented
347 2 my $self = shift;
348 2 return $self->param( "SERVER_PROTOCOL" );
349 }
350  
351 =head2 set_encoding
352  
353 $req->set_encoding( $encoding );
354  
355 Sets the character encoding used by the request's STDIN, STDOUT and STDERR
356 streams. This method may be called at any time to change the encoding in
357 effect, which will be used the next time C<read_stdin_line>, C<read_stdin>,
358 C<print_stdout> or C<print_stderr> are called. This encoding will remain in
359 effect until changed again. The encoding of a new request is determined by the
360 C<default_encoding> parameter of the containing C<Net::Async::FastCGI> object.
361 If the value C<undef> is passed, the encoding will be removed, and the above
362 methods will work directly on bytes instead of encoded strings.
363  
364 =cut
365  
366 sub set_encoding
367 25 ▶{
Subroutine set_encoding: called CC=3 SCAR=11.6
Pod documented
368 25 my $self = shift;
369 25 my ( $encoding ) = @_;
370  
371 25 ▶ if( defined $encoding ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $encoding) { } 25 0 25
372 25 my $codec = find_encoding( $encoding );
373 25 ▶ defined $codec or croak "Unrecognised encoding '$encoding'";
Branch: 1 branch
BranchTrueFalseTotal
defined $codec or croak("Unrecognised encoding '${encoding}'") 25 0 25
374 25 $self->{codec} = $codec;
375 }
376 else {
377 0 undef $self->{codec};
378 }
379 }
380  
381 =head2 read_stdin_line
382  
383 $line = $req->read_stdin_line;
384  
385 This method works similarly to the C<< <HANDLE> >> operator. If at least one
386 line of data is available then it is returned, including the linefeed, and
387 removed from the buffer. If not, then any remaining partial line is returned
388 and removed from the buffer. If no data is available any more, then C<undef>
389 is returned instead.
390  
391 =cut
392  
393 sub read_stdin_line
394 13 ▶{
Subroutine read_stdin_line: called CC=6 SCAR=18.2
Pod documented
395 13 my $self = shift;
396 13 ▶ croak "Cannot call ->read_stdin_line on streaming-stdin requests" if $self->{stream_stdin};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"stream_stdin"} 0 13 13
397  
398 13 my $codec = $self->{codec};
399  
400 13 ▶ if( $self->{stdin} =~ s/^(.*[\r\n])// ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'stdin'} =~ s/^(.*[\r\n])//u) { } 4 9 13
elsif ($self->{'stdin'} =~ s/^(.+)//u) { } 1 8 9
401 4 ▶ return $codec ? $codec->decode( $1 ) : $1;
Branch: 1 branch
BranchTrueFalseTotal
$codec ? : 4 0 4
402 }
403 elsif( $self->{stdin} =~ s/^(.+)// ) {
404 1 ▶ return $codec ? $codec->decode( $1 ) : $1;
Branch: 1 branch
BranchTrueFalseTotal
$codec ? : 1 0 1
405 }
406 else {
407 8 return undef;
408 }
409 }
410  
411 =head2 read_stdin
412  
413 $data = $req->read_stdin( $size );
414  
415 This method works similarly to the C<read(HANDLE)> function. It returns the
416 next block of up to $size bytes from the STDIN buffer. If no data is available
417 any more, then C<undef> is returned instead. If $size is not defined, then it
418 will return all the available data.
419  
420 =cut
421  
422 sub read_stdin
423 8 ▶{
Subroutine read_stdin: called CC=5 SCAR=16.2
Pod documented
424 8 my $self = shift;
425 8 ▶ croak "Cannot call ->read_stdin on streaming-stdin requests" if $self->{stream_stdin};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"stream_stdin"} 0 8 8
426 8 my ( $size ) = @_;
427  
428 8 ▶ return undef unless length $self->{stdin};
Branch: 1 branch
BranchTrueFalseTotal
unless length $self->{"stdin"} 2 6 8
429  
430 6 ▶ $size = length $self->{stdin} unless defined $size;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $size 1 5 6
431  
432 6 my $codec = $self->{codec};
433  
434 # If $size is too big, substr() will cope
435 6 my $bytes = substr( $self->{stdin}, 0, $size, "" );
436 6 ▶ return $codec ? $codec->decode( $bytes ) : $bytes;
Branch: 1 branch
BranchTrueFalseTotal
$codec ? : 6 0 6
437 }
438  
439 =head2 set_on_stdin_read
440  
441 $req->set_on_stdin_read( $on_stdin_read );
442  
443 $again = $on_stdin_read->( $req, $buffref, $eof );
444  
445 I<Since version 0.26.>
446  
447 Only valid on requests on servers with stdin streaming enabled.
448  
449 This method should be called as part of the C<on_request> event on the server,
450 to set the callback function to invoke when new data is provided to the stdin
451 stream for this request.
452  
453 The callback function is invoked in a similar style to the C<on_read> event
454 handler of an L<IO::Async::Stream>. It is passed the request itself, along
455 with a SCALAR reference to the buffer containing the stdin data, and a boolean
456 indicating if the end of stdin data has been reached.
457  
458 It should inspect this buffer and remove some prefix of it that it wishes to
459 consume. Any remaining content will be present on the next call. If it returns
460 a true value, the callback will be invoked again immediately, to consume more
461 data. This continues until there is no more data left, or it returns false.
462  
463 =cut
464  
465 sub set_on_stdin_read
466 3 ▶{
Subroutine set_on_stdin_read: called CC=2 SCAR=7.1
Pod documented
467 3 my $self = shift;
468 3 ▶ croak "Cannot call ->set_on_stdin_read except on streaming-stdin requests" unless $self->{stream_stdin};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"stream_stdin"} 0 3 3
469 3 ( $self->{on_stdin_read} ) = @_;
470 }
471  
472 sub _print_stream
473 23 ▶{
Subroutine _print_stream: called CC=2 SCAR=6.9
474 23 my $self = shift;
475 23 my ( $data, $stream ) = @_;
476  
477 23 ▶ while( length $data ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $data) 23 23 46
478 # Send chunks of up to MAXRECORDDATA bytes at once
479 23 my $chunk = substr( $data, 0, MAXRECORDDATA, "" );
480 23 $self->write_record( { type => $stream, content => $chunk } );
481 }
482 }
483  
484 sub _flush_streams
485 36 ▶{
Subroutine _flush_streams: called CC=4 SCAR=13.9
486 36 my $self = shift;
487  
488 36 ▶ if( length $self->{stdout} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (length $self->{'stdout'}) { } 20 16 36
elsif (my $cb = $self->{'stdout_cb'}) { } 4 12 16
489 20 $self->_print_stream( $self->{stdout}, FCGI_STDOUT );
490 20 $self->{stdout} = "";
491 }
492 elsif( my $cb = $self->{stdout_cb} ) {
493 4 $cb->();
494 }
495  
496 36 ▶ if( length $self->{stderr} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $self->{"stderr"}) 3 33 36
497 3 $self->_print_stream( $self->{stderr}, FCGI_STDERR );
498 3 $self->{stderr} = "";
499 }
500 }
501  
502 sub _needs_flush
503 16 ▶{
Subroutine _needs_flush: called CC=1 SCAR=0.0
504 16 my $self = shift;
505 16 return defined $self->{stdout_cb};
506 }
507  
508 =head2 print_stdout
509  
510 $req->print_stdout( $data );
511  
512 This method appends the given data to the STDOUT stream of the FastCGI
513 request, sending it to the webserver to be sent to the client.
514  
515 =cut
516  
517 sub print_stdout
518 41 ▶{
Subroutine print_stdout: called CC=2 SCAR=7.0
Pod documented
519 41 my $self = shift;
520 41 my ( $data ) = @_;
521  
522 41 my $codec = $self->{codec};
523  
524 41 ▶ $self->{stdout} .= $codec ? $codec->encode( $data ) : $data;
Branch: 1 branch
BranchTrueFalseTotal
$codec ? : 41 0 41
525  
526 41 $self->{conn}->_req_needs_flush( $self );
527 }
528  
529 =head2 print_stderr
530  
531 $req->print_stderr( $data );
532  
533 This method appends the given data to the STDERR stream of the FastCGI
534 request, sending it to the webserver.
535  
536 =cut
537  
538 sub print_stderr
539 3 ▶{
Subroutine print_stderr: called CC=2 SCAR=7.0
Pod documented
540 3 my $self = shift;
541 3 my ( $data ) = @_;
542  
543 3 my $codec = $self->{codec};
544  
545 3 $self->{used_stderr} = 1;
546 3 ▶ $self->{stderr} .= $codec ? $codec->encode( $data ) : $data;
Branch: 1 branch
BranchTrueFalseTotal
$codec ? : 3 0 3
547  
548 3 $self->{conn}->_req_needs_flush( $self );
549 }
550  
551 =head2 stream_stdout_then_finish
552  
553 $req->stream_stdout_then_finish( $readfn, $exitcode );
554  
555 This method installs a callback for streaming data to the STDOUT stream.
556 Whenever the output stream is otherwise-idle, the function will be called to
557 generate some more data to output. When this function returns C<undef> it
558 indicates the end of the stream, and the request will be finished with the
559 given exit code.
560  
561 If this method is used, then care should be taken to ensure that the number of
562 bytes written to the server matches the number that was claimed in the
563 C<Content-Length>, if such was provided. This logic should be performed by the
564 containing application; C<Net::Async::FastCGI> will not track it.
565  
566 =cut
567  
568 sub stream_stdout_then_finish
569 2 ▶{
Subroutine stream_stdout_then_finish: called CC=1 SCAR=0.0
Pod documented
570 2 my $self = shift;
571 2 my ( $readfn, $exitcode ) = @_;
572  
573 4 ▶ $self->{stdout_cb} = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
574 4 my $data = $readfn->();
575  
576 4 ▶ if( defined $data ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $data) { } 2 2 4
577 2 $self->print_stdout( $data );
578 }
579 else {
580 2 delete $self->{stdout_cb};
581 2 $self->finish( $exitcode );
582 }
583 2 };
584  
585 2 $self->{conn}->_req_needs_flush( $self );
586 }
587  
588 =head2 stdin
589  
590 $stdin = $req->stdin;
591  
592 Returns an IO handle representing the request's STDIN buffer. This may be read
593 from using the C<read> or C<readline> functions or the C<< <$stdin> >>
594 operator.
595  
596 Note that this will be a tied IO handle, it will not be useable directly as an
597 OS-level filehandle.
598  
599 =cut
600  
601 sub stdin
602 7 ▶{
Subroutine stdin: called CC=1 SCAR=0.0
Pod documented
603 7 my $self = shift;
604  
605 return Net::Async::FastCGI::Request::TiedHandle->new(
606 3 ▶ READ => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
607 3 $_[1] = $self->read_stdin( $_[2] );
608 3 ▶ return defined $_[1] ? length $_[1] : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $_[1] ? : 2 1 3
609 },
610 1 ▶ READLINE => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
611 1 return $self->read_stdin_line;
612 },
613 7 );
614 }
615  
616 =head2 stdout
617  
618 =head2 stderr
619  
620 $stdout = $req->stdout;
621  
622 $stderr = $req->stderr;
623  
624 Returns an IO handle representing the request's STDOUT or STDERR streams
625 respectively. These may written to using C<print>, C<printf>, C<say>, etc..
626  
627 Note that these will be tied IO handles, they will not be useable directly as
628 an OS-level filehandle.
629  
630 =cut
631  
632 sub _stdouterr
633 8 ▶{
Subroutine _stdouterr: called CC=1 SCAR=0.0
634 8 my $self = shift;
635 8 my ( $method ) = @_;
636  
637 return Net::Async::FastCGI::Request::TiedHandle->new(
638 3 ▶ WRITE => sub { $self->$method( $_[1] ) },
Subroutine __ANON__: called CC=1 SCAR=0.0
639 8 );
640 }
641  
642 sub stdout
643 1 ▶{
Subroutine stdout: called CC=1 SCAR=0.0
Pod documented
644 1 return shift->_stdouterr( "print_stdout" );
645 }
646  
647 sub stderr
648 7 ▶{
Subroutine stderr: called CC=1 SCAR=0.0
Pod documented
649 7 return shift->_stdouterr( "print_stderr" );
650 }
651  
652 =head2 finish
653  
654 $req->finish( $exitcode );
655  
656 When the request has been dealt with, this method should be called to indicate
657 to the webserver that it is finished. After calling this method, no more data
658 may be appended to the STDOUT stream. At some point after calling this method,
659 the request object will be removed from the containing C<Net::Async::FastCGI>
660 object, once all the buffered outbound data has been sent.
661  
662 If present, C<$exitcode> should indicate the numeric status code to send to
663 the webserver. If absent, a value of C<0> is presumed.
664  
665 =cut
666  
667 sub finish
668 21 ▶{
Subroutine finish: called CC=5 SCAR=16.1
Pod documented
669 21 my $self = shift;
670 21 my ( $exitcode ) = @_;
671  
672 21 ▶ return if $self->is_aborted;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_aborted 1 20 21
673  
674 20 $self->_flush_streams;
675  
676 # Signal the end of STDOUT
677 20 $self->write_record( { type => FCGI_STDOUT, content => "" } );
678  
679 # Signal the end of STDERR if we used it
680 20 ▶ $self->write_record( { type => FCGI_STDERR, content => "" } ) if $self->{used_stderr};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"used_stderr"} 3 17 20
681  
682 20 ▶ $self->write_record( { type => FCGI_END_REQUEST,
Condition100%2/2
$exitcode || 0
l!l
218
MC/DC100%1/1
$exitcode || 0
$exitcode
Truth table100%2/2
A
A= $exitcode
Aresult
11
00
683 content => build_end_request_body( $exitcode || 0, FCGI_REQUEST_COMPLETE )
684 } );
685  
686 20 my $conn = $self->{conn};
687  
688 20 ▶ if( $self->{keepconn} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'keepconn'}) { } 12 8 20
689 12 $conn->_removereq( $self->{reqid} );
690 }
691 else {
692 8 $conn->close;
693 }
694 }
695  
696 =head2 stdout_with_close
697  
698 $stdout = $req->stdout_with_close;
699  
700 Similar to the C<stdout> method, except that when the C<close> method is
701 called on the returned filehandle, the request will be finished by calling
702 C<finish>.
703  
704 =cut
705  
706 sub stdout_with_close
707 1 ▶{
Subroutine stdout_with_close: called CC=1 SCAR=0.0
Pod documented
708 1 my $self = shift;
709  
710 return Net::Async::FastCGI::Request::TiedHandle->new(
711 2 ▶ WRITE => sub { $self->print_stdout( $_[1] ) },
Subroutine __ANON__: called CC=1 SCAR=0.0
712 1 ▶ CLOSE => sub { $self->finish( 0 ) },
Subroutine __ANON__: called CC=1 SCAR=0.0
713 1 );
714 }
715  
716 sub _abort
717 9 ▶{
Subroutine _abort: called CC=1 SCAR=0.0
718 9 my $self = shift;
719 9 $self->{aborted} = 1;
720  
721 9 my $conn = $self->{conn};
722 9 $conn->_removereq( $self->{reqid} );
723  
724 9 delete $self->{stdout_cb};
725 }
726  
727 =head2 is_aborted
728  
729 $req->is_aborted;
730  
731 Returns true if the webserver has already closed the control connection. No
732 further work on this request is necessary, as it will be discarded.
733  
734 It is not required to call this method; if the request is aborted then any
735 output will be discarded. It may however be useful to call just before
736 expensive operations, in case effort can be avoided if it would otherwise be
737 wasted.
738  
739 =cut
740  
741 sub is_aborted
742 90 ▶{
Subroutine is_aborted: called CC=1 SCAR=0.0
Pod documented
743 90 my $self = shift;
744 90 return $self->{aborted};
745 }
746  
747 =head1 HTTP::Request/Response Interface
748  
749 The following pair of methods form an interface that allows the request to be
750 used as a source of L<HTTP::Request> objects, responding to them by sending
751 L<HTTP::Response> objects. This may be useful to fit it in to existing code
752 that already uses these.
753  
754 =cut
755  
756 =head2 as_http_request
757  
758 $http_req = $req->as_http_request;
759  
760 Returns a new C<HTTP::Request> object that gives a reasonable approximation to
761 the request. Because the webserver has translated the original HTTP request
762 into FastCGI parameters, this may not be a perfect recreation of the request
763 as received by the webserver.
764  
765 =cut
766  
767 sub as_http_request
768 1 ▶{
Subroutine as_http_request: called CC=9 SCAR=22.9
Pod documented
769 1 my $self = shift;
770  
771 1 require HTTP::Request;
772  
773 1 my $params = $self->params;
774  
775 my $authority =
776 ( $params->{HTTP_HOST} || $params->{SERVER_NAME} || "" ) . ":" .
777 1 ▶ ( $params->{SERVER_PORT} || "80" );
Condition42%3/7
$params->{'HTTP_HOST'} || $params->{'SERVER_NAME'} || ''
l!l
10
$params->{"HTTP_HOST"} or $params->{"SERVER_NAME"}
l!l&&r!l&&!r
100
$params->{'SERVER_PORT'} || '80'
l!l
10
MC/DC0%0/2
$params->{'HTTP_HOST'} || $params->{'SERVER_NAME'} || ''
$params->{"HTTP_HOST"} $params->{"SERVER_NAME"}
MC/DC0%0/1
$params->{'SERVER_PORT'} || '80'
$params->{'SERVER_PORT'}
Truth table33%1/3
A or B
A= $params->{"HTTP_HOST"}B= $params->{"SERVER_NAME"}
ABresult
1X1
011
000
Truth table50%1/2
A
A= $params->{'SERVER_PORT'}
Aresult
11
00
778  
779 1 my $path = $self->path;
780 1 my $query_string = $self->query_string;
781  
782 1 ▶ $path .= "?$query_string" if length $query_string;
Branch: 1 branch
BranchTrueFalseTotal
if length $query_string 0 1 1
783  
784 1 my $uri = URI->new( "http://$authority$path" )->canonical;
785  
786 1 my @headers;
787  
788 # Content-Type and Content-Length come specially
789 push @headers, "Content-Type" => $params->{CONTENT_TYPE}
790 1 ▶ if exists $params->{CONTENT_TYPE};
Branch: 1 branch
BranchTrueFalseTotal
if exists $params->{"CONTENT_TYPE"} 1 0 1
791  
792 push @headers, "Content-Length" => $params->{CONTENT_LENGTH}
793 1 ▶ if exists $params->{CONTENT_LENGTH};
Branch: 1 branch
BranchTrueFalseTotal
if exists $params->{"CONTENT_LENGTH"} 1 0 1
794  
795 # Pull all the HTTP_FOO parameters as headers. These will be in all-caps
796 # and use _ for word separators, but HTTP::Headers can cope
797 1 foreach ( keys %$params ) {
798 11 ▶ m/^HTTP_(.*)$/ and push @headers, $1 => $params->{$_};
Branch: 1 branch
BranchTrueFalseTotal
/^HTTP_(.*)$/u and push @headers, $1, $params->{$_} 1 10 11
799 }
800  
801 1 my $content = $self->{stdin};
802  
803 1 my $req = HTTP::Request->new( $self->method, $uri, \@headers, $content );
804  
805 1 $req->protocol( $self->protocol );
806  
807 1 return $req;
808 }
809  
810 =head2 send_http_response
811  
812 $req->send_http_response( $resp );
813  
814 Sends the given C<HTTP::Response> object as the response to this request. The
815 status, headers and content are all written out to the request's STDOUT stream
816 and then the request is finished with 0 as the exit code.
817  
818 =cut
819  
820 sub send_http_response
821 1 ▶{
Subroutine send_http_response: called CC=1 SCAR=0.0
Pod documented
822 1 my $self = shift;
823 1 my ( $resp ) = @_;
824  
825 # (Fast)CGI suggests this is the way to report the status
826 1 $resp->header( Status => $resp->code );
827  
828 1 my $topline = $resp->protocol . " " . $resp->status_line;
829  
830 1 $self->print_stdout( $topline . $CRLF );
831 1 $self->print_stdout( $resp->headers_as_string( $CRLF ) );
832  
833 1 $self->print_stdout( $CRLF );
834  
835 1 $self->print_stdout( $resp->content );
836 1 $self->finish( 0 );
837 }
838  
839 package # hide from CPAN
840 Net::Async::FastCGI::Request::TiedHandle;
841 18 ▶use base qw( Tie::Handle );
Subroutine BEGIN: called CC=1 SCAR=0.0
842  
843 18 ▶use Symbol qw( gensym );
Subroutine BEGIN: called CC=1 SCAR=0.0
844  
845 sub new
846 16 ▶{
Subroutine new: called CC=1 SCAR=0.0
847 16 my $class = shift;
848  
849 16 my $handle = gensym;
850 16 tie *$handle, $class, @_;
851  
852 16 return $handle;
853 }
854  
855 sub TIEHANDLE
856 16 ▶{
Subroutine TIEHANDLE: called CC=1 SCAR=0.0
857 16 my $class = shift;
858 16 return bless { @_ }, $class;
859 }
860  
861 1 ▶sub CLOSE { shift->{CLOSE}->( @_ ) }
Subroutine CLOSE: called CC=1 SCAR=0.0
862 3 ▶sub READ { shift->{READ}->( @_ ) }
Subroutine READ: called CC=1 SCAR=0.0
863 1 ▶sub READLINE { shift->{READLINE}->( @_ ) }
Subroutine READLINE: called CC=1 SCAR=0.0
864 5 ▶sub WRITE { shift->{WRITE}->( @_ ) }
Subroutine WRITE: called CC=1 SCAR=0.0
865  
866 =head1 EXAMPLES
867  
868 =head2 Streaming A File
869  
870 To serve contents of files on disk, it may be more efficient to use
871 C<stream_stdout_then_finish>:
872  
873 use Net::Async::FastCGI;
874 use IO::Async::Loop;
875  
876 my $fcgi = Net::Async::FastCGI->new(
877 on_request => sub {
878 my ( $fcgi, $req ) = @_;
879  
880 open( my $file, "<", "/path/to/file" );
881 $req->print_stdout( "Status: 200 OK\r\n" .
882 "Content-type: application/octet-stream\r\n" .
883 "\r\n" );
884  
885 $req->stream_stdout_then_finish(
886 sub { read( $file, my $buffer, 8192 ) or return undef; return $buffer },
887 0
888 );
889 }
890  
891 my $loop = IO::Async::Loop->new();
892  
893 $loop->add( $fcgi );
894  
895 $loop->run;
896  
897 It may be more efficient again to instead use the C<X-Sendfile> feature of
898 certain webservers, which allows the webserver itself to serve the file
899 efficiently. See your webserver's documentation for more detail.
900  
901 =head1 AUTHOR
902  
903 Paul Evans <leonerd@leonerd.org.uk>
904  
905 =cut
906  
907 18 0x55AA;
« Net/Async/FastCGI/PSGI.pm ↑ Summary Net/Async/FastCGI/ServerProtocol.pm »