FakeCGI.pm untested

filter: Statementstmt 0.0% 0 / 707 Branchbran 0.0% 0 / 360 Conditioncond 0.0% 0 / 177 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 60 Podpod 0.0% 0 / 27 totaltotal 0.0% 0 / 1331 CC 132 SCAR 58.0
CC
132
Cov
0%
_cgi_header
992.0
_run_code
812.0
_capture_start
272.0
CRAP 328.9
1 package Dancer::Plugin::FakeCGI;
2  
3 use strict;
4 use warnings;
5  
6 use Dancer::Plugin;
7 use Dancer::Config;
8 use Dancer ':syntax';
9  
10 use Cwd;
11 use CGI::Compile;
12 use HTTP::Message;
13 use Test::TinyMocker;
14 use Carp;
15 use Symbol;
16 use IO::File;
17 use IO::Scalar;
18 use File::Temp;
19 use Fcntl;
20  
21 use Data::Dumper;
22  
23 =encoding utf8
24  
25 =head1 NAME
26  
27 Dancer::Plugin::FakeCGI - run CGI methods or Perl-files under Dancer
28  
29 =head1 SYNOPSIS
30  
31 =head1 DESCRIPTION
32  
33 Supports to run CGI perl files on CGI methods under Dancer.
34  
35 =head1 CONFIGURATION
36  
37 plugins:
38 FakeCGI:
39 cgi-dir: 'cgi-dir'
40 cgi-bin: '/cgi-bin'
41 cgi-package: 'lib/CGI'
42 cgi-class: ourCGI
43 stdout-type: "file"
44 temp-dir: "tmp"
45  
46 =over
47  
48 =item B<cgi-dir> - for setting directory where is placed Perl CGI file, standart is 'cgi-dir'. This directory must be in root on Dancer directory.
49  
50 =item B<cgi-bin> - web url directory where are Perl CGI files visible. Must be set.
51  
52 =item B<cgi-package> - for setting INC library where is CGI packagesa(loaded from B<fake_cgi_method>), standart is nothing.
53  
54 =item B<cgi-class> - definition child-classes for CGI, it can be defined as ARRAY, standart every 'CGI*::'
55  
56 =item B<stdout-type> - where will be saved captured string from F<STD[OUT|ERR]>, standart is capture into memory. Change with this options:
57  
58 =over 2
59  
60 =item B<file> - captured string will be saved in directory defined B<temp-dir> and in C<after> hook will be avery temp file removed
61  
62 =item B<memory> - for saving captured string use IO::Scalar
63  
64 =back
65  
66 =item B<temp-dir> - temporary directory where will be save all captured files if B<stdout-type> is set to file. Best option is use B<file> captured and B<temp-dir> mount as RAM filesystem
67  
68 =back
69  
70 =head1 TODO
71  
72 =over
73  
74 =item B<1> - Maybe captured string parsed in HTTP::Message->parse
75  
76 =item B<2> - CGI::Push use infinity loop which not existed than we don't capture any string from STDOUT and doesn't send any data.
77  
78 =item B<3> - script_name() with referer
79  
80 =item B<4> - Mod_PERL emulation for version 2
81  
82 =item B<5> - find better solution for capturing STD[OUT|ERR] under system() call when capture to memory used
83  
84 =item B<6> - Performance issue :
85  
86 every CGI files are loaded(served) 20-50% slowest then under Mod_PERL(Registry.pm). This emulation get about 15-20ms more than uner Apache. Next difference is capture in memory and to file.
87 In memory is 10-20% faster. One problem finded and there is Cwd::cwd() function which is slowest than getcwd() and take 65ms.
88 CGI::Compile() is similar as Mod_PERL::PerlRun(). Everytime it run eval() on given loaded code.
89 If we want to use behavior as Apache::Registry(), than should on first time evaled of given code to memory as package with function and
90 other every call run this method to omited evaled code into memory.
91  
92 =back
93  
94 =head1 BUGS
95  
96 =over
97  
98 =item B<1> - Not use infinity loop!!! Every CGI script must exited - finished to run properly in Dancer
99  
100 =item B<2> -Problem with fork|system function under HTTP::Server::Simple. This server make bad opening file descriptor of STDOUT. On this server it will be redirected to STDERR
101  
102 =back
103  
104 =head1 METHODS
105  
106 =cut
107  
108 our $VERSION = '0.62';
109  
110 # Own handles
111 my $settings = undef;
112 my %handle_require = ();
113 my %handle_file = ();
114  
115 my $capture = undef;
116 sub Is_Win32 { $^O eq 'MSWin32' && basename($^X) eq 'wperl.exe' }
117  
118 # Must first initialize faked Apache.pm and after that CGI
119 BEGIN {
120 my ($pack, $filename) = caller;
121 my $dir = $filename;
122 $dir =~ s/\.pm//;
123  
124 *CORE::GLOBAL::system = \&_own_system; # Emulation of 'system'
125  
126 # Import fake Apache
127 #unshift(@INC, $dir); # Add directories with Apache.pm as first position
128 #require Apache1;
129 #shift(@INC);
130 require Dancer::Plugin::FakeCGI::Apache1;
131 Apache->import;
132  
133 local %ENV = %ENV;
134 $ENV{MOD_PERL} = 1;
135 $ENV{MOD_PERL_API_VERSION} = 1;
136  
137 #Disabling CGI::Push module
138 $INC{"CGI/Push.pm"} = $INC{'Dancer/Plugin/FakeCGI.pm'};
139  
140 # Import CGI
141 require CGI;
142  
143 CGI->import('read_from_client', 'read_from_cmdline', 'new_MultipartBuffer');
144 CGI::initialize_globals()
145 if defined &CGI::initialize_globals; # Initialize CGI
146  
147 $ENV{MOD_PERL} = 0;
148 $ENV{MOD_PERL_API_VERSION} = 0;
149 require CGI::Cookie; # Better is use CGI::Cookie without MOD_PERL functionalities
150 }
151  
152 #################################################################################################
153 # CGI start #
154 #################################################################################################
155 $Dancer::Plugin::FakeCGI::Apache1::CGI_obj = CGI->new(); # Initialization for faked mod_perl emulation back to CGI
156  
157 # Disabling CGI::Push
158 {
159  
160 package CGI::Push;
161  
162 use vars qw{$AUTOLOAD};
163 use Carp;
164  
165 sub AUTOLOAD {
166 my $self = shift;
167  
168 my $name = $AUTOLOAD;
169 $name =~ s/.*://; # strip fully-qualified portion
170  
171 croak "Emulation for CGI::Push module doesn't implement, because it use infinity loop....";
172 }
173  
174 sub import {
175 croak "Emulation for CGI::Push module doesn't implement, because it use infinity loop....";
176 }
177 }
178  
179 # Initialize some CGI methods and mocking
180 my @CGI_mock_methods = ('header', 'redirect');
181 foreach my $k (@CGI_mock_methods) {
182 no strict 'refs';
183 &{"CGI::" . $k}(); # Try run first for compiled given sub in CGI
184 Test::TinyMocker::mock("CGI", $k, \&{"_cgi_" . $k});
185 }
186  
187 # Return if first position in method is some of CLASS
188 sub _cgi_self_test {
189 return 0 if (!defined($_[0]) || !ref($_[0]));
190 return 1
191 if (ref($_[0]) eq "CGI" || ref($_[0]) =~ /CGI::/); # Its CGI object or Children from CGI
192 return 0 unless ($settings->{'cgi-class'});
193 if (ref($settings->{'cgi-class'}) eq "ARRAY") {
194 foreach (@{$settings->{'cgi-class'}}) {
195 return 1 if (ref($_[0]) eq $_);
196 }
197 } else {
198 return 1 if (ref($_[0]) eq $settings->{'cgi-class'});
199 }
200 warn "First param is reference, but is not set : " . ref($_[0])
201 if (ref($_[0]));
202 return 0;
203 }
204  
205 # Retype header function
206 sub _cgi_header {
207  
208 my $self = _cgi_self_test(@_) ? shift(@_) : undef;
209  
210 # old CGI
211 my @p = @_;
212  
213 return "" if $self && $self->{'.header_printed'}++ and $CGI::HEADERS_ONCE;
214  
215 my ($type, $status, $cookie, $target, $expires, $nph, $cgi_charset, $attachment, $p3p, @other) = CGI::rearrange([
216 ['TYPE', 'CONTENT_TYPE', 'CONTENT-TYPE'],
217 'STATUS', ['COOKIE', 'COOKIES'],
218 'TARGET', 'EXPIRES', 'NPH', 'CHARSET', 'ATTACHMENT', 'P3P'
219 ],
220 @p
221 );
222  
223 #_fix_CGI_into_Dancer(); # It question if we wanted fix CGI into Dancer
224  
225 # CR escaping for values, per RFC 822
226 for my $header ($type, $status, $cookie, $target, $expires, $nph, $cgi_charset, $attachment, $p3p, @other) {
227 if (defined $header) {
228  
229 # From RFC 822:
230 # Unfolding is accomplished by regarding CRLF immediately
231 # followed by a LWSP-char as equivalent to the LWSP-char.
232 $header =~ s/$CGI::CRLF(\s)/$1/g;
233  
234 # All other uses of newlines are invalid input.
235 if ($header =~ m/$CGI::CRLF|\015|\012/) {
236  
237 # shorten very long values in the diagnostic
238 $header = substr($header, 0, 72) . '...'
239 if (length $header > 72);
240 croak "Invalid header value contains a newline not followed by whitespace: $header";
241 }
242 }
243 }
244  
245 $nph ||= $CGI::NPH;
246  
247 # Set content type
248 content_type($type || 'text/html');
249  
250 # sets if $charset is given, gets if not
251  
252 if (defined $cgi_charset) {
253 charset($cgi_charset);
254 } elsif ($type && $type =~ /^text\//) {
255 $cgi_charset = setting('charset');
256 }
257 $cgi_charset ||= '';
258  
259 # rearrange() was designed for the HTML portion, so we need to fix it up a little.
260 my @other_headers;
261 for (@other) {
262  
263 # Don't use \s because of perl bug 21951
264 next unless my ($header, $value) = /([^ \r\n\t=]+)=\"?(.+?)\"?$/s;
265 $header =~ s/^(\w)(.*)/"\u$1\L$2"/e;
266 push @other_headers, {$header => CGI::unescapeHTML($value)};
267 }
268  
269 $type .= "; charset=$cgi_charset"
270 if $type
271 and $type ne ''
272 and $type !~ /\bcharset\b/
273 and defined $cgi_charset
274 and $cgi_charset ne '';
275  
276 # Maybe future compatibility. Maybe not.
277 my $protocol = $ENV{SERVER_PROTOCOL} || 'HTTP/1.0';
278  
279 #push(@header,$protocol . ' ' . ($status || '200 OK')) if $nph;
280 $status ||= 200 if $nph;
281  
282 push_header("Server", CGI::server_software()) if $nph;
283  
284 if ($status) {
285 $status = _parse_int($status);
286 status($status) if ($status);
287 }
288  
289 push_header "Window-Target" => $target if $target;
290 if ($p3p) {
291 $p3p = join ' ', @$p3p if ref($p3p) eq 'ARRAY';
292 $p3p =~ s/CP=//;
293 $p3p =~ s/"//;
294 push_header "P3P" => 'policyref="/w3c/p3p.xml", CP="' . $p3p . '"';
295 }
296  
297 # push all the cookies -- there may be several
298 if ($cookie) {
299 my (@cookie) = ref($cookie) && ref($cookie) eq 'ARRAY' ? @{$cookie} : $cookie;
300 for my $cs (@cookie) {
301 if (UNIVERSAL::isa($cs, 'CGI::Cookie')) {
302 my $self_cookie = $cs;
303 next unless $self_cookie->name;
304  
305 my %h = (name => CGI::escape($self_cookie->name));
306  
307 #my $value = join "&", map { CGI::escape($_) } $self_cookie->value;
308 my @a_value = $self_cookie->value;
309 if (scalar(@a_value) > 1) {
310 my %h_value = (@a_value);
311 $h{value} = \%h_value;
312 } else {
313 $h{value} = $a_value[0];
314 }
315 foreach my $k ('domain', 'path', 'expires', 'secure') {
316 $h{$k} = $self_cookie->$k if $self_cookie->$k;
317 }
318  
319 $h{'max-age'} = $self_cookie->max_age if $self_cookie->max_age;
320 $h{'http_only'} = 1 if $self_cookie->httponly;
321  
322 set_cookie(%h);
323 } else {
324 push_header("Set-Cookie", $cs) if $cs ne '';
325 }
326 }
327 }
328  
329 # if the user indicates an expiration time, then we need
330 # both an Expires and a Date header (so that the browser is uses OUR clock)
331 push_header "Expires" => CGI::expires($expires, 'http') if $expires;
332 push_header "Date" => CGI::expires(0, 'http')
333 if $expires || $cookie || $nph;
334  
335 push_header "Pragma" => "no-cache" if ($self && $self->cache());
336 push_header "Content-Disposition" => "attachment; filename=\"$attachment\""
337 if $attachment;
338  
339 push_header map { ucfirst $_ } @other if (@other);
340 foreach my $rh (@other_headers) {
341 push_header %$rh;
342 }
343  
344 return '';
345 }
346  
347 # Retype read_from_client function
348 sub _cgi_read_from_client {
349 shift(@_) if (_cgi_self_test(@_));
350  
351 my $buf = (ref($_[0]) eq "SCALAR") ? $_[0] : \$_[0];
352 my $len = $_[1];
353 my $offset = $_[2] || 0;
354  
355 no strict 'refs';
356 $$buf = substr(request->body(), $offset, $len);
357 return length($$buf);
358 }
359  
360 # Retype read_from_cmdline function
361 sub _cgi_read_from_cmdline {
362 shift(@_) if (_cgi_self_test(@_));
363  
364 my $str = "";
365 _cgi_read_from_client(\$str, 0);
366 my ($subpath);
367 return {'query_string' => $str, 'subpath' => $subpath};
368 }
369  
370 # Retype redirect function
371 sub _cgi_redirect {
372  
373 my $self = _cgi_self_test(@_) ? shift(@_) : CGI->new;
374 my @p = @_;
375  
376 my ($url, $target, $status, $cookie, $nph, @other) =
377 CGI::rearrange([['LOCATION', 'URI', 'URL'], 'TARGET', 'STATUS', ['COOKIE', 'COOKIES'], 'NPH'], @p);
378 $status = '302 Found' unless defined $status;
379 $url ||= $self->self_url;
380 my (@o);
381 for (@other) { tr/\"//d; push(@o, split("=", $_, 2)); }
382 unshift(
383 @o,
384 '-Status' => $status,
385 '-Location' => $url,
386 '-nph' => $nph
387 );
388 unshift(@o, '-Target' => $target) if $target;
389 unshift(@o, '-Type' => '');
390 my @unescaped;
391 unshift(@unescaped, '-Cookie' => $cookie) if $cookie;
392  
393 return $self->header((map { $self->unescapeHTML($_) } @o), @unescaped);
394 }
395  
396 # Retype new_MultipartBuffer function
397 sub _cgi_new_MultipartBuffer {
398 my $self = shift;
399 my $new = Dancer::Plugin::FakeCGI::MultipartBuffer->new($self, @_);
400  
401 #$new->{'.req'} = $self->{'.req'} || Apache->request;
402 return $new;
403 }
404  
405 #################################################################################################
406 # CGI end #
407 #################################################################################################
408  
409 #
410 my $dancer_version = (exists &dancer_version) ? int(dancer_version()) : 1;
411 my ($logger);
412 if ($dancer_version == 1) {
413 require Dancer::Config;
414 Dancer::Config->import();
415  
416 #$logger = sub { Dancer::Logger->can($_[0])->($_[1]) };
417 } else {
418  
419 #$logger = sub { log @_ };
420 }
421  
422 # Return path where are cgi-bin files
423 sub _ret_cgi_bin_path {
424 return path(setting('confdir'), defined($_[0]) ? $_[0] : $settings->{'cgi-dir'});
425 }
426  
427 # Perl trim function to remove whitespace from the start and end of the string
428 sub _trim($) {
429 my $string = shift;
430 $string =~ s/^\s+//;
431 $string =~ s/\s+$//;
432 return $string;
433 }
434  
435 # Loading setting
436 sub _load_settings {
437 return if (defined($settings) && ref($settings) eq "HASH");
438 my $first = defined($settings) ? 0 : 1;
439 $settings = plugin_setting() || {};
440 unshift(@INC, _ret_cgi_bin_path($settings->{'cgi-package'})) if ($first && $settings->{'cgi-package'});
441 $settings->{'cgi-dir'} ||= 'cgi-dir';
442  
443 my $dir = _ret_cgi_bin_path();
444 unless (-d $dir) {
445 croak "Directory doesn't exists : $dir";
446 }
447 unless ($settings->{'cgi-bin'}) {
448 croak "Setting 'cgi-bin' must be setted";
449 }
450  
451 $settings->{'stdout-type'} ||= 'memory';
452 if ($settings->{'stdout-type'} eq "file") {
453 unless ($settings->{'temp-dir'}) {
454 croak "Setting 'temp-dir' must be setted";
455 }
456 unless (-d $settings->{'temp-dir'}) {
457 croak "Setting 'temp-dir:" . $settings->{'temp-dir'} . "' isn't directory";
458 }
459 unless (-r $settings->{'temp-dir'}) {
460 croak "Not readable directory :" . $settings->{'temp-dir'};
461 }
462 unless (-w $settings->{'temp-dir'}) {
463 croak "Not writable directory :" . $settings->{'temp-dir'};
464 }
465 } else {
466 $settings->{'stdout-type'} = 'memory';
467 }
468  
469 # Repair url
470 if ($first) {
471 my $string = _trim($settings->{'cgi-bin'});
472 $string =~ s/\/$//;
473 $string =~ s/^\///;
474 $settings->{'cgi-bin'} = "/" . $string;
475 }
476  
477 return unless ($first);
478 }
479  
480 # Method for loading module
481 sub _load_package {
482 my $package = shift;
483  
484 my $pack = caller;
485 unless (exists($handle_require{$package})) {
486 my ($eval_result, $eval_error) = _eval("package $pack;require $package @_;1;");
487 croak("Problem with require $package: $eval_error")
488 unless ($eval_result);
489 $handle_require{$package} = 1;
490 return $eval_result;
491 }
492 return 1;
493 }
494  
495 # Test if given file can run
496 sub _test_runable {
497 my $fname = shift || return "Not defined filename";
498  
499 if (-r $fname && -s $fname) {
500 if (-d $fname) {
501 return "Is directory";
502 }
503 unless (-x $fname or Is_Win32) {
504 return "File permissions deny server execution";
505 }
506 return undef;
507 }
508 return "Filename not found or unable to stat : $fname";
509 }
510  
511 # Return filename
512 sub _get_file_name {
513 my ($name, $ret_filename) = @_;
514  
515 unless (defined($name)) {
516 croak("Not defined filename");
517 return undef;
518 }
519  
520 my $dir = _ret_cgi_bin_path();
521 my $filename = $dir . "/" . $name;
522 my $tf = _test_runable($filename);
523 if ($tf) {
524 croak $tf;
525 return undef;
526 }
527  
528 return ($ret_filename ? $filename : $name);
529 }
530  
531 my $run_code_evaled = 0;
532  
533 # Own function os system() for capturing string
534 sub _own_system {
535 my @args = @_;
536  
537 return CORE::system(@args) unless ($run_code_evaled);
538  
539 # Flushing STDOUT and STDERR to file or memory to prevent problems
540 flush STDERR;
541 flush STDOUT;
542  
543 if ($ENV{SERVER_SOFTWARE} && $ENV{SERVER_SOFTWARE} =~ /HTTP::Server::Simple/) {
544 warn
545 "In HTTP::Server::Simple is problem with redirect STDOUT under forked/system proccess, use plackup instead this server !!!";
546 } elsif ($settings->{'stdout-type'} eq "memory") {
547 warn "system() function can't capture STDOUT when is set to memory, must be set to file !!!";
548  
549 #require IPC::Open3;
550 #my $rdr;
551 #my $err = Symbol::gensym;
552 #my $pid = IPC::Open3::open3(undef, $rdr, $err, @args);
553 #waitpid( $pid, 0 );
554 #return $? >> 8;
555 }
556  
557 require Capture::Tiny;
558 my ($out, $err) = Capture::Tiny::capture {
559 return CORE::system(@args);
560 };
561 print STDERR $err if ($err);
562 print STDOUT $out if ($out);
563 }
564  
565 # Method for compile files
566 sub _compile_file {
567 my ($file, $is_perl, $package_name) = @_;
568  
569 my $filename = _get_file_name($file, 1) || return;
570 my $mtime = (stat($filename))[9];
571  
572 # Test if compiled name exist and it isn't newer
573 if ($handle_require{$file} && (!$handle_require{$file}->{'mtime'} || $mtime != $handle_require{$file}->{'mtime'})) {
574 $is_perl = $handle_require{$file}->{'is_perl'};
575 delete($handle_require{$file});
576 }
577  
578 debug("After testing $file");
579  
580 my $sub = undef;
581 unless (exists($handle_require{$file})) {
582  
583 # Change to current dir where is cgi-bin
584 my $currWorkDir = Cwd::cwd();
585  
586 #my $dir = dirname($file);
587 my $dir = _ret_cgi_bin_path();
588 chdir($dir);
589  
590 my ($eval, $package, $fn_name);
591 if ($is_perl) {
592  
593 #$sub = CGI::Compile->compile($file, $package_name);
594 ($sub, $eval, $package, $fn_name) = CGI::Compile->compile($file, $package_name, undef, "handler");
595 unless ($sub) {
596 my ($eval_result, $eval_error) = _eval($eval);
597 no strict 'refs';
598 $sub = \&{$package . "::" . $fn_name};
599 }
600 } else {
601 my $cgi = $file;
602 $cgi =~ s/^\.//;
603 $cgi =~ s/^\///;
604 $sub = sub {
605 system("./" . $cgi);
606 if ($? == -1) {
607 die "failed to execute CGI '$cgi': $!";
608 } elsif ($? & 127) {
609 die sprintf "CGI '$cgi' died with signal %d, %s coredump", ($? & 127), ($? & 128) ? 'with' : 'without';
610 } else {
611 my $exit_code = $? >> 8;
612  
613 return 0 if $exit_code == 0;
614  
615 die "CGI '$cgi' exited non-zero with: $exit_code";
616 }
617 };
618 }
619 chdir($currWorkDir);
620 $handle_require{$file} =
621 {mtime => $mtime, code => $sub, is_perl => $is_perl, package => $package, func => $fn_name, loaded => 0};
622 } elsif (ref($handle_require{$file}) eq "HASH") {
623 $sub = $handle_require{$file}->{'code'};
624 }
625  
626 debug("Loading $file");
627 return $sub, $handle_require{$file};
628 }
629  
630 # return int from scalar
631 sub _parse_int {
632 my $ret = $_[0] || return 0;
633  
634 $ret =~ s/\D*$//;
635 return $ret ? int(0 . $ret) : 0;
636 }
637  
638 # Eval function
639 sub _eval {
640 my ($code, @args) = @_;
641  
642 # Work around oddities surrounding resetting of $@ by immediately
643 # storing it.
644 my ($sigdie, $eval_result, $eval_error);
645 {
646 local ($@, $!, $SIG{__DIE__}); # isolate eval
647 $eval_result = eval $code; ## no critic (BuiltinFunctions::ProhibitStringyEval)
648 $eval_error = $@;
649 $sigdie = $SIG{__DIE__} || undef;
650 }
651  
652 # make sure that $code got a chance to set $SIG{__DIE__}
653 $SIG{__DIE__} = $sigdie if defined $sigdie;
654  
655 return ($eval_result, $eval_error);
656 }
657  
658 # Function for added params in dancer which can be changed in CGI
659 sub _fix_CGI_into_Dancer {
660 my @a = CGI::param();
661 pop(@a) if (scalar(@a) % 2); # Odd count of params, problems in CGI::Util::rearange
662 my %all_CGI_params = (@a);
663 my $all_Dancer_params = params();
664  
665 # Added CGI param into Dancer
666 while (my ($k, $d) = each %all_CGI_params) {
667 $all_Dancer_params->{$k} = $d;
668 }
669  
670 # Added CGI param into Dancer
671 while (my ($k, $d) = each %$all_Dancer_params) {
672 next if ($k eq "splat");
673 $all_Dancer_params->{$k} = undef unless (exists($all_CGI_params{$k}));
674 }
675 }
676  
677 #################################################################################################
678 # Capture start #
679 #################################################################################################
680 # Initialization of captured(use_STDOUT, use_STDERR)
681 sub _capture_start {
682  
683 my @a_type = ();
684 push(@a_type, "STDOUT") if (shift); # If first param true, than capture STDOUT
685 push(@a_type, "STDERR") if (shift); # If second params true, than capture STDERR
686  
687 $capture ||= {STDOUT => {}, STDERR => {}};
688 foreach my $type (@a_type) {
689 my $rh = $capture->{$type};
690  
691 # If captured print error and return
692 if ($rh->{"old_fh"}) {
693 croak "Type $type is already captured";
694 next;
695 }
696  
697 # If not initialized than made primary initalization
698 if ($settings->{'stdout-type'} eq 'memory') {
699 $rh->{"string"} ||= '';
700 } else {
701 ($rh->{"io_fh"}, $rh->{"filename"}) = File::Temp::tempfile(
702 DIR => path(setting('confdir'), $settings->{'temp-dir'}),
703  
704 #TEMPLATE => 'tempXXXXX',
705 SUFFIX => "." . $type,
706 UNLINK => 0, # We unlink automatically in after hook
707 OPEN => 1,
708 EXLOCK => 1,
709 ) unless (exists($rh->{"io_fh"}));
710 }
711  
712 open(my $fh, ">&" . $type) or die "Can't dup $type: $!";
713 $rh->{"std_fh"} = $fh;
714  
715 no strict 'subs';
716 close($type eq "STDERR" ? STDERR : STDOUT);
717  
718 if ($settings->{'stdout-type'} eq 'memory') {
719 my $result;
720 if ($type eq "STDERR") {
721 $result = open(STDERR, '>>', \$rh->{"string"});
722 } else {
723 $result = open(STDOUT, '>>', \$rh->{"string"});
724 }
725 die "Can't redirect $type to scalar : $!" unless ($result);
726 $rh->{"io_fh"} = new IO::Scalar \$rh->{"io_fh"} if ($type eq "STDOUT" && !exists($rh->{"io_fh"}));
727 } else {
728 my $result;
729 if ($type eq "STDERR") {
730  
731 #$result = open(\*STDERR, '>&=' . fileno($rh->{"io_fh"}));
732 $result = open(\*STDERR, '>>', $rh->{"filename"});
733 } else {
734 $result = open(\*STDOUT, '>>', $rh->{"filename"});
735 }
736 die "Can't redirect $type to " . $rh->{"filename"} . " : $!" unless ($result);
737  
738 #my $flags = fcntl($rh->{"io_fh"}, F_GETFL, 0);
739 #$flags |= O_APPEND; # Add non-blocking to the flags
740 #fcntl($rh->{"io_fh"}, F_SETFL, $flags) || die "Can't set flags from '$type' to O_APPEND : $!"; # Set the flags on the f
741 }
742  
743 binmode($type eq "STDERR" ? STDERR : STDOUT, ":utf8") if $] >= 5.008;
744 select($type eq "STDERR" ? STDERR : STDOUT);
745 $| = 1;
746 select(STDOUT);
747 }
748 }
749  
750 # Endingn or stop capturing
751 sub _capture_end {
752 return if (!$capture || ref($capture) ne "HASH");
753  
754 foreach my $type ("STDOUT", "STDERR") {
755 next if (!exists($capture->{$type}) || !$capture->{$type}->{"std_fh"});
756 no strict 'subs';
757 if ($type eq "STDERR") {
758 flush STDERR;
759 open(STDERR, ">&", $capture->{$type}->{"std_fh"}) or die "Can't restore old STDERR: $!";
760 } else {
761 flush STDERR;
762 open(STDOUT, ">&", $capture->{$type}->{"std_fh"}) or die "Can't restore old STDOUT: $!";
763 }
764 delete($capture->{$type}->{"std_fh"});
765 }
766 select(STDOUT);
767 }
768  
769 #################################################################################################
770 # Capture end #
771 #################################################################################################
772  
773 # what we run on before hook
774 hook before => sub {
775 my $route_handler = shift;
776  
777 undef $capture;
778 };
779  
780 # what we run on after hook
781 hook after => sub {
782 if (ref($capture) eq "HASH") {
783 foreach my $type ("STDOUT", "STDERR") {
784 close($capture->{$type}->{"io_fh"}) if ($capture->{$type}->{"io_fh"});
785 unlink($capture->{$type}->{"filename"}) if ($capture->{$type}->{"filename"});
786 }
787 }
788 undef $capture;
789 };
790  
791 hook before_template_render => sub {
792 my $tokens = shift;
793  
794 _fix_CGI_into_Dancer(); # Fix Dancer variables after CGI runned before template rendering
795 };
796  
797 =head3 <$capture> - is reference to this HASH
798  
799 =over
800  
801 =item F<STDOUT|STDERR> - type of captured string for given output. It is HASH reference to this other options:
802  
803 =over 2
804  
805 =item B<string> - if setting enabled capturing to memory this is string contains every characters captured
806  
807 =item B<io_fh> - handler to L<IO::File> if is set to capturing into file, if is set to memory it is handler to L<IO::Scalar>
808  
809 =item B<filename> - filename with path if capturing is to file
810  
811 =item B<header_len> - this is size of HTTP header. On this position start HTML content. It is only for capturing into file
812  
813 =item B<std_fh> - saved original filehandler into this param if is capturing enabled. If capturing stop than this option not exist
814  
815 =back
816  
817 =back
818  
819  
820 =head3 PARAMS for C<_run_code()> is hashref
821  
822 =over
823  
824 =item B<capture_stderr> - B<STDERR> will be captured similar as B<STDOUT> and when eval(_run_code) finished, that will be loged
825  
826 =item B<timeout> - in seconds which can timeouted given eval via alarm() function. If is B<0|undefined> - disabled it
827  
828 =item B<ret_error> - try run given code and return after eval
829  
830 =back
831  
832 =cut
833  
834 sub _run_code {
835 my $code = shift || return;
836 return if (ref($code) ne "CODE");
837 my $params = shift || {};
838 my $filename = shift;
839  
840 my $env = request->env();
841 local %ENV = (%ENV, (map { $_ => $env->{$_} } grep !/^psgix?\./, keys %$env));
842 foreach my $k (
843 qw/
844 SERVER_SOFTWARE SERVER_NAME GATEWAY_INTERFACE SERVER_PROTOCOL
845 SERVER_PORT REQUEST_METHOD PATH_INFO SCRIPT_NAME QUERY_STRING
846 REMOTE_HOST REMOTE_ADDR CONTENT_TYPE CONTENT_LENGTH HTTP_ACCEPT HTTP_USER_AGENT/,
847  
848 #qw/MOD_PERL PATH_TRANSLATED AUTH_TYPE REMOTE_TYPE REMOTE_IDENT/
849 ) {
850  
851 #croak("Not existed '$k' in Enviroment") unless (exists($ENV{$k}));
852 }
853  
854 # Settings from config
855 if ($settings->{'Enviroments'}) {
856 while (my ($k, $d) = each %{$settings->{'Enviroments'}}) {
857 $ENV{$k} = $d;
858 }
859 }
860  
861 # Repair couple of settings
862 $ENV{MOD_PERL} = 1; # put to all of programs, when we emulate Mod_PERL version 1
863 $ENV{DOCUMENT_ROOT} = _ret_cgi_bin_path();
864 $ENV{SCRIPT_FILENAME} = $ENV{DOCUMENT_ROOT} . "/" . $ENV{PATH_INFO};
865  
866 #$ENV{SCRIPT_NAME} = $ENV{PATH_INFO};
867  
868 # Repair PATH_INFO and SCRIPT_NAME
869 {
870 my $sname = $ENV{PATH_INFO};
871 delete($ENV{PATH_INFO});
872  
873 my $s = $settings->{'cgi-bin'};
874 if ($s && $s ne "/") {
875 $sname =~ s/$s//;
876 }
877 $sname =~ s/^\///;
878 my @a_name = split('/', $sname);
879 $ENV{SCRIPT_NAME} = fake_cgi_bin_url(shift(@a_name));
880  
881 # CGI.pm use referer from ENV{HTTP_REFERER}
882 #$ENV{SCRIPT_NAME} .= ", referer: " . $ENV{HTTP_REFERER} if ($ENV{HTTP_REFERER} && length($ENV{HTTP_REFERER}));
883 $ENV{PATH_INFO} = "/" . join('/', @a_name) if (scalar(@a_name));
884 }
885 debug("After ENV");
886  
887 CGI::initialize_globals()
888 if defined &CGI::initialize_globals; # Initialize CGI
889  
890 debug("After CGI::initialize_globals");
891  
892 my $str_alarmed = "alarm is called...\n";
893  
894 my ($ret, $err) = (undef, undef);
895 {
896 _capture_start(1, (!$params->{ret_error} && $params->{capture_stderr}) ? 1 : 0);
897 debug("After _capture_start() ");
898  
899 Dancer::Factory::Hook->instance->execute_hooks('fake_cgi_before', \%ENV, $capture) unless ($params->{ret_error});
900 debug("After hook: fake_cgi_before ");
901  
902 # Change to current dir where is cgi-bin
903 #my $currWorkDir = Cwd::cwd(); # calling method cwd() is slowest than getcwd and use about 65ms
904 my $currWorkDir = Cwd::getcwd();
905 debug("After Cwd...");
906  
907 my $dir = _ret_cgi_bin_path();
908 chdir($dir);
909  
910 debug("Before eval given code() ");
911  
912 #make sure this hooks are restored to their original state
913 local $SIG{__DIE__} = $SIG{__DIE__};
914 local $SIG{__WARN__} = $SIG{__WARN__};
915  
916 # CGI::Compile made it
917 ## Change script name
918 #my $old_name = $0;
919 ##local $0 = $filename; #this core dumps!?
920 #*0 = \$filename if ($filename);
921  
922 $run_code_evaled = 1;
923  
924 # Test for timeout
925 local $SIG{ALRM} = $SIG{ALRM};
926 my $timeout = _parse_int($params->{timeout});
927 if ($timeout) {
928 $SIG{ALRM} = sub { die $str_alarmed };
929 alarm $timeout;
930 }
931  
932 eval { # Run compiled code
933 no strict 'refs';
934 $ret = &{$code}();
935 };
936  
937 alarm(0) if ($timeout);
938  
939 $err = $@; # Save error to scalar
940  
941 #*0 = $old_name;
942  
943 $run_code_evaled = 0;
944 chdir($currWorkDir);
945  
946 debug("After eval given code() ");
947  
948 _capture_end();
949 debug("After _capture_end() ");
950 }
951  
952 return $err if ($params->{ret_error});
953  
954 # When is in CGI called system() function, there is problem with filehandle and it is a blocked, then try to reopen it
955 sub _reopen_file {
956 return unless ($_[0]);
957 close($_[0]) or warn "Can't close IO handler";
958 open(my $fh, "<:utf8", $_[0]) or die "Can't reopen for reading : $!";
959 return $fh;
960 }
961  
962 # Print captured string on STDERR
963 if ($capture->{"STDERR"}->{string}) {
964 debug $capture->{"STDERR"}->{string};
965 } elsif ($capture->{"STDERR"}->{io_fh}) {
966  
967 #$capture->{io_err} = _reopen_file($capture->{io_err});
968 seek($capture->{"STDERR"}->{"io_fh"}, 0, SEEK_SET);
969  
970 # Print everything in STDERR as one line
971 debug $capture->{"STDERR"}->{"io_fh"}->getlines();
972 unlink($capture->{"STDERR"}->{"filename"}) if ($capture->{"STDERR"}->{"filename"});
973 }
974 delete($capture->{"STDERR"});
975 debug("After STDERR print ");
976  
977 # Get on first position
978 if ($settings->{'stdout-type'} eq 'file') {
979  
980 #$capture->{io_out} = _reopen_file($capture->{io_out});
981 } elsif (exists($capture->{"STDOUT"}) && $capture->{"STDOUT"}->{"io_fh"}) {
982 seek($capture->{"STDOUT"}->{"io_fh"}, 0, SEEK_SET);
983 }
984  
985 # If error captured, than we finish
986 if ($err) {
987 croak $err eq $str_alarmed
988 ? "Timeouted after " . $params->{timeout} . " seconds"
989 : $err;
990 return;
991 }
992  
993 # Delete headers from captured STDOUT
994 if (exists($capture->{"STDOUT"}) && $capture->{"STDOUT"}->{"io_fh"}) {
995 my $r_str = undef;
996 my $str_len = 0;
997 if ($capture->{"STDOUT"}->{"string"}) {
998 $r_str = \$capture->{"STDOUT"}->{"string"};
999 } else {
1000 my $str = '';
1001 $str_len = read($capture->{"STDOUT"}->{"io_fh"}, $str, 8 * 1024); # Read 8kB from file a find if it isn't header
1002 $r_str = \$str;
1003 }
1004  
1005 # From HTTP::Message->parse
1006 my @hdr;
1007 while (1) {
1008 unless ($r_str) {
1009 last;
1010 } elsif ($$r_str =~ s/^([^\s:]+)[ \t]*: ?(.*)\n?//) {
1011 push(@hdr, $1, $2);
1012 $hdr[-1] =~ s/\r\z//;
1013 } elsif (@hdr && $$r_str =~ s/^([ \t].*)\n?//) {
1014 $hdr[-1] .= "\n$1";
1015 $hdr[-1] =~ s/\r\z//;
1016 } else {
1017 $$r_str =~ s/^\r?\n//;
1018 last;
1019 }
1020 }
1021  
1022 if ($settings->{'stdout-type'} eq 'file') {
1023 my $l = length($$r_str);
1024 $capture->{"STDOUT"}->{"header_len"} = ($l < $str_len) ? ($str_len - $l) : 0;
1025 seek($capture->{"STDOUT"}->{"io_fh"}, $capture->{"STDOUT"}->{"header_len"}, SEEK_SET);
1026 }
1027  
1028 #my $mess = HTTP::Message->new(\@hdr, $$r_str);
1029 my $mess = HTTP::Message->new(\@hdr, "");
1030 my $h = $mess->headers;
1031  
1032 content_type $h->content_type if ($h->content_type);
1033  
1034 #charset($h->content_type_charset) if ($h->content_type_charset);
1035  
1036 $h->remove_header('Content-Type');
1037 my @ak = $h->header_field_names;
1038 push_header map { ucfirst $_ => $h->header($_) } @ak if (@ak);
1039 }
1040 debug("After header read ");
1041  
1042 Dancer::Factory::Hook->instance->execute_hooks('fake_cgi_after', $capture);
1043 debug("After hook fake_cgi_after ");
1044  
1045 return $ret;
1046 }
1047  
1048 # Method for delete character from string URL
1049 sub _clean_url_string {
1050 my $str = shift || return;
1051  
1052 $str = _trim($str);
1053 $str =~ s/^\///;
1054 $str =~ s/\/$//;
1055 return $str;
1056 }
1057  
1058 =head2 fake_cgi_bin_url($name[,@other])
1059  
1060 Method which return url for given C<$name>. If set C<@other>, than this will be append to given URL with separattor B</>
1061  
1062 =cut
1063  
1064 register fake_cgi_bin_url => sub {
1065 my ($self, $name, @others) = plugin_args(@_);
1066 _load_settings() unless ($settings);
1067  
1068 my @a = map { _clean_url_string($_); } @others;
1069  
1070 $name = _clean_url_string($name || "");
1071 my $s = _clean_url_string($settings->{'cgi-bin'} || "");
1072 return join("/", $s, $name, @a);
1073 };
1074  
1075 =head2 fake_cgi_method($package, $method, $params, @args)
1076  
1077 Method for runned specified CGI method-function and return values of runned function.
1078  
1079 =over
1080  
1081 =item B<$package> - Package name where is method, which we run. Automatically load this package to memory in first run.
1082  
1083 =item B<$method> - Method name which we run.
1084  
1085 =item B<$params> - Hash ref of params, look of params to C<_run_code()>
1086  
1087 =item B<@args> - Arguments for given method
1088  
1089 =back
1090  
1091 =cut
1092  
1093 register fake_cgi_method => sub {
1094 my ($self, $package, $method, $params, @args) = plugin_args(@_);
1095  
1096 unless (defined($method)) {
1097 croak("If not defined method in package, use 'fake_cgi_file'");
1098 return;
1099 }
1100  
1101 _load_settings() unless ($settings);
1102 return if ($package && !_load_package($package));
1103  
1104 unless ($package->can($method)) {
1105 croak("Not existed method '$method' in package '$package'");
1106 return;
1107 }
1108  
1109 my $func = (defined($package) ? ($package . "::") : "") . $method;
1110  
1111 mock(
1112 "CGI::Compile",
1113 "_read_source",
1114 sub {
1115 return "&" . $func . "(" . (@args ? join(",", @args) : "") . ");";
1116 });
1117 my $sub = CGI::Compile->compile(join("-", "fake_cgi_method", $$, time));
1118 unmock("CGI::Compile", "_read_source");
1119  
1120 my $ret = _run_code($sub, $params);
1121  
1122 debug("Running method $method in package $package ");
1123 return $ret;
1124 };
1125  
1126 =head2 fake_cgi_file($file, $params, $test_is_perl)
1127  
1128 Method for runned specified Perl CGI file and returned exit value
1129  
1130 =over
1131  
1132 =item B<$file> - CGI filename and first in first run we compiled this file into memory
1133  
1134 =item B<$params> - Hash ref of params, look of params to C<_run_code()>
1135  
1136 =item B<$test_is_perl> - try first if given file is Perl code, default we use given filename as is Perl script.
1137  
1138 =back
1139  
1140 =cut
1141  
1142 register fake_cgi_file => sub {
1143 my ($self, $file, $params, $test_is_perl) = plugin_args(@_);
1144  
1145 _load_settings() unless ($settings);
1146 my $fname = _get_file_name($file) || return;
1147  
1148 my $is_perl = 1;
1149 $is_perl = fake_cgi_is_perl($fname) if ($test_is_perl);
1150 my ($sub, $rh) = _compile_file($fname, $is_perl);
1151  
1152 my $ret = _run_code($sub, $params, $file);
1153 debug("Running $file ");
1154 return $ret;
1155 };
1156  
1157 =head2 fake_cgi_compile(@args)
1158  
1159 Load packages into memory or Compiled files into memory. B<@args> is array of this HASHREF options:
1160  
1161 =over
1162  
1163 =item B<package> - load package into memory
1164  
1165 =item B<filename> - compile Perl filename into memory
1166  
1167 =item B<test_is_perl> - if B<filename> than run test if it is Perl CGI file
1168  
1169 =back
1170  
1171 =cut
1172  
1173 register fake_cgi_compile => sub {
1174 my ($self, @args) = plugin_args(@_);
1175 _load_settings() unless ($settings);
1176 foreach my $rh (@args) {
1177 if (ref($rh) ne "HASH") {
1178 croak("Must be hash");
1179 } elsif (exists($rh->{filename})) {
1180 my $fname = _get_file_name($rh->{filename});
1181 if ($fname) {
1182 my $is_perl = 1;
1183 $is_perl = fake_cgi_is_perl($fname) if ($rh->{test_is_perl});
1184 _compile_file($fname, $is_perl);
1185 }
1186 } elsif (exists($rh->{package})) {
1187 _load_package($rh->{package});
1188 } else {
1189 croak("Nothing defined");
1190 }
1191 }
1192 };
1193  
1194 # Takes a path to a CGI from C<root/cgi-bin> such as C<foo/bar.cgi> and returns
1195 # the action name it is registered as.
1196 sub _cgi_action {
1197 my ($cgi) = @_;
1198  
1199 my $action_name = 'CGI_' . $cgi;
1200 $action_name =~ s/([^A-Za-z0-9_])/sprintf("_%2x", unpack("C", $1))/eg;
1201  
1202 return $action_name;
1203 }
1204  
1205 =head2 fake_cgi_is_perl($file, $compile)
1206  
1207 Tries to figure out whether the CGI is Perl code or not.
1208  
1209 Return 1 if its Perl code otherwise is 0.
1210  
1211 =over
1212  
1213 =item B<$file> - filename of test file
1214  
1215 =item B<$compile> - if true and given tested file is Perl code, than compiled given file into memory
1216  
1217 =back
1218  
1219 =cut
1220  
1221 register fake_cgi_is_perl => sub {
1222 my ($self, $cgi, $compiled) = plugin_args(@_);
1223 _load_settings() unless ($settings);
1224  
1225 if (Is_Win32) {
1226 my $cgi_name = _cgi_action($cgi);
1227  
1228 # the fork code fails on Win32
1229 my $sub = _compile_file($cgi, undef, $cgi_name);
1230 my $success = _run_code($sub, {ret_error => 1}) ? 0 : 1;
1231  
1232 require Class::Unload;
1233 Class::Unload->unload($cgi_name);
1234 return $success;
1235 }
1236  
1237 require File::Spec;
1238  
1239 my (undef, $tempfile) = File::Temp::tempfile;
1240  
1241 my $pid = fork;
1242 unless (defined $pid) {
1243 croak "Cannot make fork: $!";
1244 return 1;
1245 }
1246  
1247 if ($pid) {
1248 waitpid $pid, 0;
1249 my $errors = IO::File->new($tempfile)->getline;
1250 unlink $tempfile;
1251 _compile_file($cgi, 1) if ($compiled && !$errors);
1252 return $errors ? 0 : 1;
1253 }
1254  
1255 # child
1256 my $fname = _get_file_name($cgi, 1);
1257 unless ($fname || !-s $fname) {
1258 IO::File->new(">$tempfile")->print("Not existed file: $cgi");
1259 exit;
1260 }
1261  
1262 local *NULL;
1263 open NULL, '>', File::Spec->devnull;
1264 open STDOUT, '>&', \*NULL;
1265 open STDERR, '>&', \*NULL;
1266 close STDIN;
1267  
1268 #my $ret = _run_code($sub, {ret_error => 1});
1269 eval { CGI::Compile->compile($fname, "Dancer::Plugin::FakeCGI::_CGIs_::__DUMMY__"); };
1270  
1271 IO::File->new(">$tempfile")->print($@);
1272 exit;
1273 };
1274  
1275 =head2 fake_cgi_bin($code, $patterns, $test_is_perl)
1276  
1277 Automatically serve CGI files from B<cgi-dir> directory
1278  
1279 plugins:
1280 FakeCGI:
1281 cgi-bin_file_pattern: *.cgi
1282  
1283 Setting B<cgi-bin_file_pattern> can be defined as array is pattern of file or files, which will be readed and try to compiled and setted to run as CGI.
1284  
1285 =over
1286  
1287 =item B<$code> - reference for code, if not set, than automatically add servering for given file with this options.
1288  
1289 Given method should return B<true> or B<false>. If given code no return true, than serve given CGI files in standart way.
1290  
1291 This is parametter for given called code:
1292  
1293 =over 3
1294  
1295 =item directory
1296  
1297 =item filename
1298  
1299 =item url
1300  
1301 =item is_perl
1302  
1303 =back
1304  
1305 =item B<$paterns> - is scalar or can be array ref. If not set, than will be set from settings, otherwise read everything which kind of file will be readed
1306  
1307 =item B<$test_is_perl> - test if readable file it is Perl CGI file, if not defined, than we use every file as Perl CGI.
1308  
1309 =back
1310  
1311 =head4 EXAMPLES
1312  
1313 =over
1314  
1315 =item Standart definition in setting file:
1316  
1317 plugins:
1318 FakeCGI:
1319 cgi-bin_file_pattern: "*.pl"
1320  
1321 In yours Dancer package only put C<fake_cgi_bin();> and this script try to load every B<*.pl> files in B<cgi-bin> directory under Dancer directory.
1322  
1323 =item Tested files in own function for every *.pl and *.sh file:
1324  
1325 sub test_file {
1326 my ($cgi_bin, $cgi, $url, $is_perl) = @_;
1327  
1328 return 1 if ($cgi =~ /^\./); # skip serving this file
1329 return 1 if ($cgi =~ /test.pl/); # skip serving this file
1330  
1331 if ($cgi eq "index.pl") { # own serving for given file
1332 any $url => sub {
1333 redirect "/index.sh";
1334 };
1335 return 1;
1336 }
1337  
1338 return 0; # default server
1339 }
1340  
1341 fake_cgi_bin(\&test_file, ["*.pl", "*.sh"], 1);
1342  
1343 =back
1344  
1345 =cut
1346  
1347 register fake_cgi_bin => sub {
1348 my ($self, $code, $patterns, $test_perl_enable) = plugin_args(@_);
1349  
1350 $code = undef if (ref($code) ne "CODE");
1351  
1352 require File::Find::Rule;
1353  
1354 #require List::MoreUtils;
1355 #require File::Spec::Functions;
1356  
1357 _load_settings() unless ($settings);
1358  
1359 $patterns ||= ($settings->{"cgi-bin_file_pattern"} || '*');
1360 $patterns = [$patterns] if not ref $patterns;
1361 for my $pat (@$patterns) {
1362 if ($pat =~ m{^/(.*)/\z}) {
1363 $pat = qr/$1/;
1364 }
1365 }
1366  
1367 my $cgi_bin = _ret_cgi_bin_path();
1368 $cgi_bin .= "/" if ($cgi_bin !~ /\/$/); # Put '/' if directorires is symlink File::Find::Rule can find any files
1369  
1370 foreach my $file (File::Find::Rule->file->name(@$patterns)->in($cgi_bin)) {
1371 my $cgi = File::Spec::Functions::abs2rel($file, $cgi_bin);
1372  
1373 next if (_test_runable($file));
1374  
1375 next if $cgi =~ /\.swp\z/;
1376  
1377 #next if List::MoreUtils::any { $_ eq '.svn' } File::Spec::Functions::splitdir $cgi_path;
1378 #my $path = join '/' => File::Spec::Functions::splitdir($cgi);
1379 #my $action_name = _cgi_action($path);
1380  
1381 my $test = 0;
1382 if ($code) {
1383 my $is_perl = 1;
1384 $is_perl = fake_cgi_is_perl($cgi) if ($test_perl_enable);
1385 $test = &$code($cgi_bin, $cgi, fake_cgi_bin_url($cgi), $is_perl);
1386 }
1387 unless ($test) {
1388 any fake_cgi_bin_url($cgi) => sub {
1389 fake_cgi_file($cgi, {test_is_perl => 1});
1390 fake_cgi_as_string();
1391 };
1392 }
1393 }
1394 };
1395  
1396 =head2 fake_cgi_as_string($ret_ref)
1397  
1398 Return captured strings from CGI, which will be printed to STDOUT.
1399  
1400 If B<$ret_ref> than given string will be returned as reference to SCALAR.
1401 This option can make better performance.
1402  
1403 =cut
1404  
1405 register fake_cgi_as_string => sub {
1406 my ($self, $ret_ref) = plugin_args(@_);
1407  
1408 return "" if (ref($capture) ne "HASH" || !exists($capture->{"STDOUT"}));
1409  
1410 my $ret = "";
1411 if ($capture->{"STDOUT"}->{"string"}) {
1412  
1413 #my $str = $capture->{io_out}->sref;
1414 #return $str ? $$str : "";
1415 $ret = $capture->{"STDOUT"}->{"string"};
1416 } elsif ($capture->{"STDOUT"}->{"io_fh"}) {
1417 my $fh = $capture->{"STDOUT"}->{"io_fh"};
1418 my $curpos = tell($fh);
1419 my $pos = $capture->{"STDOUT"}->{"header_len"} || 0;
1420 seek($fh, $pos > 0 ? $pos : 0, SEEK_SET);
1421 $ret = do { local $/; <$fh>; };
1422 seek($fh, $curpos, SEEK_SET);
1423 }
1424  
1425 if ($ret_ref) {
1426 $ret ||= "";
1427 return \$ret;
1428 }
1429 return $ret || "";
1430 };
1431  
1432 =head2 fake_cgi_capture($capture_start)
1433  
1434 This method every time return actuall settings form capture method.
1435  
1436 If argument B<$capture_start> is defined, can be possible START or STOP capturing with this options:
1437  
1438 =over
1439  
1440 =item B<true|1> - capturing will be initalized or restarted. Every data in restarting will bi appended.
1441  
1442 =item B<false|0> - capturing
1443  
1444 =back
1445  
1446 =head3 RETURN array of this position:
1447  
1448 =over
1449  
1450 =item Hash reference for B<$capture>
1451  
1452 =item L<IO::Scalar> or L<IO::File> of captured STDOUT strings
1453  
1454 =item actual position of seek() - tell() method
1455  
1456 =item size of all data captured from STDOUT in bytes
1457  
1458 =item len of HTTP header. From this position start HTML content
1459  
1460 =back
1461  
1462 =cut
1463  
1464 register fake_cgi_capture => sub {
1465 my ($self, $capture_start) = plugin_args(@_);
1466  
1467 return () if (ref($capture) ne "HASH");
1468  
1469 if (defined($capture_start)) {
1470 if ($capture_start) {
1471 my @a = ();
1472 foreach my $type ("STDOUT", "STDERR") {
1473 push(@a,
1474 (exists($capture->{"STDOUT"}) && ($capture->{"STDOUT"}->{"io_fh"} || $capture->{"STDOUT"}->{"string"}))
1475 ? 1
1476 : 0);
1477 }
1478 _capture_start(@a);
1479 } else {
1480 _capture_end();
1481 }
1482 }
1483  
1484 my $pos = undef;
1485 my $size = undef;
1486 my $fh = undef;
1487 my $header_len = undef;
1488  
1489 if (exists($capture->{"STDOUT"}) && $capture->{"STDOUT"}->{"io_fh"}) {
1490 my $fh = $capture->{"STDOUT"}->{"io_fh"};
1491 $fh->flush();
1492 if ($capture->{"STDOUT"}->{"string"}) {
1493 $size = length($capture->{"STDOUT"}->{"string"});
1494 } else {
1495 $size = ($fh->stat())[7];
1496 }
1497 $pos = tell($fh);
1498 $header_len = $capture->{"STDOUT"}->{"header_len"} || 0;
1499 }
1500  
1501 return $capture, $fh, $pos, $size, $header_len;
1502 };
1503  
1504 =head1 HOOKS
1505  
1506 This plugin uses Dancer's hooks support to allow you to register code that should execute at given times.
1507  
1508 =head3 TYPES
1509  
1510 =over
1511  
1512 =item B<fake_cgi_before($env,$capture)> : hook which will be called before run CGI method or Perl CGI file. Arguments is HASH reference to %ENV and reference to $capture
1513  
1514 =item B<fake_cgi_after($capture)> : hook which will be called after runned CGI method or Perl CGI file. Arguments is reference to $capture
1515  
1516 =back
1517  
1518 =head3 EXAMPLE
1519  
1520 hook 'fake_cgi_before' => sub {
1521 my ($env,$capture) = @_;
1522 };
1523  
1524 hook 'fake_cgi_after' => sub {
1525 my ($capture) = @_;
1526 };
1527  
1528 =cut
1529  
1530 Dancer::Factory::Hook->instance->install_hooks(qw(
1531 fake_cgi_before
1532 fake_cgi_after
1533 ));
1534  
1535 _load_settings() unless ($settings);
1536  
1537 #register_hook(qw());
1538 register_plugin(for_versions => ['1', '2']);
1539  
1540 # Mocking for Multipart* in CGI
1541 package Dancer::Plugin::FakeCGI::MultipartBuffer;
1542 use vars qw(@ISA);
1543 @ISA = qw(MultipartBuffer);
1544  
1545 $Dancer::Plugin::FakeCGI::MultipartBuffer::AutoloadClass = 'MultipartBuffer';
1546 *Dancer::Plugin::FakeCGI::MultipartBuffer::read_from_client = \&Dancer::Plugin::FakeCGI::_cgi_read_from_client;
1547  
1548 1; # End of Dancer::Plugin::FakeCGI
1549 __END__