7ca93f6b0508b413367f3e94ba48364cad2712b2
[catagits/Catalyst-Controller-WrapCGI.git] / lib / Catalyst / Controller / WrapCGI.pm
1 package Catalyst::Controller::WrapCGI;
2
3 use Moose;
4 use mro 'c3';
5
6 extends 'Catalyst::Controller';
7
8 use HTTP::Request::AsCGI ();
9 use HTTP::Request ();
10 use URI ();
11 use Catalyst::Exception ();
12 use URI::Escape;
13 use HTTP::Request::Common;
14
15 use namespace::clean -except => 'meta';
16
17 =head1 NAME
18
19 Catalyst::Controller::WrapCGI - Run CGIs in Catalyst
20
21 =head1 VERSION
22
23 Version 0.0035
24
25 =cut
26
27 our $VERSION = '0.0035';
28
29 =head1 SYNOPSIS
30
31     package MyApp::Controller::Foo;
32
33     use parent qw/Catalyst::Controller::WrapCGI/;
34     use CGI ();
35
36     sub hello : Path('cgi-bin/hello.cgi') {
37         my ($self, $c) = @_;
38
39         $self->cgi_to_response($c, sub {
40             my $q = CGI->new;
41             print $q->header, $q->start_html('Hello'),
42                 $q->h1('Catalyst Rocks!'),
43                 $q->end_html;
44         });
45     }
46
47 In your .conf, configure which environment variables to pass:
48
49     <Controller::Foo>
50         <CGI>
51             username_field username # used for REMOTE_USER env var
52             pass_env PERL5LIB
53             pass_env PATH
54             pass_env /^MYAPP_/
55             kill_env MYAPP_BAD
56         </CGI>
57     </Controller::Foo>
58
59 =head1 DESCRIPTION
60
61 Allows you to run Perl code in a CGI environment derived from your L<Catalyst>
62 context.
63
64 B<*WARNING*>: do not export L<CGI> functions into a Controller, it will break
65 with L<Catalyst> 5.8 onward.
66
67 If you just want to run CGIs from files, see L<Catalyst::Controller::CGIBin>.
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 $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.
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.
147
148 Used by L</cgi_to_response>, which is probably what you want to use as well.
149
150 =cut
151
152 sub 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;
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,
178               map {
179                 my $header = $_;
180                 map { $header => $_ } $upl->headers->header($header)
181               } $upl->headers->header_field_names
182             ]
183           } keys %uploads
184         ];
185       $body_content = $post->content;
186       $req->content_type($post->header('Content-Type'));
187     } elsif (%$body_params) {
188       my $encoder = URI->new;
189       $encoder->query_form(%$body_params);
190       $body_content = $encoder->query;
191       $req->content_type('application/x-www-form-urlencoded');
192     }
193   }
194
195   my $filtered_env = $self->_filtered_env(\%ENV);
196
197   $req->content($body_content);
198   $req->content_length(length($body_content));
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 }
204                 : '');
205
206   my $path_info = '/'.join '/' => map uri_escape_utf8($_), @{ $c->req->args };
207
208   my $env = HTTP::Request::AsCGI->new(
209               $req,
210               ($username ? (REMOTE_USER => $username) : ()),
211               %$filtered_env,
212               PATH_INFO => $path_info,
213 # eww, this is likely broken:
214               FILEPATH_INFO => '/'.$c->action.$path_info,
215               SCRIPT_NAME => $c->uri_for($c->action)->path
216             );
217
218   {
219     local *STDIN = $REAL_STDIN;   # restore the real ones so the filenos
220     local *STDOUT = $REAL_STDOUT; # are 0 and 1 for the env setup
221
222     my $old = select($REAL_STDOUT); # in case somebody just calls 'print'
223
224     my $saved_error;
225
226     $env->setup;
227     eval { $call->() };
228     $saved_error = $@;
229     $env->restore;
230
231     select($old);
232
233     Catalyst::Exception->throw(
234         message => "CGI invocation failed: $saved_error"
235     ) if $saved_error;
236   }
237
238   return $env->response;
239 }
240
241 =head1 FILTERED ENVIRONMENT
242
243 If you don't use the L</pass_env> option to restrict which environment variables
244 are passed in, the default is to pass the whole of C<%ENV> except the variables
245 listed below.
246
247   MOD_PERL
248   SERVER_SOFTWARE
249   SERVER_NAME
250   GATEWAY_INTERFACE
251   SERVER_PROTOCOL
252   SERVER_PORT
253   REQUEST_METHOD
254   PATH_INFO
255   PATH_TRANSLATED
256   SCRIPT_NAME
257   QUERY_STRING
258   REMOTE_HOST
259   REMOTE_ADDR
260   AUTH_TYPE
261   REMOTE_USER
262   REMOTE_IDENT
263   CONTENT_TYPE
264   CONTENT_LENGTH
265   HTTP_ACCEPT
266   HTTP_USER_AGENT
267
268 C<%ENV> can be further trimmed using L</kill_env>.
269
270 =cut
271
272 my $DEFAULT_KILL_ENV = [qw/
273   MOD_PERL SERVER_SOFTWARE SERVER_NAME GATEWAY_INTERFACE SERVER_PROTOCOL
274   SERVER_PORT REQUEST_METHOD PATH_INFO PATH_TRANSLATED SCRIPT_NAME QUERY_STRING
275   REMOTE_HOST REMOTE_ADDR AUTH_TYPE REMOTE_USER REMOTE_IDENT CONTENT_TYPE
276   CONTENT_LENGTH HTTP_ACCEPT HTTP_USER_AGENT
277 /];
278
279 sub _filtered_env {
280   my ($self, $env) = @_;
281   my @ok;
282
283   my $pass_env = $self->{CGI}{pass_env};
284   $pass_env = []            if not defined $pass_env;
285   $pass_env = [ $pass_env ] unless ref $pass_env;
286
287   my $kill_env = $self->{CGI}{kill_env};
288   $kill_env = $DEFAULT_KILL_ENV unless defined $kill_env;
289   $kill_env = [ $kill_env ]  unless ref $kill_env;
290
291   if (@$pass_env) {
292     for (@$pass_env) {
293       if (m!^/(.*)/\z!) {
294         my $re = qr/$1/;
295         push @ok, grep /$re/, keys %$env;
296       } else {
297         push @ok, $_;
298       }
299     }
300   } else {
301     @ok = keys %$env;
302   }
303
304   for my $k (@$kill_env) {
305     if ($k =~ m!^/(.*)/\z!) {
306       my $re = qr/$1/;
307       @ok = grep { ! /$re/ } @ok;
308     } else {
309       @ok = grep { $_ ne $k } @ok;
310     }
311   }
312   return { map {; $_ => $env->{$_} } @ok };
313 }
314
315 __PACKAGE__->meta->make_immutable;
316
317 =head1 DIRECT SOCKET/NPH SCRIPTS
318
319 This currently won't work:
320
321     #!/usr/bin/perl
322
323     use CGI ':standard';
324
325     $| = 1;
326
327     print header;
328
329     for (0..1000) {
330         print $_, br, "\n";
331     }
332
333 because the coderef is executed synchronously with C<STDOUT> pointing to a temp
334 file.
335
336 =head1 ACKNOWLEDGEMENTS
337
338 Original development sponsored by L<http://www.altinity.com/>
339
340 =head1 SEE ALSO
341
342 L<Catalyst::Controller::CGIBin>, L<CatalystX::GlobalContext>,
343 L<Catalyst::Controller>, L<CGI>, L<Catalyst>
344
345 =head1 AUTHORS
346
347 Originally written by:
348
349 Matt S. Trout, C<< <mst at shadowcat.co.uk> >>
350
351 Contributors:
352
353 Rafael Kitover C<< <rkitover at cpan.org> >>
354
355 Hans Dieter Pearcey C<< <hdp at cpan.org> >>
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 COPYRIGHT & LICENSE
390
391 Copyright (c) 2008 Matt S. Trout
392
393 This program is free software; you can redistribute it and/or modify it
394 under the same terms as Perl itself.
395
396 =cut
397
398 1; # End of Catalyst::Controller::WrapCGI
399
400 # vim: expandtab shiftwidth=2 ts=2 tw=80: