d1760a711481553386be1f42be8ded5fab95754e
[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::Slurp 'slurp';
9 use File::Find::Rule ();
10 use Catalyst::Exception ();
11 use File::Spec::Functions qw/splitdir abs2rel/;
12 use IPC::Open3;
13 use Symbol 'gensym';
14 use List::MoreUtils 'any';
15 use IO::File ();
16 use Carp;
17 use File::Temp 'tempfile';
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.022
28
29 =cut
30
31 our $VERSION = '0.022';
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. See L</DESCRIPTION> for a discussion on how
156 CGI actions are named.
157
158 A path such as C<root/cgi-bin/hlagh/bar.cgi> will get the private path
159 C<foo/CGI_hlagh__bar_cgi>, for controller Foo, with the C</>s converted to C<__>
160 and prepended with C<CGI_>, as well as all non-word characters converted to
161 C<_>s. This is because L<Catalyst> action names can't have non-word characters
162 in them.
163
164 This means that C<foo/bar.cgi> and C<foo__bar.cgi> for example will both map to
165 the action C<CGI_foo__bar_cgi> so B<DON'T DO THAT>.
166
167 =cut
168
169 sub cgi_action {
170     my ($self, $cgi) = @_;
171
172     my $action_name = 'CGI_' . join '__' => split '/' => $cgi;
173     $action_name    =~ s/\W/_/g;
174
175     $action_name
176 }
177
178 =head2 cgi_path
179
180 C<< $self->cgi_path($cgi) >>
181
182 Takes a path to a CGI from C<root/cgi-bin> such as C<foo/bar.cgi> and returns
183 the public path it should be registered under.
184
185 The default is to prefix with C<$cgi_root_path/>, using the C<cgi_root_path>
186 config setting, above.
187
188 =cut
189
190 sub cgi_path {
191     my ($self, $cgi) = @_;
192
193     my $root = $self->cgi_root_path;
194     $root =~ s{/*$}{};
195     return "$root/$cgi";
196 }
197
198 =head2 is_perl_cgi
199
200 C<< $self->is_perl_cgi($path) >>
201
202 Tries to figure out whether the CGI is Perl or not.
203
204 If it's Perl, it will be inlined into a sub instead of being forked off, see
205 L</wrap_perl_cgi>.
206
207 =cut
208
209 sub is_perl_cgi {
210     my ($self, $cgi) = @_;
211
212     my (undef, $tempfile) = tempfile;
213
214     my $pid = fork;
215     die "Cannot fork: $!" unless defined $pid;
216
217     if ($pid) {
218         waitpid $pid, 0;
219         my $errors = IO::File->new($tempfile)->getline;
220         unlink $tempfile;
221         return $errors ? 0 : 1;
222     }
223
224     # child
225     local *NULL;
226     open NULL, '>', File::Spec->devnull;
227     open STDOUT, '>&', \*NULL;
228     open STDERR, '>&', \*NULL;
229     close STDIN;
230
231     eval { $self->wrap_perl_cgi($cgi, '__DUMMY__') };
232
233     IO::File->new(">$tempfile")->print($@);
234
235     exit;
236 }
237
238 =head2 wrap_perl_cgi
239
240 C<< $self->wrap_perl_cgi($path, $action_name) >>
241
242 Takes the path to a Perl CGI and returns a coderef suitable for passing to
243 cgi_to_response (from L<Catalyst::Controller::WrapCGI>.)
244
245 C<$action_name> is the generated name for the action representing the CGI file
246 from C<cgi_action>.
247
248 This is similar to how L<ModPerl::Registry> works, but will only work for
249 well-written CGIs. Otherwise, you may have to override this method to do
250 something more involved (see L<ModPerl::PerlRun>.)
251
252 Scripts with C<__DATA__> sections now work too, as well as scripts that call
253 C<exit()>.
254
255 =cut
256
257 sub wrap_perl_cgi {
258     my ($self, $cgi, $action_name) = @_;
259
260     my $code = slurp $cgi;
261
262     $code =~ s/^__DATA__\n(.*)//ms;
263     my $data = $1;
264
265     my $orig_exit = \*CORE::GLOBAL::exit;
266     my $orig_die  = $SIG{__DIE__};
267     my $orig_warn = $SIG{__WARN__};
268
269     my $coderef = do {
270         no warnings;
271         # catch exit() and turn it into (effectively) a return
272         # we *must* eval STRING because the code needs to be compiled with the
273         # overridden CORE::GLOBAL::exit in view
274         #
275         # set $0 to the name of the cgi file in case it's used there
276         my $source = ' 
277             my $cgi_exited = "EXIT\n";
278             BEGIN { *CORE::GLOBAL::exit = sub (;$) {
279                 die [ $cgi_exited, $_[0] || 0 ];
280             } }
281             package Catalyst::Controller::CGIBin::_CGIs_::'.$action_name.';
282             sub {'."\n"
283                 . 'local *DATA;'."\n"
284                 . q{open DATA, '<', \$data;}."\n"
285                 . qq{local \$0 = "\Q$cgi\E";}."\n"
286                 . q/my $rv = eval {/."\n"
287                 . 'local $SIG{__DIE__}  = $SIG{__DIE__}  || sub { die @_ };'."\n"
288                 . 'local $SIG{__WARN__} = $SIG{__WARN__} || sub { warn @_ };'."\n"
289                 . $code
290                 . q/};/
291                 . q{
292                     return $rv unless $@;
293                     die $@ if $@ and not (
294                       ref($@) eq 'ARRAY' and
295                       $@->[0] eq $cgi_exited
296                     );
297                     die "exited nonzero: $@->[1]" if $@->[1] != 0;
298                     return $rv;
299                 }
300          . '}';
301          eval $source;
302     };
303
304     # clean up
305     *CORE::GLOBAL::exit = $orig_exit;
306     $SIG{__DIE__}       = $orig_die;
307     $SIG{__WARN__}      = $orig_warn;
308
309     croak __PACKAGE__ . ": Could not compile $cgi to coderef: $@" if $@;
310
311     return $coderef
312 }
313
314 =head2 wrap_nonperl_cgi
315
316 C<< $self->wrap_nonperl_cgi($path, $action_name) >>
317
318 Takes the path to a non-Perl CGI and returns a coderef for executing it.
319
320 C<$action_name> is the generated name for the action representing the CGI file.
321
322 By default returns:
323
324     sub { system $path }
325
326 =cut
327
328 sub wrap_nonperl_cgi {
329     my ($self, $cgi, $action_name) = @_;
330
331     sub { system $cgi }
332 }
333
334 __PACKAGE__->meta->make_immutable;
335
336 =head1 SEE ALSO
337
338 L<Catalyst::Controller::WrapCGI>, L<CatalystX::GlobalContext>,
339 L<Catalyst::Controller>, L<CGI>, L<Catalyst>
340
341 =head1 BUGS
342
343 Please report any bugs or feature requests to C<bug-catalyst-controller-wrapcgi at
344 rt.cpan.org>, or through the web interface at
345 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Catalyst-Controller-WrapCGI>.
346 I will be notified, and then you'll automatically be notified of progress on
347 your bug as I make changes.
348
349 =head1 SUPPORT
350
351 More information at:
352
353 =over 4
354
355 =item * RT: CPAN's request tracker
356
357 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Catalyst-Controller-WrapCGI>
358
359 =item * AnnoCPAN: Annotated CPAN documentation
360
361 L<http://annocpan.org/dist/Catalyst-Controller-WrapCGI>
362
363 =item * CPAN Ratings
364
365 L<http://cpanratings.perl.org/d/Catalyst-Controller-WrapCGI>
366
367 =item * Search CPAN
368
369 L<http://search.cpan.org/dist/Catalyst-Controller-WrapCGI>
370
371 =back
372
373 =head1 AUTHOR
374
375 See L<Catalyst::Controller::WrapCGI/AUTHOR> and
376 L<Catalyst::Controller::WrapCGI/CONTRIBUTORS>.
377
378 =head1 COPYRIGHT & LICENSE
379
380 Copyright (c) 2008-2009 L<Catalyst::Controller::WrapCGI/AUTHOR> and
381 L<Catalyst::Controller::WrapCGI/CONTRIBUTORS>.
382
383 This program is free software; you can redistribute it and/or modify it
384 under the same terms as Perl itself.
385
386 =cut
387
388 1; # End of Catalyst::Controller::CGIBin
389
390 # vim: expandtab shiftwidth=4 ts=4 tw=80: