fix fail with HTTP::Request::AsCGI 1.2 and Perl < 5.8.9, release
[catagits/Catalyst-Controller-WrapCGI.git] / lib / Catalyst / Controller / CGIBin.pm
1 package Catalyst::Controller::CGIBin;
2
3 use Moose;
4 use mro 'c3';
5
6 extends 'Catalyst::Controller::WrapCGI';
7
8 use File::Find::Rule ();
9 use Catalyst::Exception ();
10 use File::Spec::Functions qw/splitdir abs2rel/;
11 use IPC::Open3;
12 use Symbol 'gensym';
13 use List::MoreUtils 'any';
14 use IO::File ();
15 use File::Temp 'tempfile';
16 use File::pushd;
17 use CGI::Compile;
18  
19 use namespace::clean -except => 'meta';
20
21 =head1 NAME
22
23 Catalyst::Controller::CGIBin - Serve CGIs from root/cgi-bin
24
25 =head1 VERSION
26
27 Version 0.027
28
29 =cut
30
31 our $VERSION = '0.027';
32
33 =head1 SYNOPSIS
34
35 In your controller:
36
37     package MyApp::Controller::Foo;
38
39     use parent qw/Catalyst::Controller::CGIBin/;
40
41 In your .conf:
42
43     <Controller::Foo>
44         cgi_root_path cgi-bin
45         cgi_dir       cgi-bin
46         <CGI>
47             username_field username # used for REMOTE_USER env var
48             pass_env PERL5LIB
49             pass_env PATH
50             pass_env /^MYAPP_/
51         </CGI>
52     </Controller::Foo>
53
54 =head1 DESCRIPTION
55
56 Dispatches to CGI files in root/cgi-bin for /cgi-bin/ paths.
57
58 Unlike L<ModPerl::Registry> this module does _NOT_ stat and recompile the CGI
59 for every invocation. This may be supported in the future if there's interest.
60
61 CGI paths are converted into action names using L</cgi_action>.
62
63 Inherits from L<Catalyst::Controller::WrapCGI>, see the documentation for that
64 module for other configuration information.
65
66 =head1 CONFIG PARAMS
67
68 =head2 cgi_root_path
69
70 The global URI path prefix for CGIs, defaults to C<cgi-bin>.
71
72 =head2 cgi_dir
73
74 Path from which to read CGI files. Can be relative to C<$MYAPP_HOME/root> or
75 absolute.  Defaults to C<$MYAPP_HOME/root/cgi-bin>.
76
77 =cut
78
79 has cgi_root_path => (is => 'ro', isa => 'Str', default => 'cgi-bin');
80 has cgi_dir       => (is => 'ro', isa => 'Str', default => 'cgi-bin');
81
82 sub register_actions {
83     my ($self, $app) = @_;
84
85     my $cgi_bin = File::Spec->file_name_is_absolute($self->cgi_dir) ?
86         $self->cgi_dir
87         : $app->path_to('root', $self->cgi_dir);
88
89     my $namespace = $self->action_namespace($app);
90
91     my $class = ref $self || $self;
92
93     for my $file (File::Find::Rule->file->in($cgi_bin)) {
94         my $cgi_path = abs2rel($file, $cgi_bin);
95
96         next if any { $_ eq '.svn' } splitdir $cgi_path;
97         next if $cgi_path =~ /\.swp\z/;
98
99         my $path        = join '/' => splitdir($cgi_path);
100         my $action_name = $self->cgi_action($path);
101         my $public_path = $self->cgi_path($path);
102         my $reverse     = $namespace ? "$namespace/$action_name" : $action_name;
103         my $attrs       = { Path => [ $public_path ] };
104
105         my ($cgi, $type);
106
107         if ($self->is_perl_cgi($file)) { # syntax check passed
108             $type = 'Perl';
109             $cgi  = $self->wrap_perl_cgi($file, $action_name);
110         } else {
111             $type = 'Non-Perl';
112             $cgi  = $self->wrap_nonperl_cgi($file, $action_name);
113         }
114
115         $app->log->info("Registering root/cgi-bin/$cgi_path as a $type CGI.")
116             if $app->debug;
117
118         my $code = sub {
119             my ($controller, $context) = @_;
120             $controller->cgi_to_response($context, $cgi)
121         };
122
123         my $action = $self->create_action(
124             name       => $action_name,
125             code       => $code,
126             reverse    => $reverse,
127             namespace  => $namespace,
128             class      => $class,
129             attributes => $attrs
130         );
131
132         $app->dispatcher->register($app, $action);
133     }
134
135     $self->next::method($app, @_);
136
137 # Tell Static::Simple to ignore cgi_dir
138     if ($cgi_bin =~ /^@{[ $app->path_to('root') ]}/) {
139         my $rel = File::Spec->abs2rel($cgi_bin, $app->path_to('root'));
140
141         if (!any { $_ eq $rel }
142                 @{ $app->config->{static}{ignore_dirs}||[] }) {
143             push @{ $app->config->{static}{ignore_dirs} }, $rel;
144         }
145     }
146 }
147
148 =head1 METHODS
149
150 =head2 cgi_action
151
152 C<< $self->cgi_action($cgi) >>
153
154 Takes a path to a CGI from C<root/cgi-bin> such as C<foo/bar.cgi> and returns
155 the action name it is registered as.
156
157 =cut
158
159 sub cgi_action {
160     my ($self, $cgi) = @_;
161
162     my $action_name = 'CGI_' . $cgi;
163     $action_name =~ s/([^A-Za-z0-9_])/sprintf("_%2x", unpack("C", $1))/eg;
164
165     return $action_name;
166 }
167
168 =head2 cgi_path
169
170 C<< $self->cgi_path($cgi) >>
171
172 Takes a path to a CGI from C<root/cgi-bin> such as C<foo/bar.cgi> and returns
173 the public path it should be registered under.
174
175 The default is to prefix with C<$cgi_root_path/>, using the C<cgi_root_path>
176 config setting, above.
177
178 =cut
179
180 sub cgi_path {
181     my ($self, $cgi) = @_;
182
183     my $root = $self->cgi_root_path;
184     $root =~ s{/*$}{};
185     return "$root/$cgi";
186 }
187
188 =head2 is_perl_cgi
189
190 C<< $self->is_perl_cgi($path) >>
191
192 Tries to figure out whether the CGI is Perl or not.
193
194 If it's Perl, it will be inlined into a sub instead of being forked off, see
195 L</wrap_perl_cgi>.
196
197 =cut
198
199 sub is_perl_cgi {
200     my ($self, $cgi) = @_;
201
202     my (undef, $tempfile) = tempfile;
203
204     my $pid = fork;
205     die "Cannot fork: $!" unless defined $pid;
206
207     if ($pid) {
208         waitpid $pid, 0;
209         my $errors = IO::File->new($tempfile)->getline;
210         unlink $tempfile;
211         return $errors ? 0 : 1;
212     }
213
214     # child
215     local *NULL;
216     open NULL, '>', File::Spec->devnull;
217     open STDOUT, '>&', \*NULL;
218     open STDERR, '>&', \*NULL;
219     close STDIN;
220
221     eval { $self->wrap_perl_cgi($cgi, '__DUMMY__') };
222
223     IO::File->new(">$tempfile")->print($@);
224
225     exit;
226 }
227
228 =head2 wrap_perl_cgi
229
230 C<< $self->wrap_perl_cgi($path, $action_name) >>
231
232 Takes the path to a Perl CGI and returns a coderef suitable for passing to
233 cgi_to_response (from L<Catalyst::Controller::WrapCGI>) using L<CGI::Compile>.
234
235 C<$action_name> is the generated name for the action representing the CGI file
236 from C<cgi_action>.
237
238 This is similar to how L<ModPerl::Registry> works, but will only work for
239 well-written CGIs. Otherwise, you may have to override this method to do
240 something more involved (see L<ModPerl::PerlRun>.)
241
242 Scripts with C<__DATA__> sections now work too, as well as scripts that call
243 C<exit()>.
244
245 =cut
246
247 sub wrap_perl_cgi {
248     my ($self, $cgi, $action_name) = @_;
249
250     return CGI::Compile->compile($cgi,
251         "Catalyst::Controller::CGIBin::_CGIs_::$action_name");
252 }
253
254 =head2 wrap_nonperl_cgi
255
256 C<< $self->wrap_nonperl_cgi($path, $action_name) >>
257
258 Takes the path to a non-Perl CGI and returns a coderef for executing it.
259
260 C<$action_name> is the generated name for the action representing the CGI file.
261
262 By default returns something like:
263
264     sub { system $path }
265
266 =cut
267
268 sub wrap_nonperl_cgi {
269     my ($self, $cgi, $action_name) = @_;
270
271     return sub {
272         system $cgi;
273
274         if ($? == -1) {
275             die "failed to execute CGI '$cgi': $!";
276         }
277         elsif ($? & 127) {
278             die sprintf "CGI '$cgi' died with signal %d, %s coredump",
279                 ($? & 127),  ($? & 128) ? 'with' : 'without';
280         }
281         else {
282             my $exit_code = $? >> 8;
283
284             return 0 if $exit_code == 0;
285
286             die "CGI '$cgi' exited non-zero with: $exit_code";
287         }
288     };
289 }
290
291 __PACKAGE__->meta->make_immutable;
292
293 =head1 SEE ALSO
294
295 L<Catalyst::Controller::WrapCGI>, L<CatalystX::GlobalContext>,
296 L<Catalyst::Controller>, L<CGI>, L<CGI::Compile>, L<Catalyst>
297
298 =head1 BUGS
299
300 Please report any bugs or feature requests to C<bug-catalyst-controller-wrapcgi at
301 rt.cpan.org>, or through the web interface at
302 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Catalyst-Controller-WrapCGI>.
303 I will be notified, and then you'll automatically be notified of progress on
304 your bug as I make changes.
305
306 =head1 SUPPORT
307
308 More information at:
309
310 =over 4
311
312 =item * RT: CPAN's request tracker
313
314 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Catalyst-Controller-WrapCGI>
315
316 =item * AnnoCPAN: Annotated CPAN documentation
317
318 L<http://annocpan.org/dist/Catalyst-Controller-WrapCGI>
319
320 =item * CPAN Ratings
321
322 L<http://cpanratings.perl.org/d/Catalyst-Controller-WrapCGI>
323
324 =item * Search CPAN
325
326 L<http://search.cpan.org/dist/Catalyst-Controller-WrapCGI>
327
328 =back
329
330 =head1 AUTHOR
331
332 See L<Catalyst::Controller::WrapCGI/AUTHOR> and
333 L<Catalyst::Controller::WrapCGI/CONTRIBUTORS>.
334
335 =head1 COPYRIGHT & LICENSE
336
337 Copyright (c) 2008-2009 L<Catalyst::Controller::WrapCGI/AUTHOR> and
338 L<Catalyst::Controller::WrapCGI/CONTRIBUTORS>.
339
340 This program is free software; you can redistribute it and/or modify it
341 under the same terms as Perl itself.
342
343 =cut
344
345 1; # End of Catalyst::Controller::CGIBin
346
347 # vim: expandtab shiftwidth=4 ts=4 tw=80: