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 package PublicInbox::WwwStatic;
6 use parent qw(Exporter);
7 use Fcntl qw(SEEK_SET O_RDONLY O_NONBLOCK);
8 use HTTP::Date qw(time2str);
9 use HTTP::Status qw(status_message);
10 use Errno qw(EACCES ENOTDIR ENOENT);
11 our @EXPORT_OK = qw(@NO_CACHE r);
13 our @NO_CACHE = ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT',
15 'Cache-Control', 'no-cache, max-age=0, must-revalidate');
18 my ($code, $msg) = @_;
19 $msg ||= status_message($code);
20 [ $code, [ qw(Content-Type text/plain), 'Content-Length', length($msg),
26 my ($env, $in, $h, $beg, $end, $size) = @_;
30 if ($end ne '') { # "bytes=-$end" => last N bytes
41 } elsif ($end eq '' || $end >= $size) {
44 } elsif ($end < $size) {
51 $len = $end - $beg + 1;
56 sysseek($in, $beg, SEEK_SET) or return r(500);
58 push @$h, qw(Accept-Ranges bytes Content-Range);
59 push @$h, "bytes $beg-$end/$size";
61 # FIXME: Plack::Middleware::Deflater bug?
62 $env->{'psgix.no-compress'} = 1;
66 push @$h, 'Content-Range', "bytes */$size";
67 return [ 416, $h, [] ];
73 my ($env, $h, $path, $type) = @_;
76 if ($env->{REQUEST_METHOD} eq 'HEAD') {
77 return r(404) unless -f $path && -r _; # in case it's a FIFO :P
78 } else { # GET, callers should've already filtered out other methods
79 if (!sysopen($in, $path, O_RDONLY|O_NONBLOCK)) {
80 return r(404) if $! == ENOENT || $! == ENOTDIR;
81 return r(403) if $! == EACCES;
84 return r(404) unless -f $in;
86 my $size = -s _; # bare "_" reuses "struct stat" from "-f" above
87 my $mtime = time2str((stat(_))[9]);
89 if (my $ims = $env->{HTTP_IF_MODIFIED_SINCE}) {
90 return [ 304, [], [] ] if $mtime eq $ims;
95 push @$h, 'Content-Type', $type;
96 if (($env->{HTTP_RANGE} || '') =~ /\bbytes=([0-9]*)-([0-9]*)\z/) {
97 ($code, $len) = prepare_range($env, $in, $h, $1, $2, $size);
98 return $code if ref($code);
100 push @$h, 'Content-Length', $len, 'Last-Modified', $mtime;
101 my $body = $in ? bless {
108 [ $code, $h, $body ];
111 # called by PSGI servers:
114 my $len = $self->{len} or return; # undef, tells server we're done
115 my $n = delete($self->{initial_rd}) // 8192;
116 $n = $len if $len < $n;
117 my $r = sysread($self->{in}, my $buf, $n);
118 if (defined $r && $r > 0) { # success!
119 $self->{len} = $len - $r;
122 my $m = defined $r ? "EOF with $len bytes left" : "read error: $!";
123 my $env = $self->{env};
124 $env->{'psgi.errors'}->print("$self->{path} $m\n");
126 # drop the client on error
127 if (my $io = $env->{'psgix.io'}) {
128 $io->close; # this is likely PublicInbox::DS::close
129 } else { # for some PSGI servers w/o psgix.io
130 die "dropping client socket\n";
135 sub close {} # noop, just let everything go out-of-scope