1 # Copyright (C) 2016-2019 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::Hval qw(ascii_html);
22 our @EXPORT_OK = qw(@NO_CACHE r path_info_raw);
24 our @NO_CACHE = ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT',
26 'Cache-Control', 'no-cache, max-age=0, must-revalidate');
31 *{background:#000;color:#ccc}
32 a{color:#69f;text-decoration:none}
35 @media screen AND (prefers-color-scheme:light) {
36 *{background:#fff;color:#333}
37 a{color:#00f;text-decoration:none}
47 my ($code, $msg) = @_;
48 $msg ||= status_message($code);
49 [ $code, [ qw(Content-Type text/plain), 'Content-Length', length($msg),
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'}] );
61 %$r = ( in => $in, off => $off, len => $len, path => $path );
67 my ($env, $in, $h, $beg, $end, $size) = @_;
71 if ($end ne '') { # "bytes=-$end" => last N bytes
82 } elsif ($end eq '' || $end >= $size) {
85 } elsif ($end < $size) {
92 $len = $end - $beg + 1;
96 push @$h, qw(Accept-Ranges bytes Content-Range);
97 push @$h, "bytes $beg-$end/$size";
99 # FIXME: Plack::Middleware::Deflater bug?
100 $env->{'psgix.no-compress'} = 1;
104 push @$h, 'Content-Range', "bytes */$size";
105 return [ 416, $h, [] ];
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;
115 return unless -f $path && defined(($mtime = (stat(_))[9]));
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 Content-Encoding gzip);
124 sub response ($$$;$) {
125 my ($env, $h, $path, $type) = @_;
126 $type //= Plack::MIME->mime_type($path) // 'application/octet-stream';
127 if ($path !~ /\.gz\z/i) {
128 if (my $res = try_gzip_static($env, $h, $path, $type)) {
134 if ($env->{REQUEST_METHOD} eq 'HEAD') {
135 return r(404) unless -f $path && -r _; # in case it's a FIFO :P
136 } else { # GET, callers should've already filtered out other methods
137 if (!sysopen($in, $path, O_RDONLY|O_NONBLOCK)) {
138 return r(404) if $! == ENOENT || $! == ENOTDIR;
139 return r(403) if $! == EACCES;
142 return r(404) unless -f $in;
144 my $size = -s _; # bare "_" reuses "struct stat" from "-f" above
145 my $mtime = time2str((stat(_))[9]);
147 if (my $ims = $env->{HTTP_IF_MODIFIED_SINCE}) {
148 return [ 304, [], [] ] if $mtime eq $ims;
153 push @$h, 'Content-Type', $type;
155 if (($env->{HTTP_RANGE} || '') =~ /\bbytes=([0-9]*)-([0-9]*)\z/) {
156 ($code, $off, $len) = setup_range($env, $in, $h, $1, $2, $size);
157 return $code if ref($code);
159 push @$h, 'Content-Length', $len, 'Last-Modified', $mtime;
160 [ $code, $h, $in ? getline_response($env, $in, $off, $len, $path) : [] ]
163 # called by PSGI servers on each response chunk:
167 # avoid buffering, by becoming the buffer! (public-inbox-httpd)
168 if (my $tmpio = delete $self->{bypass}) {
169 my $http = pop @$tmpio; # PublicInbox::HTTP
170 push @{$http->{wbuf}}, $tmpio; # [ $in, $off, $len ]
175 # generic PSGI runs this:
176 my $len = $self->{len} or return; # undef, tells server we're done
178 $n = $len if $len < $n;
179 sysseek($self->{in}, $self->{off}, SEEK_SET) or
180 die "sysseek ($self->{path}): $!";
181 my $r = sysread($self->{in}, my $buf, $n);
182 if (defined $r && $r > 0) { # success!
183 $self->{len} = $len - $r;
187 my $m = defined $r ? "EOF with $len bytes left" : "read error: $!";
188 die "$self->{path} $m, dropping client socket\n";
191 sub close {} # noop, called by PSGI server, just let everything go out-of-scope
193 # OO interface for use as a Plack app
195 my ($class, %opt) = @_;
196 my $index = $opt{'index'} // [ 'index.html' ];
197 $index = [ $index ] if defined($index) && ref($index) ne 'ARRAY';
198 $index = undef if scalar(@$index) == 0;
199 my $style = $opt{style};
200 if (defined $style) {
201 $style = \$style unless ref($style);
203 my $docroot = $opt{docroot};
204 die "`docroot' not set" unless defined($docroot) && $docroot ne '';
208 autoindex => $opt{autoindex},
209 style => $style // \$STYLE,
213 # PATH_INFO is decoded, and we want the undecoded original
215 sub path_info_raw ($) {
217 my $sn = $env->{SCRIPT_NAME};
218 my $re = $path_re_cache{$sn} ||= do {
219 $sn = '/'.$sn unless index($sn, '/') == 0;
221 qr!\A(?:https?://[^/]+)?\Q$sn\E(/[^\?\#]+)!;
223 $env->{REQUEST_URI} =~ $re ? $1 : $env->{PATH_INFO};
226 sub redirect_slash ($) {
228 my $url = $env->{'psgi.url_scheme'} . '://';
229 my $host_port = $env->{HTTP_HOST} //
230 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
231 $url .= $host_port . path_info_raw($env) . '/';
232 my $body = "Redirecting to $url\n";
233 [ 302, [ qw(Content-Type text/plain), 'Location', $url,
234 'Content-Length', length($body) ], [ $body ] ]
240 for my $s (qw(K M G T P)) {
241 last if $size < 1024;
248 sprintf('%lu', $size).$suffix;
251 # by default, this returns "index.html" if it exists for a given directory
252 # It'll generate a directory listing, (autoindex).
253 # May be disabled by setting autoindex => 0
254 sub dir_response ($$$) {
255 my ($self, $env, $fs_path) = @_;
256 if (my $index = $self->{'index'}) { # serve index.html or similar
257 for my $html (@$index) {
258 my $p = $fs_path . $html;
259 my $res = response($env, [], $p);
260 return $res if $res->[0] != 404;
263 return r(404) unless $self->{autoindex};
264 opendir(my $dh, $fs_path) or do {
265 return r(404) if ($! == ENOENT || $! == ENOTDIR);
266 return r(403) if $! == EACCES;
269 my @entries = grep(!/\A\./, readdir($dh));
271 my (%dirs, %other, %want_gz);
272 my $path_info = $env->{PATH_INFO};
273 push @entries, '..' if $path_info ne '/';
274 for my $base (@entries) {
275 my $href = ascii_html(uri_escape_utf8($base));
276 my $name = ascii_html($base);
277 my @st = stat($fs_path . $base) or next; # unlikely
278 my ($gzipped, $uncompressed, $hsize);
285 $dirs{"$base\0$mtime"} = \$entry;
287 $other{"$base\0$mtime"} = \$entry;
288 if ($base !~ /\.gz\z/i) {
289 $want_gz{"$base.gz\0$mtime"} = undef;
291 $hsize = human_size($st[7]);
295 # 54 = 80 - (SP length(strftime(%Y-%m-%d %k:%M)) SP human_size)
296 $hsize = sprintf('% 8s', $hsize);
297 my $pad = 54 - length($name);
298 $pad = 1 if $pad <= 0;
299 $entry .= qq(<a\nhref="$href">$name</a>) . (' ' x $pad);
300 $mtime = strftime('%Y-%m-%d %k:%M', gmtime($mtime));
301 $entry .= $mtime . $hsize;
304 # filter out '.gz' files as long as the mtime matches the
305 # uncompressed version
306 delete(@other{keys %want_gz});
307 @entries = ((map { ${$dirs{$_}} } sort keys %dirs),
308 (map { ${$other{$_}} } sort keys %other));
310 my $path_info_html = ascii_html($path_info);
311 my $body = "<html><head><title>Index of $path_info_html</title>" .
313 "</head><body><pre>Index of $path_info_html</pre><hr><pre>\n";
314 $body .= join("\n", @entries) . "</pre><hr></body></html>\n";
315 [ 200, [ qw(Content-Type text/html
316 Content-Length), bytes::length($body) ], [ $body ] ]
319 sub call { # PSGI app endpoint
320 my ($self, $env) = @_;
321 return r(405) if $env->{REQUEST_METHOD} !~ /\A(?:GET|HEAD)\z/;
322 my $path_info = $env->{PATH_INFO};
323 return r(403) if index($path_info, "\0") >= 0;
324 my (@parts) = split(m!/+!, $path_info, -1);
325 return r(403) if grep(/\A(?:\.\.)\z/, @parts) || $parts[0] ne '';
327 my $fs_path = join('/', $self->{docroot}, @parts);
328 return dir_response($self, $env, $fs_path) if $parts[-1] eq '';
330 my $res = response($env, [], $fs_path);
331 $res->[0] == 404 && -d $fs_path ? redirect_slash($env) : $res;