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>
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).
8 # It encapsulates the "autoindex", "index", and "gzip_static"
9 # functionality of nginx.
10 package PublicInbox::WwwStatic;
12 use parent qw(Exporter);
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);
23 our @EXPORT_OK = qw(@NO_CACHE r path_info_raw);
25 our @NO_CACHE = ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT',
27 'Cache-Control', 'no-cache, max-age=0, must-revalidate');
32 *{background:#000;color:#ccc}
33 a{color:#69f;text-decoration:none}
36 @media screen AND (prefers-color-scheme:light) {
37 *{background:#fff;color:#333}
38 a{color:#00f;text-decoration:none}
48 my ($code, $msg) = @_;
49 $msg ||= status_message($code);
50 [ $code, [ qw(Content-Type text/plain), 'Content-Length', length($msg),
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'}] );
62 %$r = ( in => $in, off => $off, len => $len, path => $path );
68 my ($env, $in, $h, $beg, $end, $size) = @_;
72 if ($end ne '') { # "bytes=-$end" => last N bytes
83 } elsif ($end eq '' || $end >= $size) {
86 } elsif ($end < $size) {
93 $len = $end - $beg + 1;
97 push @$h, qw(Accept-Ranges bytes Content-Range);
98 push @$h, "bytes $beg-$end/$size";
100 # FIXME: Plack::Middleware::Deflater bug?
101 $env->{'psgix.no-compress'} = 1;
105 push @$h, 'Content-Range', "bytes */$size";
106 return [ 416, $h, [] ];
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;
116 return unless -f $path && defined(($mtime = (stat(_))[9]));
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);
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)) {
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;
145 return r(404) unless -f $in;
147 my $size = -s _; # bare "_" reuses "struct stat" from "-f" above
148 my $mtime = time2str((stat(_))[9]);
150 if (my $ims = $env->{HTTP_IF_MODIFIED_SINCE}) {
151 return [ 304, [], [] ] if $mtime eq $ims;
156 push @$h, 'Content-Type', $type;
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);
162 push @$h, 'Content-Length', $len, 'Last-Modified', $mtime;
163 [ $code, $h, $in ? getline_response($env, $in, $off, $len, $path) : [] ]
166 # called by PSGI servers on each response chunk:
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 ]
178 # generic PSGI runs this:
179 my $len = $self->{len} or return; # undef, tells server we're done
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;
190 my $m = defined $r ? "EOF with $len bytes left" : "read error: $!";
191 die "$self->{path} $m, dropping client socket\n";
194 sub close {} # noop, called by PSGI server, just let everything go out-of-scope
196 # OO interface for use as a Plack app
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);
206 my $docroot = $opt{docroot};
207 die "`docroot' not set" unless defined($docroot) && $docroot ne '';
211 autoindex => $opt{autoindex},
212 style => $style // \$STYLE,
216 # PATH_INFO is decoded, and we want the undecoded original
218 sub path_info_raw ($) {
220 my $sn = $env->{SCRIPT_NAME};
221 my $re = $path_re_cache{$sn} ||= do {
222 $sn = '/'.$sn unless index($sn, '/') == 0;
224 qr!\A(?:https?://[^/]+)?\Q$sn\E(/[^\?\#]+)!;
226 $env->{REQUEST_URI} =~ $re ? $1 : $env->{PATH_INFO};
229 sub redirect_slash ($) {
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 ] ]
243 for my $s (qw(K M G T P)) {
244 last if $size < 1024;
251 sprintf('%lu', $size).$suffix;
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;
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;
272 my @entries = grep(!/\A\./, readdir($dh));
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);
288 $dirs{"$base\0$mtime"} = \$entry;
290 $other{"$base\0$mtime"} = \$entry;
291 if ($base !~ /\.gz\z/i) {
292 $want_gz{"$base.gz\0$mtime"} = undef;
294 $hsize = human_size($st[7]);
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;
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));
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>" .
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 ] ]
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 '';
333 my $fs_path = join('/', $self->{docroot}, @parts);
334 return dir_response($self, $env, $fs_path) if $parts[-1] eq '';
336 my $res = response($env, [], $fs_path);
337 $res->[0] == 404 && -d $fs_path ? redirect_slash($env) : $res;