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