File: Static.pm

package info (click to toggle)
libmojolicious-perl 0.999926-1%2Bsqueeze2
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 1,672 kB
  • ctags: 949
  • sloc: perl: 17,391; makefile: 4
file content (323 lines) | stat: -rw-r--r-- 7,567 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
# Copyright (C) 2008-2010, Sebastian Riedel.

package MojoX::Dispatcher::Static;

use strict;
use warnings;

use base 'Mojo::Base';

use File::stat;
use File::Spec;
use Mojo::Asset::File;
use Mojo::Content::Single;
use Mojo::Path;
use MojoX::Types;

__PACKAGE__->attr([qw/prefix root/]);
__PACKAGE__->attr(types => sub { MojoX::Types->new });

# Valentine's Day's coming? Aw crap! I forgot to get a girlfriend again!
sub dispatch {
    my ($self, $c) = @_;

    # Already rendered
    return if $c->res->code;

    # Canonical path
    my $path = $c->req->url->path->clone->canonicalize->to_string;

    # Prefix
    if (my $prefix = $self->prefix) {
        return 1 unless $path =~ s/^$prefix//;
    }

    # Parts
    my @parts = @{Mojo::Path->new->parse($path)->parts};

    # Shortcut
    return 1 unless @parts;

    # Prevent directory traversal
    return 1 if $parts[0] eq '..';

    # Serve static file
    return $self->serve($c, File::Spec->catfile(@parts));
}

sub serve {
    my ($self, $c, $rel) = @_;

    # Append path to root
    my $path = File::Spec->catfile($self->root, split('/', $rel));

    # Extension
    $path =~ /\.(\w+)$/;
    my $ext = $1;

    # Type
    my $type = $self->types->type($ext) || 'text/plain';

    # Dispatch
    if (-f $path) {

        # Log
        $c->app->log->debug(qq/Serving static file "$rel"./);

        my $res = $c->res;
        if (-r $path) {
            my $req  = $c->req;
            my $stat = stat($path);

            # If modified since
            if (my $date = $req->headers->header('If-Modified-Since')) {

                # Not modified
                my $since = Mojo::Date->new($date)->epoch;
                if (defined $since && $since == $stat->mtime) {

                    # Log
                    $c->app->log->debug('File not modified.');

                    $res->code(304);
                    $res->headers->remove('Content-Type');
                    $res->headers->remove('Content-Length');
                    $res->headers->remove('Content-Disposition');
                    return;
                }
            }

            $res->code(200);

            # Partial content
            my $size  = $stat->size;
            my $start = 0;
            my $end   = $size - 1 >= 0 ? $size - 1 : 0;

            if (my $range = $req->headers->header('Range')) {
                if ($range =~ m/^bytes=(\d+)\-(\d+)?/ && $1 <= $end) {
                    $start = $1;
                    $end = $2 if defined $2 && $2 <= $end;
                    $res->code(206);
                    $res->headers->header(
                        'Content-Length' => $end - $start + 1);
                    $res->headers->header(
                        'Content-Range' => "bytes $start-$end/$size");
                    $c->app->log->debug("Range request: $start-$end/$size.");
                }
                else {

                    # Not satisfiable
                    $res->code(416);
                    return;
                }
            }

            # Content
            $res->content(
                Mojo::Content::Single->new(
                    asset => Mojo::Asset::File->new(
                        start_range => $start,
                        end_range   => $end
                    ),
                    headers => $res->headers
                )
            );

            # Accept ranges
            $res->headers->header('Accept-Ranges' => 'bytes');

            # Last modified
            $res->headers->header(
                'Last-Modified' => Mojo::Date->new($stat->mtime));

            $res->headers->content_type($type);
            $res->content->asset->path($path);

            return;
        }

        # Exists, but is forbidden
        else {

            # Log
            $c->app->log->debug('File forbidden.');

            $res->code(403);
            return;
        }
    }

    return 1;
}

sub serve_404 { shift->serve_error(shift, 404) }

