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;
54 sysseek($in, $beg, SEEK_SET) or return r(500);
55 push @$h, qw(Accept-Ranges bytes Content-Range);
56 push @$h, "bytes $beg-$end/$size";
58 # FIXME: Plack::Middleware::Deflater bug?
59 $env->{'psgix.no-compress'} = 1;
63 push @$h, 'Content-Range', "bytes */$size";
64 return [ 416, $h, [] ];
70 my ($env, $h, $path, $type) = @_;
71 return r(404) unless -f $path && -r _; # just in case it's a FIFO :P
73 open my $in, '<', $path or return;
75 my $mtime = time2str((stat(_))[9]);
77 if (my $ims = $env->{HTTP_IF_MODIFIED_SINCE}) {
78 return [ 304, [], [] ] if $mtime eq $ims;
83 push @$h, 'Content-Type', $type;
84 if (($env->{HTTP_RANGE} || '') =~ /\bbytes=([0-9]*)-([0-9]*)\z/) {
85 ($code, $len) = prepare_range($env, $in, $h, $1, $2, $size);
86 return $code if ref($code);
88 push @$h, 'Content-Length', $len, 'Last-Modified', $mtime;
99 # called by PSGI servers:
102 my $len = $self->{len} or return; # undef, tells server we're done
103 my $n = delete($self->{initial_rd}) // 8192;
104 $n = $len if $len < $n;
105 my $r = sysread($self->{in}, my $buf, $n);
106 if (defined $r && $r > 0) { # success!
107 $self->{len} = $len - $r;
110 my $m = defined $r ? "EOF with $len bytes left" : "read error: $!";
111 my $env = $self->{env};
112 $env->{'psgi.errors'}->print("$self->{path} $m\n");
114 # drop the client on error
115 if (my $io = $env->{'psgix.io'}) {
116 $io->close; # this is likely PublicInbox::DS::close
117 } else { # for some PSGI servers w/o psgix.io
118 die "dropping client socket\n";
123 sub close {} # noop, just let everything go out-of-scope