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);
8 use HTTP::Date qw(time2str);
9 use HTTP::Status qw(status_message);
10 our @EXPORT_OK = qw(@NO_CACHE r);
12 our @NO_CACHE = ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT',
14 'Cache-Control', 'no-cache, max-age=0, must-revalidate');
17 my ($code, $msg) = @_;
18 $msg ||= status_message($code);
19 [ $code, [ qw(Content-Type text/plain), 'Content-Length', length($msg),
25 my ($env, $in, $h, $beg, $end, $size) = @_;
29 if ($end ne '') { # "bytes=-$end" => last N bytes
40 } elsif ($end eq '' || $end >= $size) {
43 } elsif ($end < $size) {
50 $len = $end - $beg + 1;
55 sysseek($in, $beg, SEEK_SET) or return r(500);
57 push @$h, qw(Accept-Ranges bytes Content-Range);
58 push @$h, "bytes $beg-$end/$size";
60 # FIXME: Plack::Middleware::Deflater bug?
61 $env->{'psgix.no-compress'} = 1;
65 push @$h, 'Content-Range', "bytes */$size";
66 return [ 416, $h, [] ];
72 my ($env, $h, $path, $type) = @_;
73 return r(404) unless -f $path && -r _; # just in case it's a FIFO :P
76 if ($env->{REQUEST_METHOD} eq 'HEAD') {
78 } else { # GET, callers should've already filtered out other methods
79 open $in, '<', $path or return r(403);
82 my $mtime = time2str((stat(_))[9]);
84 if (my $ims = $env->{HTTP_IF_MODIFIED_SINCE}) {
85 return [ 304, [], [] ] if $mtime eq $ims;
90 push @$h, 'Content-Type', $type;
91 if (($env->{HTTP_RANGE} || '') =~ /\bbytes=([0-9]*)-([0-9]*)\z/) {
92 ($code, $len) = prepare_range($env, $in, $h, $1, $2, $size);
93 return $code if ref($code);
95 push @$h, 'Content-Length', $len, 'Last-Modified', $mtime;
96 my $body = $in ? bless {
103 [ $code, $h, $body ];
106 # called by PSGI servers:
109 my $len = $self->{len} or return; # undef, tells server we're done
110 my $n = delete($self->{initial_rd}) // 8192;
111 $n = $len if $len < $n;
112 my $r = sysread($self->{in}, my $buf, $n);
113 if (defined $r && $r > 0) { # success!
114 $self->{len} = $len - $r;
117 my $m = defined $r ? "EOF with $len bytes left" : "read error: $!";
118 my $env = $self->{env};
119 $env->{'psgi.errors'}->print("$self->{path} $m\n");
121 # drop the client on error
122 if (my $io = $env->{'psgix.io'}) {
123 $io->close; # this is likely PublicInbox::DS::close
124 } else { # for some PSGI servers w/o psgix.io
125 die "dropping client socket\n";
130 sub close {} # noop, just let everything go out-of-scope