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