blib/lib/Plack/Handler/FCGI.pm untested

filter: Statementstmt 0.0% 0 / 151 Branchbran 0.0% 0 / 62 Conditioncond 0.0% 0 / 53 MC/DCmcdc 0.0% 0 / 31 Subroutinesub 0.0% 0 / 17 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 319 CC 32 SCAR 61.7
CC
32
Cov
0%
run
812.0
new
20.0
_handle_response
6.0
CRAP 476.2
1 package Plack::Handler::FCGI;
2 use strict;
3 use warnings;
4 use constant RUNNING_IN_HELL => $^O eq 'MSWin32';
5  
6 use Scalar::Util qw(blessed);
7 use Plack::Util;
8 use FCGI;
9 use HTTP::Status qw(status_message);
10 use URI;
11 use URI::Escape;
12  
13 sub new {
14 my $class = shift;
15 my $self = bless {@_}, $class;
16  
17 $self->{leave_umask} ||= 0;
18 $self->{keep_stderr} ||= 0;
19 $self->{nointr} ||= 0;
20 $self->{daemonize} ||= $self->{detach}; # compatibility
21 $self->{nproc} ||= 1 unless blessed $self->{manager};
22 $self->{pid} ||= $self->{pidfile}; # compatibility
23 $self->{listen} ||= [ ":$self->{port}" ] if $self->{port}; # compatibility
24 $self->{backlog} ||= 100;
25 $self->{manager} = 'FCGI::ProcManager' unless exists $self->{manager};
26  
27 $self;
28 }
29  
30 sub run {
31 my ($self, $app) = @_;
32  
33 my $running_on_server_starter = exists $ENV{SERVER_STARTER_PORT};
34 my $sock = 0;
35 if (-S STDIN) {
36 # running from web server. Do nothing
37 # Note it should come before listen check because of plackup's default
38 } elsif ($running_on_server_starter) {
39 # Runing under Server::Starter
40 require Server::Starter;
41 my %socks = %{Server::Starter::server_ports()};
42 if (scalar(keys(%socks)) > 1) {
43 die "More than one socket are specified by Server::Starter";
44 }
45 $sock = (values %socks)[0];
46 } elsif ($self->{listen}) {
47 my $old_umask = umask;
48 unless ($self->{leave_umask}) {
49 umask(0);
50 }
51 $sock = FCGI::OpenSocket( $self->{listen}->[0], $self->{backlog} )
52 or die "failed to open FastCGI socket: $!";
53 unless ($self->{leave_umask}) {
54 umask($old_umask);
55 }
56 } elsif (!RUNNING_IN_HELL) {
57 die "STDIN is not a socket: specify a listen location";
58 }
59  
60 @{$self}{qw(stdin stdout stderr)}
61 = (IO::Handle->new, IO::Handle->new, IO::Handle->new);
62  
63 my %env;
64 my $request = FCGI::Request(
65 $self->{stdin}, $self->{stdout}, $self->{stderr},
66 \%env, $sock,
67 ($self->{nointr} ? 0 : &FCGI::FAIL_ACCEPT_ON_INTR),
68 );
69  
70 my $proc_manager;
71  
72 if ($self->{listen} or $running_on_server_starter) {
73 $self->daemon_fork if $self->{daemonize};
74  
75 if ($self->{manager}) {
76 if (blessed $self->{manager}) {
77 for (qw(nproc pid proc_title)) {
78 die "Don't use '$_' when passing in a 'manager' object"
79 if $self->{$_};
80 }
81 $proc_manager = $self->{manager};
82 } else {
83 Plack::Util::load_class($self->{manager});
84 $proc_manager = $self->{manager}->new({
85 n_processes => $self->{nproc},
86 pid_fname => $self->{pid},
87 (exists $self->{proc_title}
88 ? (pm_title => $self->{proc_title}) : ()),
89 });
90 }
91  
92 # detach *before* the ProcManager inits
93 $self->daemon_detach if $self->{daemonize};
94 }
95 elsif ($self->{daemonize}) {
96 $self->daemon_detach;
97 }
98 } elsif (blessed $self->{manager}) {
99 $proc_manager = $self->{manager};
100 }
101  
102 $proc_manager && $proc_manager->pm_manage;
103  
104 while ($request->Accept >= 0) {
105 $proc_manager && $proc_manager->pm_pre_dispatch;
106  
107 my $env = {
108 %env,
109 'psgi.version' => [1,1],
110 'psgi.url_scheme' => ($env{HTTPS}||'off') =~ /^(?:on|1)$/i ? 'https' : 'http',
111 'psgi.input' => $self->{stdin},
112 'psgi.errors' =>
113 ($self->{keep_stderr} ? \*STDERR : $self->{stderr}),
114 'psgi.multithread' => Plack::Util::FALSE,
115 'psgi.multiprocess' => defined $proc_manager,
116 'psgi.run_once' => Plack::Util::FALSE,
117 'psgi.streaming' => Plack::Util::TRUE,
118 'psgi.nonblocking' => Plack::Util::FALSE,
119 'psgix.harakiri' => defined $proc_manager,
120 'psgix.cleanup' => 1,
121 'psgix.cleanup.handlers' => [],
122 };
123  
124 delete $env->{HTTP_CONTENT_TYPE};
125 delete $env->{HTTP_CONTENT_LENGTH};
126  
127 # lighttpd munges multiple slashes in PATH_INFO into one. Try recovering it
128 my $uri = URI->new("http://localhost" . $env->{REQUEST_URI});
129 $env->{PATH_INFO} = uri_unescape($uri->path);
130 $env->{PATH_INFO} =~ s/^\Q$env->{SCRIPT_NAME}\E//;
131  
132 # root access for mod_fastcgi
133 if (!exists $env->{PATH_INFO}) {
134 $env->{PATH_INFO} = '';
135 }
136  
137 # typical fastcgi_param from nginx might get empty values
138 for my $key (qw(CONTENT_TYPE CONTENT_LENGTH)) {
139 no warnings;
140 delete $env->{$key} if exists $env->{$key} && $env->{$key} eq '';
141 }
142  
143 if (defined(my $HTTP_AUTHORIZATION = $env->{Authorization})) {
144 $env->{HTTP_AUTHORIZATION} = $HTTP_AUTHORIZATION;
145 }
146  
147 my $res = Plack::Util::run_app $app, $env;
148  
149 if (ref $res eq 'ARRAY') {
150 $self->_handle_response($res);
151 }
152 elsif (ref $res eq 'CODE') {
153 $res->(sub {
154 $self->_handle_response($_[0]);
155 });
156 }
157 else {
158 die "Bad response $res";
159 }
160  
161 # give pm_post_dispatch the chance to do things after the client thinks
162 # the request is done
163 $request->Finish;
164  
165 $proc_manager && $proc_manager->pm_post_dispatch();
166  
167 # When the fcgi-manager exits it sends a TERM signal to the workers.
168 # However, if we're busy processing the cleanup handlers, testing
169 # shows that the worker doesn't actually exit in that case.
170 # Trapping the TERM signal and finshing up fixes that.
171 my $exit_due_to_signal = 0;
172 if ( @{ $env->{'psgix.cleanup.handlers'} || [] } ) {
173 local $SIG{TERM} = sub { $exit_due_to_signal = 1 };
174 for my $handler ( @{ $env->{'psgix.cleanup.handlers'} } ) {
175 $handler->($env);
176 }
177 }
178  
179 if ($proc_manager && $env->{'psgix.harakiri.commit'}) {
180 $proc_manager->pm_exit("safe exit with harakiri");
181 }
182 elsif ($exit_due_to_signal) {
183 $proc_manager && $proc_manager->pm_exit("safe exit due to signal");
184 exit; # want to exit, even without a $proc_manager
185 }
186 }
187 }
188  
189 sub _handle_response {
190 my ($self, $res) = @_;
191  
192 $self->{stdout}->autoflush(1);
193 binmode $self->{stdout};
194  
195 my $hdrs;
196 my $message = status_message($res->[0]);
197 $hdrs = "Status: $res->[0] $message\015\012";
198  
199 my $headers = $res->[1];
200 while (my ($k, $v) = splice @$headers, 0, 2) {
201 $hdrs .= "$k: $v\015\012";
202 }
203 $hdrs .= "\015\012";
204  
205 print { $self->{stdout} } $hdrs;
206  
207 my $cb = sub { print { $self->{stdout} } $_[0] };
208 my $body = $res->[2];
209 if (defined $body) {
210 Plack::Util::foreach($body, $cb);
211 }
212 else {
213 return Plack::Util::inline_object
214 write => $cb,
215 close => sub { };
216 }
217 }
218  
219 sub daemon_fork {
220 require POSIX;
221 fork && exit;
222 }
223  
224 sub daemon_detach {
225 my $self = shift;
226 print "FastCGI daemon started (pid $$)\n";
227 open STDIN, "+</dev/null" or die $!; ## no critic
228 open STDOUT, ">&STDIN" or die $!;
229 open STDERR, ">&STDIN" or die $!;
230 POSIX::setsid();
231 }
232  
233 1;
234  
235 __END__