Skip to content

Commit

Permalink
Fixed a bug in Dechunk middleware where the parsing stalls when a
Browse files Browse the repository at this point in the history
buffer length is shorter than the chunked length.

Also fixes a Auto temporary buffer bug it saves into a temporary file
multiple times.
  • Loading branch information
miyagawa committed Feb 9, 2010
1 parent 1b2e27e commit 82121a7
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 11 deletions.
17 changes: 12 additions & 5 deletions lib/Plack/Middleware/Dechunk.pm
Expand Up @@ -25,11 +25,18 @@ sub dechunk_input {

DECHUNK:
while (1) {
my $read = $env->{'psgi.input'}->read(my $chunk_buffer, CHUNK_SIZE, length $chunk_buffer);

while ( $chunk_buffer =~ s/^([0-9a-fA-F]+).*\015\012// ) {
my $chunk_len = hex $1;
last DECHUNK if $chunk_len == 0;
my $read = $env->{'psgi.input'}->read($chunk_buffer, CHUNK_SIZE, length $chunk_buffer);

while ( $chunk_buffer =~ s/^(([0-9a-fA-F]+).*\015\012)// ) {
my $trailer = $1;
my $chunk_len = hex $2;

if ($chunk_len == 0) {
last DECHUNK;
} elsif (length $chunk_buffer < $chunk_len) {
$chunk_buffer = $trailer . $chunk_buffer;
last;
}

$buffer->print(substr $chunk_buffer, 0, $chunk_len, '');
$chunk_buffer =~ s/^\015\012//;
Expand Down
3 changes: 2 additions & 1 deletion lib/Plack/TempBuffer/Auto.pm
Expand Up @@ -14,10 +14,11 @@ sub print {
my $self = shift;
$self->{_buffer}->print(@_);

if ($self->{_buffer}->size > $self->{_max}) {
if ($self->{_max} && $self->{_buffer}->size > $self->{_max}) {
my $buf = $self->{_buffer}->{buffer};
$self->{_buffer} = Plack::TempBuffer->create('File'),
$self->{_buffer}->print($buf);
delete $self->{_max};
}
}

Expand Down
14 changes: 9 additions & 5 deletions t/Plack-Middleware/dechunk.t
Expand Up @@ -2,8 +2,11 @@ use strict;
use Plack::Test;
use HTTP::Request;
use Test::More;
use Digest::MD5;
use Plack::Middleware::Dechunk;

my $file = "share/kyoto.jpg";

my @backends = qw(Server MockHTTP); # Server should come first
sub flip_backend { $Plack::Test::Impl = shift @backends }

Expand All @@ -24,16 +27,17 @@ $app = Plack::Middleware::Dechunk->wrap($app);
test_psgi $app, sub {
my $cb = shift;

my @chunks = ('0123456789') x 4;
my $content = join '', @chunks;
open my $fh, "<:raw", $file;
local $/ = \1024;

my $req = HTTP::Request->new(POST => "http://localhost/");
$req->content(sub { shift @chunks });
$req->content(sub { scalar <$fh> });

my $res = $cb->($req);

is $res->header('X-Content-Length'), 40;
is $res->content, $content;
is $res->header('X-Content-Length'), 2397701;
is Digest::MD5::md5_hex($res->content), '9c6d7249a77204a88be72e9b2fe279e8';

} while flip_backend;

done_testing;

0 comments on commit 82121a7

Please sign in to comment.