773d52e48f061cc376a8d7a7e61cdbffddf6195f
[catagits/Catalyst-Controller-WrapCGI.git] / lib / Catalyst / Controller / CGIBin.pm
1 package Catalyst::Controller::CGIBin;
2
3 use strict;
4 use warnings;
5
6 use MRO::Compat;
7 use mro 'c3';
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 namespace::clean -except => 'meta';
18
19 use parent 'Catalyst::Controller::WrapCGI';
20
21 =head1 NAME
22
23 Catalyst::Controller::CGIBin - Serve CGIs from root/cgi-bin
24
25 =head1 VERSION
26
27 Version 0.007
28
29 =cut
30
31 our $VERSION = '0.007';
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     # example of a forward to /cgi-bin/hlagh/mtfnpy.cgi
42     sub dongs : Local Args(0) {
43         my ($self, $c) = @_;
44         $c->forward($self->cgi_action('hlagh/mtfnpy.cgi'));
45     }
46
47 In your .conf:
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         </CGI>
56     </Controller::Foo>
57
58 =head1 DESCRIPTION
59
60 Dispatches to CGI files in root/cgi-bin for /cgi-bin/ paths.
61
62 Unlike L<ModPerl::Registry> this module does _NOT_ stat and recompile the CGI
63 for every invocation. If this is something you need, let me know.
64
65 CGI paths are converted into action names using cgi_action (below.)
66
67 Inherits from L<Catalyst::Controller::WrapCGI>, see the documentation for that
68 module for configuration information.
69
70 =cut
71
72 sub register_actions {
73     my ($self, $app) = @_;
74
75     my $cgi_bin = $app->path_to('root', 'cgi-bin');
76
77     my $namespace = $self->action_namespace($app);
78
79     my $class = ref $self || $self;
80
81     for my $file (File::Find::Rule->file->in($cgi_bin)) {
82         my $cgi_path = abs2rel($file, $cgi_bin);
83
84         next if any { $_ eq '.svn' } splitdir $cgi_path;
85
86         my $path        = join '/' => splitdir($cgi_path);
87         my $action_name = $self->cgi_action($path);
88         my $public_path = $self->cgi_path($path);
89         my $reverse     = $namespace ? "$namespace/$action_name" : $action_name;
90         my $attrs       = { Path => [ $public_path ], Args => [ 0 ] };
91
92         my ($cgi, $type);
93
94         if ($self->is_perl_cgi($file)) { # syntax check passed
95             $type = 'Perl';
96             $cgi  = $self->wrap_perl_cgi($file, $action_name);
97         } else {
98             $type = 'Non-Perl';
99             $cgi  = $self->wrap_nonperl_cgi($file, $action_name);
100         }
101
102         $app->log->info("Registering root/cgi-bin/$cgi_path as a $type CGI.")
103             if $app->debug;
104
105         my $code = sub {
106             my ($controller, $context) = @_;
107             $controller->cgi_to_response($context, $cgi)
108         };
109
110         my $action = $self->create_action(
111             name       => $action_name,
112             code       => $code,
113             reverse    => $reverse,
114             namespace  => $namespace,
115             class      => $class,
116             attributes => $attrs
117         );
118
119         $app->dispatcher->register($app, $action);
120     }
121
122     $self->next::method($app, @_);
123
124 # Tell Static::Simple to ignore the cgi-bin dir.
125     if (!any{ $_ eq 'cgi-bin' } @{ $app->config->{static}{ignore_dirs}||[] }) {
126         push @{ $app->config->{static}{ignore_dirs} }, 'cgi-bin';
127     }
128 }
129
130 =head1 METHODS
131
132 =head2 $self->cgi_action($cgi)
133
134 Takes a path to a CGI from C<root/cgi-bin> such as C<foo/bar.cgi> and returns
135 the action name it is registered as. See L</DESCRIPTION> for a discussion on how
136 CGI actions are named.
137
138 A path such as C<root/cgi-bin/hlagh/bar.cgi> will get the private path
139 C<foo/CGI_hlagh__bar_cgi>, for controller Foo, with the C</>s converted to C<__>
140 and prepended with C<CGI_>, as well as all non-word characters converted to
141 C<_>s. This is because L<Catalyst> action names can't have non-word characters
142 in them.
143
144 This means that C<foo/bar.cgi> and C<foo__bar.cgi> for example will both map to
145 the action C<CGI_foo__bar_cgi> so B<DON'T DO THAT>.
146
147 =cut
148
149 sub cgi_action {
150     my ($self, $cgi) = @_;
151
152     my $action_name = 'CGI_' . join '__' => split '/' => $cgi;
153     $action_name    =~ s/\W/_/g;
154
155     $action_name
156 }
157
158 =head2 $self->cgi_path($cgi)
159
160 Takes a path to a CGI from C<root/cgi-bin> such as C<foo/bar.cgi> and returns
161 the public path it should be registered under.
162
163 The default is C<cgi-bin/$cgi>.
164
165 =cut
166
167 sub cgi_path {
168     my ($self, $cgi) = @_;
169     return "cgi-bin/$cgi";
170 }
171
172 =head2 $self->is_perl_cgi($path)
173
174 Tries to figure out whether the CGI is Perl or not.
175
176 If it's Perl, it will be inlined into a sub instead of being forked off, see
177 wrap_perl_cgi (below.)
178
179 If it's not doing what you expect, you might want to override it, and let me
180 know as well!
181
182 =cut
183
184 sub is_perl_cgi {
185     my ($self, $cgi) = @_;
186
187     my $shebang = IO::File->new($cgi)->getline;
188
189     return 0 if $shebang !~ /perl/ && $cgi !~ /\.pl\z/;
190
191     my $taint_check = $shebang =~ /-T/ ?  '-T' : '';
192
193     open NULL, '>', File::Spec->devnull;
194     my $pid = open3(gensym, '&>NULL', '&>NULL', "$^X $taint_check -c $cgi");
195     close NULL;
196     waitpid $pid, 0;
197
198     $? >> 8 == 0
199 }
200
201 =head2 $self->wrap_perl_cgi($path, $action_name)
202
203 Takes the path to a Perl CGI and returns a coderef suitable for passing to
204 cgi_to_response (from L<Catalyst::Controller::WrapCGI>.)
205
206 C<$action_name> is the generated name for the action representing the CGI file
207 from C<cgi_action>.
208
209 This is similar to how L<ModPerl::Registry> works, but will only work for
210 well-written CGIs. Otherwise, you may have to override this method to do
211 something more involved (see L<ModPerl::PerlRun>.)
212
213 Scripts with C<__DATA__> sections now work too.
214
215 =cut
216
217 sub wrap_perl_cgi {
218     my ($self, $cgi, $action_name) = @_;
219
220     my $code = slurp $cgi;
221
222     $code =~ s/^__DATA__(?:\r?\n|\r\n?)(.*)//ms;
223     my $data = $1;
224
225     my $coderef = do {
226         no warnings;
227         # catch exit() and turn it into (effectively) a return
228         # we *must* eval STRING because the code needs to be compiled with the
229         # overridden CORE::GLOBAL::exit in view
230         #
231         # set $0 to the name of the cgi file in case it's used there
232         eval ' 
233             my $cgi_exited = "EXIT\n";
234             BEGIN { *CORE::GLOBAL::exit = sub (;$) {
235                 die [ $cgi_exited, $_[0] || 0 ];
236             } }
237             package Catalyst::Controller::CGIBin::_CGIs_::'.$action_name.';
238             sub {'
239                 . 'local *DATA;'
240                 . q{open DATA, '<', \$data;}
241                 . qq{local \$0 = "\Q$cgi\E";}
242                 . q/my $rv = eval {/
243                 . $code
244                 . q/};/
245                 . q{
246                     return $rv unless $@;
247                     die $@ if $@ and not (
248                       ref($@) eq 'ARRAY' and
249                       $@->[0] eq $cgi_exited
250                     );
251                     die "exited nonzero: $@->[1]" if $@->[1] != 0;
252                     return $rv;
253                 }
254          . '}';
255     };
256
257     croak __PACKAGE__ . ": Could not compile $cgi to coderef: $@" if $@;
258
259     $coderef
260 }
261
262 =head2 $self->wrap_nonperl_cgi($path, $action_name)
263
264 Takes the path to a non-Perl CGI and returns a coderef for executing it.
265
266 C<$action_name> is the generated name for the action representing the CGI file.
267
268 By default returns:
269
270     sub { system $path }
271
272 =cut
273
274 sub wrap_nonperl_cgi {
275     my ($self, $cgi, $action_name) = @_;
276
277     sub { system $cgi }
278 }
279
280 =head1 SEE ALSO
281
282 L<Catalyst::Controller::WrapCGI>, L<CatalystX::GlobalContext>,
283 L<Catalyst::Controller>, L<CGI>, L<Catalyst>
284
285 =head1 AUTHOR
286
287 Rafael Kitover, C<< <rkitover at cpan.org> >>
288
289 =head1 BUGS
290
291 Please report any bugs or feature requests to C<bug-catalyst-controller-wrapcgi at
292 rt.cpan.org>, or through the web interface at
293 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Catalyst-Controller-WrapCGI>.
294 I will be notified, and then you'll automatically be notified of progress on
295 your bug as I make changes.
296
297 =head1 SUPPORT
298
299 More information at:
300
301 =over 4
302
303 =item * RT: CPAN's request tracker
304
305 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Catalyst-Controller-WrapCGI>
306
307 =item * AnnoCPAN: Annotated CPAN documentation
308
309 L<http://annocpan.org/dist/Catalyst-Controller-WrapCGI>
310
311 =item * CPAN Ratings
312
313 L<http://cpanratings.perl.org/d/Catalyst-Controller-WrapCGI>
314
315 =item * Search CPAN
316
317 L<http://search.cpan.org/dist/Catalyst-Controller-WrapCGI>
318
319 =back
320
321 =head1 COPYRIGHT & LICENSE
322
323 Copyright (c) 2008 Rafael Kitover
324
325 This program is free software; you can redistribute it and/or modify it
326 under the same terms as Perl itself.
327
328 =cut
329
330 1; # End of Catalyst::Controller::CGIBin
331
332 # vim: expandtab shiftwidth=4 ts=4 tw=80: