5859ad814d707ec54ad3eb438255961acdb16985
[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         eval ' 
222             package Catalyst::Controller::CGIBin::_CGIs_::'.$action_name.';
223             sub {'
224                 . 'local *DATA;'
225                 . q{open DATA, '<', \$data;}
226                 . $code
227          . '}';
228     };
229
230     croak __PACKAGE__ . ": Could not compile $cgi to coderef: $@" if $@;
231
232     $coderef
233 }
234
235 =head2 $self->wrap_nonperl_cgi($path, $action_name)
236
237 Takes the path to a non-Perl CGI and returns a coderef for executing it.
238
239 C<$action_name> is the generated name for the action representing the CGI file.
240
241 By default returns:
242
243     sub { system $path }
244
245 =cut
246
247 sub wrap_nonperl_cgi {
248     my ($self, $cgi, $action_name) = @_;
249
250     sub { system $cgi }
251 }
252
253 =head1 SEE ALSO
254
255 L<Catalyst::Controller::WrapCGI>, L<CatalystX::GlobalContext>,
256 L<Catalyst::Controller>, L<CGI>, L<Catalyst>
257
258 =head1 AUTHOR
259
260 Rafael Kitover, C<< <rkitover at cpan.org> >>
261
262 =head1 BUGS
263
264 Please report any bugs or feature requests to C<bug-catalyst-controller-wrapcgi at
265 rt.cpan.org>, or through the web interface at
266 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Catalyst-Controller-WrapCGI>.
267 I will be notified, and then you'll automatically be notified of progress on
268 your bug as I make changes.
269
270 =head1 SUPPORT
271
272 More information at:
273
274 =over 4
275
276 =item * RT: CPAN's request tracker
277
278 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Catalyst-Controller-WrapCGI>
279
280 =item * AnnoCPAN: Annotated CPAN documentation
281
282 L<http://annocpan.org/dist/Catalyst-Controller-WrapCGI>
283
284 =item * CPAN Ratings
285
286 L<http://cpanratings.perl.org/d/Catalyst-Controller-WrapCGI>
287
288 =item * Search CPAN
289
290 L<http://search.cpan.org/dist/Catalyst-Controller-WrapCGI>
291
292 =back
293
294 =head1 COPYRIGHT & LICENSE
295
296 Copyright (c) 2008 Rafael Kitover
297
298 This program is free software; you can redistribute it and/or modify it
299 under the same terms as Perl itself.
300
301 =cut
302
303 1; # End of Catalyst::Controller::CGIBin
304
305 # vim: expandtab shiftwidth=4 ts=4 tw=80: