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