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::NoopFilter;
21 use PublicInbox::GzipFilter qw(gzf_maybe);
22 use PublicInbox::Hval qw(ascii_html);
24 our @EXPORT_OK = qw(@NO_CACHE r path_info_raw);
26 our @NO_CACHE = ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT',
28 'Cache-Control', 'no-cache, max-age=0, must-revalidate');
33 *{background:#000;color:#ccc}
34 a{color:#69f;text-decoration:none}
37 @media screen AND (prefers-color-scheme:light) {
38 *{background:#fff;color:#333}
39 a{color:#00f;text-decoration:none}
49 my ($code, $msg) = @_;
50 $msg ||= status_message($code);
51 [ $code, [ qw(Content-Type text/plain), 'Content-Length', length($msg),
56 sub getline_response ($$$$$) {
57 my ($env, $in, $off, $len, $path) = @_;
58 my $r = bless {}, __PACKAGE__;
59 if ($env->{'pi-httpd.async'}) { # public-inbox-httpd-only mode
60 $env->{'psgix.no-compress'} = 1; # do not chunk response
61 %$r = ( bypass => [$in, $off, $len, $env->{'psgix.io'}] );
63 %$r = ( in => $in, off => $off, len => $len, path => $path );
69 my ($env, $in, $h, $beg, $end, $size) = @_;
73 if ($end ne '') { # "bytes=-$end" => last N bytes
84 } elsif ($end eq '' || $end >= $size) {
87 } elsif ($end < $size) {
94 $len = $end - $beg + 1;
98 push @$h, qw(Accept-Ranges bytes Content-Range);
99 push @$h, "bytes $beg-$end/$size";
101 # FIXME: Plack::Middleware::Deflater bug?
102 $env->{'psgix.no-compress'} = 1;
106 push @$h, 'Content-Range', "bytes */$size";
107 return [ 416, $h, [] ];
112 # returns a PSGI arrayref response iff .gz and non-.gz mtimes match
113 sub try_gzip_static ($$$$) {
114 my ($env, $h, $path, $type) = @_;
115 return unless ($env->{HTTP_ACCEPT_ENCODING} // '') =~ /\bgzip\b/i;
117 return unless -f $path && defined(($mtime = (stat(_))[9]));
119 return unless -f $gz && (stat(_))[9] == $mtime;
120 my $res = response($env, $h, $gz, $type);
121 return if ($res->[0] > 300 || $res->[0] < 200);
122 push @{$res->[1]}, qw(Cache-Control no-transform
123 Content-Encoding gzip
124 Vary Accept-Encoding);
128 sub response ($$$;$) {
129 my ($env, $h, $path, $type) = @_;
130 $type //= Plack::MIME->mime_type($path) // 'application/octet-stream';
131 if ($path !~ /\.gz\z/i) {
132 if (my $res = try_gzip_static($env, $h, $path, $type)) {
138 if ($env->{REQUEST_METHOD} eq 'HEAD') {
139 return r(404) unless -f $path && -r _; # in case it's a FIFO :P
140 } else { # GET, callers should've already filtered out other methods
141 if (!sysopen($in, $path, O_RDONLY|O_NONBLOCK)) {
142 return r(404) if $! == ENOENT || $! == ENOTDIR;
143 return r(403) if $! == EACCES;
146 return r(404) unless -f $in;
148 my $size = -s _; # bare "_" reuses "struct stat" from "-f" above
149 my $mtime = time2str((stat(_))[9]);
151 if (my $ims = $env->{HTTP_IF_MODIFIED_SINCE}) {
152 return [ 304, [], [] ] if $mtime eq $ims;
157 push @$h, 'Content-Type', $type;
159 if (($env->{HTTP_RANGE} || '') =~ /\bbytes=([0-9]*)-([0-9]*)\z/) {
160 ($code, $off, $len) = setup_range($env, $in, $h, $1, $2, $size);
161 return $code if ref($code);
163 push @$h, 'Content-Length', $len, 'Last-Modified', $mtime;
164 [ $code, $h, $in ? getline_response($env, $in, $off, $len, $path) : [] ]
167 # called by PSGI servers on each response chunk:
171 # avoid buffering, by becoming the buffer! (public-inbox-httpd)
172 if (my $tmpio = delete $self->{bypass}) {
173 my $http = pop @$tmpio; # PublicInbox::HTTP
174 push @{$http->{wbuf}}, $tmpio; # [ $in, $off, $len ]
179 # generic PSGI runs this:
180 my $len = $self->{len} or return; # undef, tells server we're done
182 $n = $len if $len < $n;
183 sysseek($self->{in}, $self->{off}, SEEK_SET) or
184 die "sysseek ($self->{path}): $!";
185 my $r = sysread($self->{in}, my $buf, $n);
186 if (defined $r && $r > 0) { # success!
187 $self->{len} = $len - $r;
191 my $m = defined $r ? "EOF with $len bytes left" : "read error: $!";
192 die "$self->{path} $m, dropping client socket\n";
195 sub close {} # noop, called by PSGI server, just let everything go out-of-scope
197 # OO interface for use as a Plack app
199 my ($class, %opt) = @_;
200 my $index = $opt{'index'} // [ 'index.html' ];
201 $index = [ $index ] if defined($index) && ref($index) ne 'ARRAY';
202 $index = undef if scalar(@$index) == 0;
203 my $style = $opt{style};
204 if (defined $style) {
205 $style = \$style unless ref($style);
207 my $docroot = $opt{docroot};
208 die "`docroot' not set" unless defined($docroot) && $docroot ne '';
212 autoindex => $opt{autoindex},
213 style => $style // \$STYLE,
217 # PATH_INFO is decoded, and we want the undecoded original
219 sub path_info_raw ($) {
221 my $sn = $env->{SCRIPT_NAME};
222 my $re = $path_re_cache{$sn} ||= do {
223 $sn = '/'.$sn unless index($sn, '/') == 0;
225 qr!\A(?:https?://[^/]+)?\Q$sn\E(/[^\?\#]+)!;
227 $env->{REQUEST_URI} =~ $re ? $1 : $env->{PATH_INFO};
230 sub redirect_slash ($) {
232 my $url = $env->{'psgi.url_scheme'} . '://';
233 my $host_port = $env->{HTTP_HOST} //
234 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
235 $url .= $host_port . path_info_raw($env) . '/';
236 my $body = "Redirecting to $url\n";
237 [ 302, [ qw(Content-Type text/plain), 'Location', $url,
238 'Content-Length', length($body) ], [ $body ] ]
244 for my $s (qw(K M G T P)) {
245 last if $size < 1024;
252 sprintf('%lu', $size).$suffix;
255 # by default, this returns "index.html" if it exists for a given directory
256 # It'll generate a directory listing, (autoindex).
257 # May be disabled by setting autoindex => 0
258 sub dir_response ($$$) {
259 my ($self, $env, $fs_path) = @_;
260 if (my $index = $self->{'index'}) { # serve index.html or similar
261 for my $html (@$index) {
262 my $p = $fs_path . $html;
263 my $res = response($env, [], $p);
264 return $res if $res->[0] != 404;
267 return r(404) unless $self->{autoindex};
268 opendir(my $dh, $fs_path) or do {
269 return r(404) if ($! == ENOENT || $! == ENOTDIR);
270 return r(403) if $! == EACCES;
273 my @entries = grep(!/\A\./, readdir($dh));
275 my (%dirs, %other, %want_gz);
276 my $path_info = $env->{PATH_INFO};
277 push @entries, '..' if $path_info ne '/';
278 for my $base (@entries) {
279 my $href = ascii_html(uri_escape_utf8($base));
280 my $name = ascii_html($base);
281 my @st = stat($fs_path . $base) or next; # unlikely
282 my ($gzipped, $uncompressed, $hsize);
289 $dirs{"$base\0$mtime"} = \$entry;
291 $other{"$base\0$mtime"} = \$entry;
292 if ($base !~ /\.gz\z/i) {
293 $want_gz{"$base.gz\0$mtime"} = undef;
295 $hsize = human_size($st[7]);
299 # 54 = 80 - (SP length(strftime(%Y-%m-%d %k:%M)) SP human_size)
300 $hsize = sprintf('% 8s', $hsize);
301 my $pad = 54 - length($name);
302 $pad = 1 if $pad <= 0;
303 $entry .= qq(<a\nhref="$href">$name</a>) . (' ' x $pad);
304 $mtime = strftime('%Y-%m-%d %k:%M', gmtime($mtime));
305 $entry .= $mtime . $hsize;
308 # filter out '.gz' files as long as the mtime matches the
309 # uncompressed version
310 delete(@other{keys %want_gz});
311 @entries = ((map { ${$dirs{$_}} } sort keys %dirs),
312 (map { ${$other{$_}} } sort keys %other));
314 my $path_info_html = ascii_html($path_info);
315 my $h = [qw(Content-Type text/html Content-Length), undef];
316 my $gzf = gzf_maybe($h, $env) || PublicInbox::NoopFilter::new();
317 $gzf->zmore("<html><head><title>Index of $path_info_html</title>" .
319 "</head><body><pre>Index of $path_info_html</pre><hr><pre>\n");
320 $gzf->zmore(join("\n", @entries));
321 my $out = $gzf->zflush("</pre><hr></body></html>\n");
322 $h->[3] = bytes::length($out);
323 [ 200, $h, [ $out ] ]
326 sub call { # PSGI app endpoint
327 my ($self, $env) = @_;
328 return r(405) if $env->{REQUEST_METHOD} !~ /\A(?:GET|HEAD)\z/;
329 my $path_info = $env->{PATH_INFO};
330 return r(403) if index($path_info, "\0") >= 0;
331 my (@parts) = split(m!/+!, $path_info, -1);
332 return r(403) if grep(/\A(?:\.\.)\z/, @parts) || $parts[0] ne '';
334 my $fs_path = join('/', $self->{docroot}, @parts);
335 return dir_response($self, $env, $fs_path) if $parts[-1] eq '';
337 my $res = response($env, [], $fs_path);
338 $res->[0] == 404 && -d $fs_path ? redirect_slash($env) : $res;