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