1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
5 package PublicInbox::GzipFilter;
7 use parent qw(Exporter);
8 use Compress::Raw::Zlib qw(Z_FINISH Z_OK);
9 our @EXPORT_OK = qw(gzf_maybe);
10 my %OPT = (-WindowBits => 15 + 16, -AppendOutput => 1);
11 my @GZIP_HDRS = qw(Vary Accept-Encoding Content-Encoding gzip);
13 sub new { bless {}, shift }
15 # for Qspawn if using $env->{'pi-httpd.async'}
22 # returns `0' and not `undef' on failure (see Www*Stream)
24 my ($res_hdr, $env) = @_;
25 return 0 if (($env->{HTTP_ACCEPT_ENCODING}) // '') !~ /\bgzip\b/;
26 my ($gz, $err) = Compress::Raw::Zlib::Deflate->new(%OPT);
27 return 0 if $err != Z_OK;
29 # in case Plack::Middleware::Deflater is loaded:
30 $env->{'plack.skip-deflater'} = 1;
31 push @$res_hdr, @GZIP_HDRS;
32 bless { gz => $gz }, __PACKAGE__;
36 my ($gz, $err) = Compress::Raw::Zlib::Deflate->new(%OPT);
37 $err == Z_OK or die "Deflate->new failed: $err";
41 # for GetlineBody (via Qspawn) when NOT using $env->{'pi-httpd.async'}
42 # Also used for ->getline callbacks
44 my $self = $_[0]; # $_[1] => input
46 # allocate the zlib context lazily here, instead of in ->new.
47 # Deflate contexts are memory-intensive and this object may
48 # be sitting in the Qspawn limiter queue for a while.
49 my $gz = $self->{gz} //= gzip_or_die();
50 my $zbuf = delete($self->{zbuf});
51 if (defined $_[1]) { # my $buf = $_[1];
52 my $err = $gz->deflate($_[1], $zbuf);
53 die "gzip->deflate: $err" if $err != Z_OK;
54 return $zbuf if length($zbuf) >= 8192;
56 $self->{zbuf} = $zbuf;
58 } else { # undef == EOF
59 my $err = $gz->flush($zbuf, Z_FINISH);
60 die "gzip->flush: $err" if $err != Z_OK;
66 # my $ret = bytes::length($_[1]); # XXX does anybody care?
67 $_[0]->{fh}->write(translate($_[0], $_[1]));
70 # similar to ->translate; use this when we're sure we know we have
71 # more data to buffer after this
73 my $self = $_[0]; # $_[1] => input
74 my $err = $self->{gz}->deflate($_[1], $self->{zbuf});
75 die "gzip->deflate: $err" if $err != Z_OK;
79 # flushes and returns the final bit of gzipped data
81 my $self = $_[0]; # $_[1] => final input (optional)
82 my $zbuf = delete $self->{zbuf};
83 my $gz = delete $self->{gz};
86 $err = $gz->deflate($_[1], $zbuf);
87 die "gzip->deflate: $err" if $err != Z_OK;
89 $err = $gz->flush($zbuf, Z_FINISH);
90 die "gzip->flush: $err" if $err != Z_OK;
96 my $fh = delete $self->{fh};
97 $fh->write(zflush($self));