sub serve_500 { shift->serve_error(shift, 500) }

sub serve_error {
    my ($self, $c, $code, $rel) = @_;

    # Shortcut
    return 1 unless $c && $code;

    my $res = $c->res;

    # Render once
    return if ($res->code || '') eq $code;

    # Code
    $res->code($code);

    # Default to "code.html"
    $rel ||= "$code.html";

    # Append path to root
    my $path = File::Spec->catfile($self->root, split('/', $rel));

    # File
    if (-r $path) {

        # Log
        $c->app->log->debug(qq/Serving error file "$rel"./);

        # File
        $res->content(
            Mojo::Content::Single->new(asset => Mojo::Asset::File->new));
        $res->content->asset->path($path);

        # Extension
        $path =~ /\.(\w+)$/;
        my $ext = $1;

        # Type
        my $type = $self->types->type($ext) || 'text/plain';
        $res->headers->content_type($type);
    }

    # 404
    elsif ($code == 404) {

        # Log
        $c->app->log->debug('Serving 404 error.');

        $res->headers->content_type('text/html');
        $res->body(<<'EOF');
<!doctype html><html>
    <head><title>File Not Found</title></head>
    <body><h2>File Not Found</h2></body>
</html>
EOF
    }

    # Error
    else {

        # Log
        $c->app->log->debug(qq/Serving error "$code"./);

        $res->headers->content_type('text/html');
        $res->body(<<'EOF');
<!doctype html><html>
    <head><title>Internal Server Error</title></head>
    <body><h2>Internal Server Error</h2></body>
</html>
EOF
    }

    return;
}

1;
__END__

=head1 NAME

MojoX::Dispatcher::Static - Serve Static Files

=head1 SYNOPSIS

    use MojoX::Dispatcher::Static;

    # New dispatcher
    my $dispatcher = MojoX::Dispatcher::Static->new(
        prefix => '/images',
        root   => '/ftp/pub/images'
    );

    # Dispatch
    my $success = $dispatcher->dispatch($c);

=head1 DESCRIPTION

L<MojoX::Dispatcher::Static> is a dispatcher for static files with C<RANGE>
and C<IF-MODIFIED-SINCE> support.

=head1 ATTRIBUTES

L<MojoX::Dispatcher::Static> implements the following attributes.

=head2 C<prefix>

    my $prefix  = $dispatcher->prefix;
    $dispatcher = $dispatcher->prefix('/static');

Prefix path to remove from incoming paths before dispatching.

=head2 C<types>

    my $types   = $dispatcher->types;
    $dispatcher = $dispatcher->types(MojoX::Types->new);

MIME types, by default a L<MojoX::Types> object.

=head2 C<root>

    my $root    = $dispatcher->root;
    $dispatcher = $dispatcher->root('/foo/bar/files');

Directory to serve static files from.

=head1 METHODS

L<MojoX::Dispatcher::Static> inherits all methods from L<Mojo::Base> and
implements the following ones.

=head2 C<dispatch>

    my $success = $dispatcher->dispatch($c);

Dispatch a L<MojoX::Controller> object.

=head2 C<serve>

    my $success = $dispatcher->serve($c, 'foo/bar.html');

Serve a specific file.

=head2 C<serve_404>

    my $success = $dispatcher->serve_404($c);
    my $success = $dispatcher->serve_404($c, '404.html');

Serve a C<404> error page, guaranteed to render at least a default page.

=head2 C<serve_500>

    my $success = $dispatcher->serve_500($c);
    my $success = $dispatcher->serve_500($c, '500.html');

Serve a C<500> error page, guaranteed to render at least a default page.

=head2 C<serve_error>

    my $success = $dispatcher->serve_error($c, 404);
    my $success = $dispatcher->serve_error($c, 404, '404.html');

Serve error page, guaranteed to render at least a default page.

=head1 SEE ALSO

L<Mojolicious>, L<Mojolicious::Guides>, L<http://mojolicious.org>.

=cut