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