switch to CGI::Compile, check exit status of non-Perl CGIs, release
[catagits/Catalyst-Controller-WrapCGI.git] / lib / Catalyst / Controller / WrapCGI.pm
CommitLineData
71e6daf6 1package Catalyst::Controller::WrapCGI;
b2a17df2 2
d5ba2ab2 3use 5.008_001;
9cd47364 4use Moose;
5use mro 'c3';
6
7extends 'Catalyst::Controller';
b2a17df2 8
0d83c5de 9use HTTP::Request::AsCGI ();
10use HTTP::Request ();
11use URI ();
21a20b7e 12use Catalyst::Exception ();
f410f043 13use URI::Escape;
16db0bfc 14use HTTP::Request::Common;
f410f043 15
16use namespace::clean -except => 'meta';
32b32c62 17
18=head1 NAME
19
20Catalyst::Controller::WrapCGI - Run CGIs in Catalyst
21
22=head1 VERSION
23
d9280b8f 24Version 0.026
32b32c62 25
26=cut
27
d9280b8f 28our $VERSION = '0.026';
32b32c62 29
30=head1 SYNOPSIS
31
32 package MyApp::Controller::Foo;
33
34 use parent qw/Catalyst::Controller::WrapCGI/;
12d29ebf 35 use CGI ();
32b32c62 36
37 sub hello : Path('cgi-bin/hello.cgi') {
38 my ($self, $c) = @_;
39
40 $self->cgi_to_response($c, sub {
12d29ebf 41 my $q = CGI->new;
42 print $q->header, $q->start_html('Hello'),
43 $q->h1('Catalyst Rocks!'),
44 $q->end_html;
32b32c62 45 });
46 }
47
457c1d76 48In your .conf, configure which environment variables to pass:
49
50 <Controller::Foo>
51 <CGI>
21a20b7e 52 username_field username # used for REMOTE_USER env var
457c1d76 53 pass_env PERL5LIB
54 pass_env PATH
21a20b7e 55 pass_env /^MYAPP_/
c4ef0be5 56 kill_env MYAPP_BAD
457c1d76 57 </CGI>
58 </Controller::Foo>
59
60=head1 DESCRIPTION
61
62Allows you to run Perl code in a CGI environment derived from your L<Catalyst>
63context.
64
12d29ebf 65B<*WARNING*>: do not export L<CGI> functions into a Controller, it will break
66with L<Catalyst> 5.8 onward.
67
21a20b7e 68If you just want to run CGIs from files, see L<Catalyst::Controller::CGIBin>.
69
b9548267 70C<REMOTE_USER> will be set to C<< $c->user->obj->$username_field >> if
71available, or to C<< $c->req->remote_user >> otherwise.
72
21a20b7e 73=head1 CONFIGURATION
74
16bed4c4 75=head2 pass_env
76
c212b57b 77C<< $your_controller->{CGI}{pass_env} >> should be an array of environment variables
21a20b7e 78or regular expressions to pass through to your CGIs. Entries surrounded by C</>
79characters are considered regular expressions.
80
16bed4c4 81=head2 kill_env
82
c212b57b 83C<< $your_controller->{CGI}{kill_env} >> should be an array of environment
84variables or regular expressions to remove from the environment before passing
85it to your CGIs. Entries surrounded by C</> characters are considered regular
86expressions.
21a20b7e 87
16bed4c4 88Default is to pass the whole of C<%ENV>, except for entries listed in
89L</FILTERED ENVIRONMENT> below.
c212b57b 90
16bed4c4 91=head2 username_field
92
93C<< $your_controller->{CGI}{username_field} >> should be the field for your
94user's name, which will be read from C<< $c->user->obj >>. Defaults to
95'username'.
21a20b7e 96
97See L</SYNOPSIS> for an example.
98
32b32c62 99=cut
b2a17df2 100
101# Hack-around because Catalyst::Engine::HTTP goes and changes
102# them to be the remote socket, and FCGI.pm does even dumber things.
103
32b32c62 104open my $REAL_STDIN, "<&=".fileno(*STDIN);
105open my $REAL_STDOUT, ">>&=".fileno(*STDOUT);
106
107=head1 METHODS
108
f410f043 109=head2 cgi_to_response
110
b9548267 111C<< $self->cgi_to_response($c, $coderef) >>
32b32c62 112
113Does the magic of running $coderef in a CGI environment, and populating the
114appropriate parts of your Catalyst context with the results.
115
f410f043 116Calls L</wrap_cgi>.
457c1d76 117
32b32c62 118=cut
b2a17df2 119
120sub cgi_to_response {
121 my ($self, $c, $script) = @_;
0d83c5de 122
b2a17df2 123 my $res = $self->wrap_cgi($c, $script);
124
125 # if the CGI doesn't set the response code but sets location they were
126 # probably trying to redirect so set 302 for them
127
32b32c62 128 my $location = $res->headers->header('Location');
129
130 if (defined $location && length $location && $res->code == 200) {
b2a17df2 131 $c->res->status(302);
132 } else {
133 $c->res->status($res->code);
134 }
135 $c->res->body($res->content);
136 $c->res->headers($res->headers);
137}
138
f410f043 139=head2 wrap_cgi
140
b9548267 141C<< $self->wrap_cgi($c, $coderef) >>
32b32c62 142
d5ba2ab2 143Runs C<$coderef> in a CGI environment using L<HTTP::Request::AsCGI>, returns an
32b32c62 144L<HTTP::Response>.
145
b9548267 146The CGI environment is set up based on C<$c>.
32b32c62 147
457c1d76 148The environment variables to pass on are taken from the configuration for your
149Controller, see L</SYNOPSIS> for an example. If you don't supply a list of
b9548267 150environment variables to pass, the whole of %ENV is used (with exceptions listed
151in L</FILTERED ENVIRONMENT>.
457c1d76 152
f410f043 153Used by L</cgi_to_response>, which is probably what you want to use as well.
32b32c62 154
155=cut
156
b2a17df2 157sub wrap_cgi {
158 my ($self, $c, $call) = @_;
159 my $req = HTTP::Request->new(
160 map { $c->req->$_ } qw/method uri headers/
161 );
162 my $body = $c->req->body;
163 my $body_content = '';
164
165 $req->content_type($c->req->content_type); # set this now so we can override
166
167 if ($body) { # Slurp from body filehandle
168 local $/; $body_content = <$body>;
169 } else {
170 my $body_params = $c->req->body_parameters;
16db0bfc 171
172 if (my %uploads = %{ $c->req->uploads }) {
173 my $post = POST 'http://localhost/',
174 Content_Type => 'form-data',
175 Content => [
176 %$body_params,
177 map {
178 my $upl = $uploads{$_};
179 $_ => [
180 undef,
181 $upl->filename,
182 Content => $upl->slurp,
01c35d4e 183 map {
184 my $header = $_;
185 map { $header => $_ } $upl->headers->header($header)
186 } $upl->headers->header_field_names
16db0bfc 187 ]
188 } keys %uploads
189 ];
190 $body_content = $post->content;
191 $req->content_type($post->header('Content-Type'));
192 } elsif (%$body_params) {
32b32c62 193 my $encoder = URI->new;
194 $encoder->query_form(%$body_params);
195 $body_content = $encoder->query;
b2a17df2 196 $req->content_type('application/x-www-form-urlencoded');
197 }
198 }
199
c212b57b 200 my $filtered_env = $self->_filtered_env(\%ENV);
457c1d76 201
b2a17df2 202 $req->content($body_content);
203 $req->content_length(length($body_content));
21a20b7e 204
205 my $username_field = $self->{CGI}{username_field} || 'username';
206
207 my $username = (($c->can('user_exists') && $c->user_exists)
208 ? eval { $c->user->obj->$username_field }
b2a17df2 209 : '');
0d83c5de 210
b9548267 211 $username ||= $c->req->remote_user if $c->req->can('remote_user');
212
83bba9ab 213 my $path_info = '/'.join '/' => map {
214 utf8::is_utf8($_) ? uri_escape_utf8($_) : uri_escape($_)
215 } @{ $c->req->args };
0d83c5de 216
b2a17df2 217 my $env = HTTP::Request::AsCGI->new(
218 $req,
21a20b7e 219 ($username ? (REMOTE_USER => $username) : ()),
c212b57b 220 %$filtered_env,
f410f043 221 PATH_INFO => $path_info,
c4ef0be5 222# eww, this is likely broken:
223 FILEPATH_INFO => '/'.$c->action.$path_info,
17a050f8 224 SCRIPT_NAME => $c->uri_for($c->action, $c->req->captures)->path
b2a17df2 225 );
226
227 {
32b32c62 228 local *STDIN = $REAL_STDIN; # restore the real ones so the filenos
229 local *STDOUT = $REAL_STDOUT; # are 0 and 1 for the env setup
b2a17df2 230
32b32c62 231 my $old = select($REAL_STDOUT); # in case somebody just calls 'print'
b2a17df2 232
233 my $saved_error;
234
235 $env->setup;
7a3e5a11 236 eval { $call->() };
b2a17df2 237 $saved_error = $@;
238 $env->restore;
239
240 select($old);
241
21a20b7e 242 Catalyst::Exception->throw(
243 message => "CGI invocation failed: $saved_error"
244 ) if $saved_error;
b2a17df2 245 }
246
247 return $env->response;
248}
249
16bed4c4 250=head1 FILTERED ENVIRONMENT
251
252If you don't use the L</pass_env> option to restrict which environment variables
253are passed in, the default is to pass the whole of C<%ENV> except the variables
254listed below.
255
256 MOD_PERL
257 SERVER_SOFTWARE
258 SERVER_NAME
259 GATEWAY_INTERFACE
260 SERVER_PROTOCOL
261 SERVER_PORT
262 REQUEST_METHOD
263 PATH_INFO
264 PATH_TRANSLATED
265 SCRIPT_NAME
266 QUERY_STRING
267 REMOTE_HOST
268 REMOTE_ADDR
269 AUTH_TYPE
270 REMOTE_USER
271 REMOTE_IDENT
272 CONTENT_TYPE
273 CONTENT_LENGTH
274 HTTP_ACCEPT
275 HTTP_USER_AGENT
276
277C<%ENV> can be further trimmed using L</kill_env>.
278
279=cut
280
281my $DEFAULT_KILL_ENV = [qw/
282 MOD_PERL SERVER_SOFTWARE SERVER_NAME GATEWAY_INTERFACE SERVER_PROTOCOL
283 SERVER_PORT REQUEST_METHOD PATH_INFO PATH_TRANSLATED SCRIPT_NAME QUERY_STRING
284 REMOTE_HOST REMOTE_ADDR AUTH_TYPE REMOTE_USER REMOTE_IDENT CONTENT_TYPE
285 CONTENT_LENGTH HTTP_ACCEPT HTTP_USER_AGENT
286/];
287
0d83c5de 288sub _filtered_env {
289 my ($self, $env) = @_;
290 my @ok;
291
292 my $pass_env = $self->{CGI}{pass_env};
293 $pass_env = [] if not defined $pass_env;
294 $pass_env = [ $pass_env ] unless ref $pass_env;
295
296 my $kill_env = $self->{CGI}{kill_env};
16bed4c4 297 $kill_env = $DEFAULT_KILL_ENV unless defined $kill_env;
0d83c5de 298 $kill_env = [ $kill_env ] unless ref $kill_env;
299
300 if (@$pass_env) {
301 for (@$pass_env) {
302 if (m!^/(.*)/\z!) {
303 my $re = qr/$1/;
304 push @ok, grep /$re/, keys %$env;
305 } else {
306 push @ok, $_;
307 }
308 }
309 } else {
310 @ok = keys %$env;
311 }
312
313 for my $k (@$kill_env) {
314 if ($k =~ m!^/(.*)/\z!) {
315 my $re = qr/$1/;
316 @ok = grep { ! /$re/ } @ok;
317 } else {
318 @ok = grep { $_ ne $k } @ok;
319 }
320 }
321 return { map {; $_ => $env->{$_} } @ok };
322}
323
f410f043 324__PACKAGE__->meta->make_immutable;
0d83c5de 325
c4ef0be5 326=head1 DIRECT SOCKET/NPH SCRIPTS
327
328This currently won't work:
329
330 #!/usr/bin/perl
331
332 use CGI ':standard';
333
334 $| = 1;
335
336 print header;
337
338 for (0..1000) {
339 print $_, br, "\n";
83bba9ab 340 sleep 1;
c4ef0be5 341 }
342
343because the coderef is executed synchronously with C<STDOUT> pointing to a temp
344file.
345
32b32c62 346=head1 ACKNOWLEDGEMENTS
347
348Original development sponsored by L<http://www.altinity.com/>
349
457c1d76 350=head1 SEE ALSO
351
21a20b7e 352L<Catalyst::Controller::CGIBin>, L<CatalystX::GlobalContext>,
457c1d76 353L<Catalyst::Controller>, L<CGI>, L<Catalyst>
354
32b32c62 355=head1 BUGS
356
357Please report any bugs or feature requests to C<bug-catalyst-controller-wrapcgi
358at rt.cpan.org>, or through the web interface at
359L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Catalyst-Controller-WrapCGI>.
360I will be notified, and then you'll automatically be notified of progress on
361your bug as I make changes.
362
363=head1 SUPPORT
364
365More information at:
366
367=over 4
368
369=item * RT: CPAN's request tracker
370
371L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Catalyst-Controller-WrapCGI>
372
373=item * AnnoCPAN: Annotated CPAN documentation
374
375L<http://annocpan.org/dist/Catalyst-Controller-WrapCGI>
376
377=item * CPAN Ratings
378
379L<http://cpanratings.perl.org/d/Catalyst-Controller-WrapCGI>
380
381=item * Search CPAN
382
383L<http://search.cpan.org/dist/Catalyst-Controller-WrapCGI>
384
385=back
386
efa4a434 387=head1 AUTHOR
388
389Matt S. Trout C<< <mst at shadowcat.co.uk> >>
390
391=head1 CONTRIBUTORS
392
393Rafael Kitover C<< <rkitover at cpan.org> >>
394
395Hans Dieter Pearcey C<< <hdp at cpan.org> >>
396
d9280b8f 397Some code stolen from Tatsuhiko Miyagawa's L<CGI::Compile>.
398
32b32c62 399=head1 COPYRIGHT & LICENSE
400
efa4a434 401Copyright (c) 2008-2009 L<Catalyst::Controller::WrapCGI/AUTHOR> and
402L<Catalyst::Controller::WrapCGI/CONTRIBUTORS>.
32b32c62 403
404This program is free software; you can redistribute it and/or modify it
405under the same terms as Perl itself.
406
407=cut
408
4091; # End of Catalyst::Controller::WrapCGI
410
21a20b7e 411# vim: expandtab shiftwidth=2 ts=2 tw=80: