AppServer/Plugin/FileRetriever.pm untested

filter: Statementstmt 0.0% 0 / 53 Branchbran 0.0% 0 / 8 Conditioncond 0.0% 0 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 0.0% 0 / 10 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 78 CC 5 SCAR 20.4
CC
5
Cov
0%
_handle_file
20.0
init
6.0
BEGIN
2.0
CRAP 7.7
1 package HTTP::AppServer::Plugin::FileRetriever;
2 # Plugin for HTTP::AppServer that retrieves files from a document root.
3 # 2010 by Tom Kirchner
4  
5 use 5.010000;
6 use strict;
7 use warnings;
8 use IO::File;
9 use JSON;
10 use Path::Trim;
11 use HTTP::AppServer::Plugin;
12 use base qw(HTTP::AppServer::Plugin);
13  
14 our $VERSION = '0.01';
15  
16 # document root for file retrieval
17 my $DocRoot = '/tmp';
18  
19 # all the mimetypes of files handled by the plugin
20 my $MimeTypes = {
21 'html' => 'text/html',
22 'css' => 'text/css',
23 'js' => 'text/javascript',
24 'png' => 'image/png',
25 'jpg' => 'image/jpg',
26 'jpeg' => 'image/jpg',
27 'gif' => 'image/gif',
28 };
29  
30 my $PathTrimmer = Path::Trim->new();
31  
32 # called by the server when the plugin is installed
33 # to determine which routes are handled by the plugin
34 sub init
35 {
36 my ($class, $server, %options) = @_;
37  
38 $PathTrimmer->set_directory_separator('/');
39  
40 # analyse options
41 $DocRoot = $options{'DocRoot'} if exists $options{'DocRoot'};
42  
43 # install properties in server
44 $server->set('mimetypes', $MimeTypes);
45 $server->set('docroot', $DocRoot);
46  
47 return (
48 # handle file (and directory) requests
49 '^\/(.*)$' => \&_handle_file,
50 );
51 }
52  
53 sub _handle_file
54 {
55 my ($server, $cgi, $filename) = @_;
56  
57 $filename = $server->docroot().'/'.$filename;
58 $filename = $PathTrimmer->trim_path($filename);
59  
60 my $answer;
61 my $mimetype = 'text/html';
62 my $docroot_regex = quotemeta $server->docroot();
63 if (!-f $filename) {
64 $server->errorpage(404);
65 }
66 elsif ($filename =~ /^$docroot_regex/) {
67 my ($fileending) = $filename =~ /^.*\.([a-zA-Z0-9]+)$/i;
68 if (defined $fileending && exists $server->mimetypes()->{$fileending}) {
69 $mimetype = $server->mimetypes()->{$fileending};
70 my $fh = IO::File->new('< '.$filename);
71 print "HTTP/1.0 200 Ok\r\n";
72 print $cgi->header($mimetype);
73 print join '', <$fh>;
74 } else {
75 $server->errorpage(404);
76 }
77 }
78 else {
79 $server->errorpage(404);
80 }
81 }
82  
83 1;
84 __END__