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