1 package Catalyst::Controller::WrapCGI;
7 extends 'Catalyst::Controller';
9 use HTTP::Request::AsCGI ();
13 use HTTP::Request::Common;
15 use namespace::clean -except => 'meta';
19 Catalyst::Controller::WrapCGI - Run CGIs in Catalyst
23 our $VERSION = '0.029';
27 package MyApp::Controller::Foo;
29 use parent qw/Catalyst::Controller::WrapCGI/;
32 sub hello : Path('cgi-bin/hello.cgi') {
35 $self->cgi_to_response($c, sub {
37 print $q->header, $q->start_html('Hello'),
38 $q->h1('Catalyst Rocks!'),
43 In your .conf, configure which environment variables to pass:
47 username_field username # used for REMOTE_USER env var
57 Allows you to run Perl code in a CGI environment derived from your L<Catalyst>
60 B<*WARNING*>: do not export L<CGI> functions into a Controller, it will break
61 with L<Catalyst> 5.8 onward.
63 If you just want to run CGIs from files, see L<Catalyst::Controller::CGIBin>.
65 C<REMOTE_USER> will be set to C<< $c->user->obj->$username_field >> if
66 available, or to C<< $c->req->remote_user >> otherwise.
72 C<< $your_controller->{CGI}{pass_env} >> should be an array of environment variables
73 or regular expressions to pass through to your CGIs. Entries surrounded by C</>
74 characters are considered regular expressions.
78 C<< $your_controller->{CGI}{kill_env} >> should be an array of environment
79 variables or regular expressions to remove from the environment before passing
80 it to your CGIs. Entries surrounded by C</> characters are considered regular
83 Default is to pass the whole of C<%ENV>, except for entries listed in
84 L</FILTERED ENVIRONMENT> below.
88 C<< $your_controller->{CGI}{username_field} >> should be the field for your
89 user's name, which will be read from C<< $c->user->obj >>. Defaults to
92 See L</SYNOPSIS> for an example.
96 # Hack-around because Catalyst::Engine::HTTP goes and changes
97 # them to be the remote socket, and FCGI.pm does even dumber things.
99 open my $REAL_STDIN, "<&=".fileno(*STDIN);
100 open my $REAL_STDOUT, ">>&=".fileno(*STDOUT);
104 =head2 cgi_to_response
106 C<< $self->cgi_to_response($c, $coderef) >>
108 Does the magic of running $coderef in a CGI environment, and populating the
109 appropriate parts of your Catalyst context with the results.
115 sub cgi_to_response {
116 my ($self, $c, $script) = @_;
118 my $res = $self->wrap_cgi($c, $script);
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
123 my $location = $res->headers->header('Location');
125 if (defined $location && length $location && $res->code == 200) {
126 $c->res->status(302);
128 $c->res->status($res->code);
130 $c->res->body($res->content);
131 $c->res->headers($res->headers);
136 C<< $self->wrap_cgi($c, $coderef) >>
138 Runs C<$coderef> in a CGI environment using L<HTTP::Request::AsCGI>, returns an
141 The CGI environment is set up based on C<$c>.
143 The environment variables to pass on are taken from the configuration for your
144 Controller, see L</SYNOPSIS> for an example. If you don't supply a list of
145 environment variables to pass, the whole of %ENV is used (with exceptions listed
146 in L</FILTERED ENVIRONMENT>.
148 Used by L</cgi_to_response>, which is probably what you want to use as well.
153 my ($self, $c, $call) = @_;
154 my $req = HTTP::Request->new(
155 map { $c->req->$_ } qw/method uri headers/
157 my $body = $c->req->body;
158 my $body_content = '';
160 $req->content_type($c->req->content_type); # set this now so we can override
162 if ($body) { # Slurp from body filehandle
163 local $/; $body_content = <$body>;
165 my $body_params = $c->req->body_parameters;
167 if (my %uploads = %{ $c->req->uploads }) {
168 my $post = POST 'http://localhost/',
169 Content_Type => 'form-data',
173 my $upl = $uploads{$_};
177 Content => $upl->slurp,
180 map { $header => $_ } $upl->headers->header($header)
181 } $upl->headers->header_field_names
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');
195 $req->content($body_content);
196 $req->content_length(length($body_content));
198 my $username_field = $self->{CGI}{username_field} || 'username';
200 my $username = (($c->can('user_exists') && $c->user_exists)
201 ? eval { $c->user->obj->$username_field }
204 $username ||= $c->req->remote_user if $c->req->can('remote_user');
206 my $path_info = '/'.join '/' => map {
207 utf8::is_utf8($_) ? uri_escape_utf8($_) : uri_escape($_)
208 } @{ $c->req->args };
210 my $env = HTTP::Request::AsCGI->new(
212 ($username ? (REMOTE_USER => $username) : ()),
213 PATH_INFO => $path_info,
214 # eww, this is likely broken:
215 FILEPATH_INFO => '/'.$c->action.$path_info,
216 SCRIPT_NAME => $c->uri_for($c->action, $c->req->captures)->path
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
223 my $old = select($REAL_STDOUT); # in case somebody just calls 'print'
227 local %ENV = %{ $self->_filtered_env(\%ENV) };
236 die $saved_error if $saved_error;
239 return $env->response;
242 =head1 FILTERED ENVIRONMENT
244 If you don't use the L</pass_env> option to restrict which environment variables
245 are passed in, the default is to pass the whole of C<%ENV> except the variables
269 C<%ENV> can be further trimmed using L</kill_env>.
273 my $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
281 my ($self, $env) = @_;
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;
288 my $kill_env = $self->{CGI}{kill_env};
289 $kill_env = $DEFAULT_KILL_ENV unless defined $kill_env;
290 $kill_env = [ $kill_env ] unless ref $kill_env;
296 push @ok, grep /$re/, keys %$env;
305 for my $k (@$kill_env) {
306 if ($k =~ m!^/(.*)/\z!) {
308 @ok = grep { ! /$re/ } @ok;
310 @ok = grep { $_ ne $k } @ok;
313 return { map {; $_ => $env->{$_} } @ok };
316 __PACKAGE__->meta->make_immutable;
318 =head1 DIRECT SOCKET/NPH SCRIPTS
320 This currently won't work:
335 because the coderef is executed synchronously with C<STDOUT> pointing to a temp
338 =head1 ACKNOWLEDGEMENTS
340 Original development sponsored by L<http://www.altinity.com/>
344 L<Catalyst::Controller::CGIBin>, L<CatalystX::GlobalContext>,
345 L<Catalyst::Controller>, L<CGI>, L<Catalyst>
349 Please report any bugs or feature requests to C<bug-catalyst-controller-wrapcgi
350 at rt.cpan.org>, or through the web interface at
351 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Catalyst-Controller-WrapCGI>.
352 I will be notified, and then you'll automatically be notified of progress on
353 your bug as I make changes.
361 =item * RT: CPAN's request tracker
363 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Catalyst-Controller-WrapCGI>
365 =item * AnnoCPAN: Annotated CPAN documentation
367 L<http://annocpan.org/dist/Catalyst-Controller-WrapCGI>
371 L<http://cpanratings.perl.org/d/Catalyst-Controller-WrapCGI>
375 L<http://search.cpan.org/dist/Catalyst-Controller-WrapCGI>
381 Matt S. Trout C<< <mst at shadowcat.co.uk> >>
385 Rafael Kitover C<< <rkitover at cpan.org> >>
387 Hans Dieter Pearcey C<< <hdp at cpan.org> >>
389 Some code stolen from Tatsuhiko Miyagawa's L<CGI::Compile>.
391 =head1 COPYRIGHT & LICENSE
393 Copyright (c) 2008-2009 L<Catalyst::Controller::WrapCGI/AUTHOR> and
394 L<Catalyst::Controller::WrapCGI/CONTRIBUTORS>.
396 This program is free software; you can redistribute it and/or modify it
397 under the same terms as Perl itself.
401 1; # End of Catalyst::Controller::WrapCGI
403 # vim: expandtab shiftwidth=2 ts=2 tw=80: