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