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