]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WwwStatic.pm
051d2e039b979f3f8b73a6b7aafe4b9f5a0d3d6f
[public-inbox.git] / lib / PublicInbox / WwwStatic.pm
1 # Copyright (C) 2016-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # This package can either be a PSGI response body for a static file
5 # OR a standalone PSGI app which returns the above PSGI response body
6 # (or an HTML directory listing).
7 #
8 # It encapsulates the "autoindex", "index", and "gzip_static"
9 # functionality of nginx.
10 package PublicInbox::WwwStatic;
11 use strict;
12 use parent qw(Exporter);
13 use bytes ();
14 use Fcntl qw(SEEK_SET O_RDONLY O_NONBLOCK);
15 use POSIX qw(strftime);
16 use HTTP::Date qw(time2str);
17 use HTTP::Status qw(status_message);
18 use Errno qw(EACCES ENOTDIR ENOENT);
19 use URI::Escape qw(uri_escape_utf8);
20 use PublicInbox::GzipFilter qw(gzf_maybe);
21 use PublicInbox::Hval qw(ascii_html);
22 use Plack::MIME;
23 our @EXPORT_OK = qw(@NO_CACHE r path_info_raw);
24
25 our @NO_CACHE = ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT',
26                 'Pragma', 'no-cache',
27                 'Cache-Control', 'no-cache, max-age=0, must-revalidate');
28
29 our $STYLE = <<'EOF';
30 <style>
31 @media screen {
32         *{background:#000;color:#ccc}
33         a{color:#69f;text-decoration:none}
34         a:visited{color:#96f}
35 }
36 @media screen AND (prefers-color-scheme:light) {
37         *{background:#fff;color:#333}
38         a{color:#00f;text-decoration:none}
39         a:visited{color:#808}
40 }
41 </style>
42 EOF
43
44 $STYLE =~ s/^\s*//gm;
45 $STYLE =~ tr/\n//d;
46
47 sub r ($;$) {
48         my ($code, $msg) = @_;
49         $msg ||= status_message($code);
50         [ $code, [ qw(Content-Type text/plain), 'Content-Length', length($msg),
51                 @NO_CACHE ],
52           [ $msg ] ]
53 }
54
55 sub getline_response ($$$$$) {
56         my ($env, $in, $off, $len, $path) = @_;
57         my $r = bless {}, __PACKAGE__;
58         if ($env->{'pi-httpd.async'}) { # public-inbox-httpd-only mode
59                 $env->{'psgix.no-compress'} = 1; # do not chunk response
60                 %$r = ( bypass => [$in, $off, $len, $env->{'psgix.io'}] );
61         } else {
62                 %$r = ( in => $in, off => $off, len => $len, path => $path );
63         }
64         $r;
65 }
66
67 sub setup_range {
68         my ($env, $in, $h, $beg, $end, $size) = @_;
69         my $code = 200;
70         my $len = $size;
71         if ($beg eq '') {
72                 if ($end ne '') { # "bytes=-$end" => last N bytes
73                         $beg = $size - $end;
74                         $beg = 0 if $beg < 0;
75                         $end = $size - 1;
76                         $code = 206;
77                 } else {
78                         $code = 416;
79                 }
80         } else {
81                 if ($beg > $size) {
82                         $code = 416;
83                 } elsif ($end eq '' || $end >= $size) {
84                         $end = $size - 1;
85                         $code = 206;
86                 } elsif ($end < $size) {
87                         $code = 206;
88                 } else {
89                         $code = 416;
90                 }
91         }
92         if ($code == 206) {
93                 $len = $end - $beg + 1;
94                 if ($len <= 0) {
95                         $code = 416;
96                 } else {
97                         push @$h, qw(Accept-Ranges bytes Content-Range);
98                         push @$h, "bytes $beg-$end/$size";
99
100                         # FIXME: Plack::Middleware::Deflater bug?
101                         $env->{'psgix.no-compress'} = 1;
102                 }
103         }
104         if ($code == 416) {
105                 push @$h, 'Content-Range', "bytes */$size";
106                 return [ 416, $h, [] ];
107         }
108         ($code, $beg, $len);
109 }
110
111 # returns a PSGI arrayref response iff .gz and non-.gz mtimes match
112 sub try_gzip_static ($$$$) {
113         my ($env, $h, $path, $type) = @_;
114         return unless ($env->{HTTP_ACCEPT_ENCODING} // '') =~ /\bgzip\b/i;
115         my $mtime;
116         return unless -f $path && defined(($mtime = (stat(_))[9]));
117         my $gz = "$path.gz";
118         return unless -f $gz && (stat(_))[9] == $mtime;
119         my $res = response($env, $h, $gz, $type);
120         return if ($res->[0] > 300 || $res->[0] < 200);
121         push @{$res->[1]}, qw(Cache-Control no-transform
122                                 Content-Encoding gzip
123                                 Vary Accept-Encoding);
124         $res;
125 }
126
127 sub response ($$$;$) {
128         my ($env, $h, $path, $type) = @_;
129         $type //= Plack::MIME->mime_type($path) // 'application/octet-stream';
130         if ($path !~ /\.gz\z/i) {
131                 if (my $res = try_gzip_static($env, $h, $path, $type)) {
132                         return $res;
133                 }
134         }
135
136         my $in;
137         if ($env->{REQUEST_METHOD} eq 'HEAD') {
138                 return r(404) unless -f $path && -r _; # in case it's a FIFO :P
139         } else { # GET, callers should've already filtered out other methods
140                 if (!sysopen($in, $path, O_RDONLY|O_NONBLOCK)) {
141                         return r(404) if $! == ENOENT || $! == ENOTDIR;
142                         return r(403) if $! == EACCES;
143                         return r(500);
144                 }
145                 return r(404) unless -f $in;
146         }
147         my $size = -s _; # bare "_" reuses "struct stat" from "-f" above
148         my $mtime = time2str((stat(_))[9]);
149
150         if (my $ims = $env->{HTTP_IF_MODIFIED_SINCE}) {
151                 return [ 304, [], [] ] if $mtime eq $ims;
152         }
153
154         my $len = $size;
155         my $code = 200;
156         push @$h, 'Content-Type', $type;
157         my $off = 0;
158         if (($env->{HTTP_RANGE} || '') =~ /\bbytes=([0-9]*)-([0-9]*)\z/) {
159                 ($code, $off, $len) = setup_range($env, $in, $h, $1, $2, $size);
160                 return $code if ref($code);
161         }
162         push @$h, 'Content-Length', $len, 'Last-Modified', $mtime;
163         [ $code, $h, $in ? getline_response($env, $in, $off, $len, $path) : [] ]
164 }
165
166 # called by PSGI servers on each response chunk:
167 sub getline {
168         my ($self) = @_;
169
170         # avoid buffering, by becoming the buffer! (public-inbox-httpd)
171         if (my $tmpio = delete $self->{bypass}) {
172                 my $http = pop @$tmpio; # PublicInbox::HTTP
173                 push @{$http->{wbuf}}, $tmpio; # [ $in, $off, $len ]
174                 $http->flush_write;
175                 return; # undef, EOF
176         }
177
178         # generic PSGI runs this:
179         my $len = $self->{len} or return; # undef, tells server we're done
180         my $n = 8192;
181         $n = $len if $len < $n;
182         sysseek($self->{in}, $self->{off}, SEEK_SET) or
183                         die "sysseek ($self->{path}): $!";
184         my $r = sysread($self->{in}, my $buf, $n);
185         if (defined $r && $r > 0) { # success!
186                 $self->{len} = $len - $r;
187                 $self->{off} += $r;
188                 return $buf;
189         }
190         my $m = defined $r ? "EOF with $len bytes left" : "read error: $!";
191         die "$self->{path} $m, dropping client socket\n";
192 }
193
194 sub close {} # noop, called by PSGI server, just let everything go out-of-scope
195
196 # OO interface for use as a Plack app
197 sub new {
198         my ($class, %opt) = @_;
199         my $index = $opt{'index'} // [ 'index.html' ];
200         $index = [ $index ] if defined($index) && ref($index) ne 'ARRAY';
201         $index = undef if scalar(@$index) == 0;
202         my $style = $opt{style};
203         if (defined $style) {
204                 $style = \$style unless ref($style);
205         }
206         my $docroot = $opt{docroot};
207         die "`docroot' not set" unless defined($docroot) && $docroot ne '';
208         bless {
209                 docroot => $docroot,
210                 index => $index,
211                 autoindex => $opt{autoindex},
212                 style => $style // \$STYLE,
213         }, $class;
214 }
215
216 # PATH_INFO is decoded, and we want the undecoded original
217 my %path_re_cache;
218 sub path_info_raw ($) {
219         my ($env) = @_;
220         my $sn = $env->{SCRIPT_NAME};
221         my $re = $path_re_cache{$sn} ||= do {
222                 $sn = '/'.$sn unless index($sn, '/') == 0;
223                 $sn =~ s!/\z!!;
224                 qr!\A(?:https?://[^/]+)?\Q$sn\E(/[^\?\#]+)!;
225         };
226         $env->{REQUEST_URI} =~ $re ? $1 : $env->{PATH_INFO};
227 }
228
229 sub redirect_slash ($) {
230         my ($env) = @_;
231         my $url = $env->{'psgi.url_scheme'} . '://';
232         my $host_port = $env->{HTTP_HOST} //
233                 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
234         $url .= $host_port . path_info_raw($env) . '/';
235         my $body = "Redirecting to $url\n";
236         [ 302, [ qw(Content-Type text/plain), 'Location', $url,
237                 'Content-Length', length($body) ], [ $body ] ]
238 }
239
240 sub human_size ($) {
241         my ($size) = @_;
242         my $suffix = '';
243         for my $s (qw(K M G T P)) {
244                 last if $size < 1024;
245                 $size /= 1024;
246                 if ($size <= 1024) {
247                         $suffix = $s;
248                         last;
249                 }
250         }
251         sprintf('%lu', $size).$suffix;
252 }
253
254 # by default, this returns "index.html" if it exists for a given directory
255 # It'll generate a directory listing, (autoindex).
256 # May be disabled by setting autoindex => 0
257 sub dir_response ($$$) {
258         my ($self, $env, $fs_path) = @_;
259         if (my $index = $self->{'index'}) { # serve index.html or similar
260                 for my $html (@$index) {
261                         my $p = $fs_path . $html;
262                         my $res = response($env, [], $p);
263                         return $res if $res->[0] != 404;
264                 }
265         }
266         return r(404) unless $self->{autoindex};
267         opendir(my $dh, $fs_path) or do {
268                 return r(404) if ($! == ENOENT || $! == ENOTDIR);
269                 return r(403) if $! == EACCES;
270                 return r(500);
271         };
272         my @entries = grep(!/\A\./, readdir($dh));
273         $dh = undef;
274         my (%dirs, %other, %want_gz);
275         my $path_info = $env->{PATH_INFO};
276         push @entries, '..' if $path_info ne '/';
277         for my $base (@entries) {
278                 my $href = ascii_html(uri_escape_utf8($base));
279                 my $name = ascii_html($base);
280                 my @st = stat($fs_path . $base) or next; # unlikely
281                 my ($gzipped, $uncompressed, $hsize);
282                 my $entry = '';
283                 my $mtime = $st[9];
284                 if (-d _) {
285                         $href .= '/';
286                         $name .= '/';
287                         $hsize = '-';
288                         $dirs{"$base\0$mtime"} = \$entry;
289                 } elsif (-f _) {
290                         $other{"$base\0$mtime"} = \$entry;
291                         if ($base !~ /\.gz\z/i) {
292                                 $want_gz{"$base.gz\0$mtime"} = undef;
293                         }
294                         $hsize = human_size($st[7]);
295                 } else {
296                         next;
297                 }
298                 # 54 = 80 - (SP length(strftime(%Y-%m-%d %k:%M)) SP human_size)
299                 $hsize = sprintf('% 8s', $hsize);
300                 my $pad = 54 - length($name);
301                 $pad = 1 if $pad <= 0;
302                 $entry .= qq(<a\nhref="$href">$name</a>) . (' ' x $pad);
303                 $mtime = strftime('%Y-%m-%d %k:%M', gmtime($mtime));
304                 $entry .= $mtime . $hsize;
305         }
306
307         # filter out '.gz' files as long as the mtime matches the
308         # uncompressed version
309         delete(@other{keys %want_gz});
310         @entries = ((map { ${$dirs{$_}} } sort keys %dirs),
311                         (map { ${$other{$_}} } sort keys %other));
312
313         my $path_info_html = ascii_html($path_info);
314         my $h = [qw(Content-Type text/html Content-Length), undef];
315         my $gzf = gzf_maybe($h, $env);
316         $gzf->zmore("<html><head><title>Index of $path_info_html</title>" .
317                 ${$self->{style}} .
318                 "</head><body><pre>Index of $path_info_html</pre><hr><pre>\n");
319         $gzf->zmore(join("\n", @entries));
320         my $out = $gzf->zflush("</pre><hr></body></html>\n");
321         $h->[3] = bytes::length($out);
322         [ 200, $h, [ $out ] ]
323 }
324
325 sub call { # PSGI app endpoint
326         my ($self, $env) = @_;
327         return r(405) if $env->{REQUEST_METHOD} !~ /\A(?:GET|HEAD)\z/;
328         my $path_info = $env->{PATH_INFO};
329         return r(403) if index($path_info, "\0") >= 0;
330         my (@parts) = split(m!/+!, $path_info, -1);
331         return r(403) if grep(/\A(?:\.\.)\z/, @parts) || $parts[0] ne '';
332
333         my $fs_path = join('/', $self->{docroot}, @parts);
334         return dir_response($self, $env, $fs_path) if $parts[-1] eq '';
335
336         my $res = response($env, [], $fs_path);
337         $res->[0] == 404 && -d $fs_path ? redirect_slash($env) : $res;
338 }
339
340 1;