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