blib/lib/Plack/App/WrapCGI.pm untested

filter: Statementstmt 0.0% 0 / 76 Branchbran 0.0% 0 / 10 Conditioncond 0.0% 0 / 14 MC/DCmcdc 0.0% 0 / 9 Subroutinesub 0.0% 0 / 12 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 124 CC 6 SCAR 23.7
CC
6
Cov
0%
prepare_app
30.0
slurp_fh
6.0
call
2.0
CRAP 10.7
1 package Plack::App::WrapCGI;
2 use strict;
3 use warnings;
4 use parent qw(Plack::Component);
5 use Plack::Util::Accessor qw(script execute _app);
6 use File::Spec;
7 use CGI::Emulate::PSGI;
8 use CGI::Compile;
9 use Carp;
10 use POSIX ":sys_wait_h";
11  
12 sub slurp_fh {
13 my $fh = $_[0];
14 local $/;
15 my $v = <$fh>;
16 defined $v ? $v : '';
17 }
18  
19 sub prepare_app {
20 my $self = shift;
21 my $script = $self->script
22 or croak "'script' is not set";
23  
24 $script = File::Spec->rel2abs($script);
25  
26 if ($self->execute) {
27 my $app = sub {
28 my $env = shift;
29  
30 pipe( my $stdoutr, my $stdoutw );
31 pipe( my $stdinr, my $stdinw );
32  
33 local $SIG{CHLD} = 'DEFAULT';
34  
35 my $pid = fork();
36 Carp::croak("fork failed: $!") unless defined $pid;
37  
38  
39 if ($pid == 0) { # child
40 local $SIG{__DIE__} = sub {
41 print STDERR @_;
42 exit(1);
43 };
44  
45 close $stdoutr;
46 close $stdinw;
47  
48 local %ENV = (%ENV, CGI::Emulate::PSGI->emulate_environment($env));
49  
50 open( STDOUT, ">&=" . fileno($stdoutw) )
51 or Carp::croak "Cannot dup STDOUT: $!";
52 open( STDIN, "<&=" . fileno($stdinr) )
53 or Carp::croak "Cannot dup STDIN: $!";
54  
55 chdir(File::Basename::dirname($script));
56 exec($script) or Carp::croak("cannot exec: $!");
57  
58 exit(2);
59 }
60  
61 close $stdoutw;
62 close $stdinr;
63  
64 syswrite($stdinw, slurp_fh($env->{'psgi.input'}));
65 # close STDIN so child will stop waiting
66 close $stdinw;
67  
68 my $res = ''; my $waited_pid;
69 while (($waited_pid = waitpid($pid, WNOHANG)) == 0) {
70 $res .= slurp_fh($stdoutr);
71 }
72 $res .= slurp_fh($stdoutr);
73  
74 # -1 means that the child went away, and something else
75 # (probably some global SIGCHLD handler) took care of it;
76 # yes, we just reset $SIG{CHLD} above, but you can never
77 # be too sure
78 if (POSIX::WIFEXITED($?) || $waited_pid == -1) {
79 return CGI::Parse::PSGI::parse_cgi_output(\$res);
80 } else {
81 Carp::croak("Error at run_on_shell CGI: $!");
82 }
83 };
84 $self->_app($app);
85 } else {
86 my $sub = CGI::Compile->compile($script);
87 my $app = CGI::Emulate::PSGI->handler($sub);
88  
89 $self->_app($app);
90 }
91 }
92  
93 sub call {
94 my($self, $env) = @_;
95 $self->_app->($env);
96 }
97  
98 1;
99  
100 __END__