C::C::WrapCGI - remove CGI env vars by default
[catagits/Catalyst-Controller-WrapCGI.git] / lib / Catalyst / Controller / WrapCGI.pm
CommitLineData
71e6daf6 1package Catalyst::Controller::WrapCGI;
b2a17df2 2
9cd47364 3use Moose;
4use mro 'c3';
5
6extends 'Catalyst::Controller';
b2a17df2 7
0d83c5de 8use HTTP::Request::AsCGI ();
9use HTTP::Request ();
10use URI ();
21a20b7e 11use Catalyst::Exception ();
f410f043 12use URI::Escape;
16db0bfc 13use HTTP::Request::Common;
f410f043 14
15use namespace::clean -except => 'meta';
32b32c62 16
17=head1 NAME
18
19Catalyst::Controller::WrapCGI - Run CGIs in Catalyst
20
21=head1 VERSION
22
16bed4c4 23Version 0.0034
32b32c62 24
25=cut
26
16bed4c4 27our $VERSION = '0.0034';
32b32c62 28
29=head1 SYNOPSIS
30
31 package MyApp::Controller::Foo;
32
33 use parent qw/Catalyst::Controller::WrapCGI/;
12d29ebf 34 use CGI ();
32b32c62 35
36 sub hello : Path('cgi-bin/hello.cgi') {
37 my ($self, $c) = @_;
38
39 $self->cgi_to_response($c, sub {
12d29ebf 40 my $q = CGI->new;
41 print $q->header, $q->start_html('Hello'),
42 $q->h1('Catalyst Rocks!'),
43 $q->end_html;
32b32c62 44 });
45 }
46
457c1d76 47In your .conf, configure which environment variables to pass:
48
49 <Controller::Foo>
50 <CGI>
21a20b7e 51 username_field username # used for REMOTE_USER env var
457c1d76 52 pass_env PERL5LIB
53 pass_env PATH
21a20b7e 54 pass_env /^MYAPP_/
c212b57b 55 kill_env MOD_PERL
457c1d76 56 </CGI>
57 </Controller::Foo>
58
59=head1 DESCRIPTION
60
61Allows you to run Perl code in a CGI environment derived from your L<Catalyst>
62context.
63
12d29ebf 64B<*WARNING*>: do not export L<CGI> functions into a Controller, it will break
65with L<Catalyst> 5.8 onward.
66
21a20b7e 67If you just want to run CGIs from files, see L<Catalyst::Controller::CGIBin>.
68
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
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
137C<<$self->wrap_cgi($c, $coderef)>>
32b32c62 138
139Runs $coderef in a CGI environment using L<HTTP::Request::AsCGI>, returns an
140L<HTTP::Response>.
141
142The CGI environment is set up based on $c.
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
146environment variables to pass, the whole of %ENV is used.
147
f410f043 148Used by L</cgi_to_response>, which is probably what you want to use as well.
32b32c62 149
150=cut
151
b2a17df2 152sub wrap_cgi {
153 my ($self, $c, $call) = @_;
154 my $req = HTTP::Request->new(
155 map { $c->req->$_ } qw/method uri headers/
156 );
157 my $body = $c->req->body;
158 my $body_content = '';
159
160 $req->content_type($c->req->content_type); # set this now so we can override
161
162 if ($body) { # Slurp from body filehandle
163 local $/; $body_content = <$body>;
164 } else {
165 my $body_params = $c->req->body_parameters;
16db0bfc 166
167 if (my %uploads = %{ $c->req->uploads }) {
168 my $post = POST 'http://localhost/',
169 Content_Type => 'form-data',
170 Content => [
171 %$body_params,
172 map {
173 my $upl = $uploads{$_};
174 $_ => [
175 undef,
176 $upl->filename,
177 Content => $upl->slurp,
01c35d4e 178 map {
179 my $header = $_;
180 map { $header => $_ } $upl->headers->header($header)
181 } $upl->headers->header_field_names
16db0bfc 182 ]
183 } keys %uploads
184 ];
185 $body_content = $post->content;
186 $req->content_type($post->header('Content-Type'));
187 } elsif (%$body_params) {
32b32c62 188 my $encoder = URI->new;
189 $encoder->query_form(%$body_params);
190 $body_content = $encoder->query;
b2a17df2 191 $req->content_type('application/x-www-form-urlencoded');
192 }
193 }
194
c212b57b 195 my $filtered_env = $self->_filtered_env(\%ENV);
457c1d76 196
b2a17df2 197 $req->content($body_content);
198 $req->content_length(length($body_content));
21a20b7e 199
200 my $username_field = $self->{CGI}{username_field} || 'username';
201
202 my $username = (($c->can('user_exists') && $c->user_exists)
203 ? eval { $c->user->obj->$username_field }
b2a17df2 204 : '');
0d83c5de 205
f410f043 206 my $path_info = '/'.join '/' => map uri_escape_utf8($_), @{ $c->req->args };
0d83c5de 207
b2a17df2 208 my $env = HTTP::Request::AsCGI->new(
209 $req,
21a20b7e 210 ($username ? (REMOTE_USER => $username) : ()),
c212b57b 211 %$filtered_env,
f410f043 212 PATH_INFO => $path_info,
213 FILEPATH_INFO => '/'.$c->action.$path_info, # eww
214 SCRIPT_NAME => $c->uri_for($c->action)->path
b2a17df2 215 );
216
217 {
32b32c62 218 local *STDIN = $REAL_STDIN; # restore the real ones so the filenos
219 local *STDOUT = $REAL_STDOUT; # are 0 and 1 for the env setup
b2a17df2 220
32b32c62 221 my $old = select($REAL_STDOUT); # in case somebody just calls 'print'
b2a17df2 222
223 my $saved_error;
224
225 $env->setup;
226 eval { $call->() };
227 $saved_error = $@;
228 $env->restore;
229
230 select($old);
231
21a20b7e 232 Catalyst::Exception->throw(
233 message => "CGI invocation failed: $saved_error"
234 ) if $saved_error;
b2a17df2 235 }
236
237 return $env->response;
238}
239
16bed4c4 240=head1 FILTERED ENVIRONMENT
241
242If you don't use the L</pass_env> option to restrict which environment variables
243are passed in, the default is to pass the whole of C<%ENV> except the variables
244listed below.
245
246 MOD_PERL
247 SERVER_SOFTWARE
248 SERVER_NAME
249 GATEWAY_INTERFACE
250 SERVER_PROTOCOL
251 SERVER_PORT
252 REQUEST_METHOD
253 PATH_INFO
254 PATH_TRANSLATED
255 SCRIPT_NAME
256 QUERY_STRING
257 REMOTE_HOST
258 REMOTE_ADDR
259 AUTH_TYPE
260 REMOTE_USER
261 REMOTE_IDENT
262 CONTENT_TYPE
263 CONTENT_LENGTH
264 HTTP_ACCEPT
265 HTTP_USER_AGENT
266
267C<%ENV> can be further trimmed using L</kill_env>.
268
269=cut
270
271my $DEFAULT_KILL_ENV = [qw/
272 MOD_PERL SERVER_SOFTWARE SERVER_NAME GATEWAY_INTERFACE SERVER_PROTOCOL
273 SERVER_PORT REQUEST_METHOD PATH_INFO PATH_TRANSLATED SCRIPT_NAME QUERY_STRING
274 REMOTE_HOST REMOTE_ADDR AUTH_TYPE REMOTE_USER REMOTE_IDENT CONTENT_TYPE
275 CONTENT_LENGTH HTTP_ACCEPT HTTP_USER_AGENT
276/];
277
0d83c5de 278sub _filtered_env {
279 my ($self, $env) = @_;
280 my @ok;
281
282 my $pass_env = $self->{CGI}{pass_env};
283 $pass_env = [] if not defined $pass_env;
284 $pass_env = [ $pass_env ] unless ref $pass_env;
285
286 my $kill_env = $self->{CGI}{kill_env};
16bed4c4 287 $kill_env = $DEFAULT_KILL_ENV unless defined $kill_env;
0d83c5de 288 $kill_env = [ $kill_env ] unless ref $kill_env;
289
290 if (@$pass_env) {
291 for (@$pass_env) {
292 if (m!^/(.*)/\z!) {
293 my $re = qr/$1/;
294 push @ok, grep /$re/, keys %$env;
295 } else {
296 push @ok, $_;
297 }
298 }
299 } else {
300 @ok = keys %$env;
301 }
302
303 for my $k (@$kill_env) {
304 if ($k =~ m!^/(.*)/\z!) {
305 my $re = qr/$1/;
306 @ok = grep { ! /$re/ } @ok;
307 } else {
308 @ok = grep { $_ ne $k } @ok;
309 }
310 }
311 return { map {; $_ => $env->{$_} } @ok };
312}
313
f410f043 314__PACKAGE__->meta->make_immutable;
0d83c5de 315
32b32c62 316=head1 ACKNOWLEDGEMENTS
317
318Original development sponsored by L<http://www.altinity.com/>
319
457c1d76 320=head1 SEE ALSO
321
21a20b7e 322L<Catalyst::Controller::CGIBin>, L<CatalystX::GlobalContext>,
457c1d76 323L<Catalyst::Controller>, L<CGI>, L<Catalyst>
324
0d83c5de 325=head1 AUTHORS
326
327Originally written by:
32b32c62 328
329Matt S. Trout, C<< <mst at shadowcat.co.uk> >>
330
0d83c5de 331Contributors:
332
333Rafael Kitover C<< <rkitover at cpan.org> >>
334
335Hans Dieter Pearcey C<< <hdp at cpan.org> >>
336
32b32c62 337=head1 BUGS
338
339Please report any bugs or feature requests to C<bug-catalyst-controller-wrapcgi
340at rt.cpan.org>, or through the web interface at
341L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Catalyst-Controller-WrapCGI>.
342I will be notified, and then you'll automatically be notified of progress on
343your bug as I make changes.
344
345=head1 SUPPORT
346
347More information at:
348
349=over 4
350
351=item * RT: CPAN's request tracker
352
353L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Catalyst-Controller-WrapCGI>
354
355=item * AnnoCPAN: Annotated CPAN documentation
356
357L<http://annocpan.org/dist/Catalyst-Controller-WrapCGI>
358
359=item * CPAN Ratings
360
361L<http://cpanratings.perl.org/d/Catalyst-Controller-WrapCGI>
362
363=item * Search CPAN
364
365L<http://search.cpan.org/dist/Catalyst-Controller-WrapCGI>
366
367=back
368
369=head1 COPYRIGHT & LICENSE
370
371Copyright (c) 2008 Matt S. Trout
372
373This program is free software; you can redistribute it and/or modify it
374under the same terms as Perl itself.
375
376=cut
377
3781; # End of Catalyst::Controller::WrapCGI
379
21a20b7e 380# vim: expandtab shiftwidth=2 ts=2 tw=80: