1 package Net::HTTP::Methods;
3 require 5.005; # 4-arg substr
10 my $CRLF = "\015\012"; # "\r\n" is not portable
12 *_bytes = defined(&utf8::downgrade) ?
14 unless (utf8::downgrade($_[0], 1)) {
16 Carp::croak("Wide character in HTTP request (bytes required)");
28 unshift(@_, "Host") if @_ == 1;
31 my $self = bless Symbol::gensym(), $class;
32 return $self->http_configure(\%cnf);
38 die "Listen option not allowed" if $cnf->{Listen};
39 my $explict_host = (exists $cnf->{Host});
40 my $host = delete $cnf->{Host};
41 my $peer = $cnf->{PeerAddr} || $cnf->{PeerHost};
43 die "No Host option provided" unless $host;
44 $cnf->{PeerAddr} = $peer = $host;
47 if ($peer =~ s,:(\d+)$,,) {
48 $cnf->{PeerPort} = int($1); # always override
50 if (!$cnf->{PeerPort}) {
51 $cnf->{PeerPort} = $self->http_default_port;
58 if ($host && $host !~ /:/) {
59 my $p = $cnf->{PeerPort};
60 $host .= ":$p" if $p != $self->http_default_port;
63 $cnf->{Proto} = 'tcp';
65 my $keep_alive = delete $cnf->{KeepAlive};
66 my $http_version = delete $cnf->{HTTPVersion};
67 $http_version = "1.1" unless defined $http_version;
68 my $peer_http_version = delete $cnf->{PeerHTTPVersion};
69 $peer_http_version = "1.0" unless defined $peer_http_version;
70 my $send_te = delete $cnf->{SendTE};
71 my $max_line_length = delete $cnf->{MaxLineLength};
72 $max_line_length = 8*1024 unless defined $max_line_length;
73 my $max_header_lines = delete $cnf->{MaxHeaderLines};
74 $max_header_lines = 128 unless defined $max_header_lines;
76 return undef unless $self->http_connect($cnf);
79 $self->keep_alive($keep_alive);
80 $self->send_te($send_te);
81 $self->http_version($http_version);
82 $self->peer_http_version($peer_http_version);
83 $self->max_line_length($max_line_length);
84 $self->max_header_lines($max_header_lines);
86 ${*$self}{'http_buf'} = "";
91 sub http_default_port {
95 # set up property accessors
96 for my $method (qw(host keep_alive send_te max_line_length max_header_lines peer_http_version)) {
97 my $prop_name = "http_" . $method;
101 my $old = ${*$self}{$prop_name};
102 ${*$self}{$prop_name} = shift if @_;
107 # we want this one to be a bit smarter
110 my $old = ${*$self}{'http_version'};
113 $v = "1.0" if $v eq "1"; # float
114 unless ($v eq "1.0" or $v eq "1.1") {
116 Carp::croak("Unsupported HTTP version '$v'");
118 ${*$self}{'http_version'} = $v;
128 my $content = (@_ % 2) ? pop : "";
130 for ($method, $uri) {
132 Carp::croak("Bad method or uri") if /\s/ || !length;
135 push(@{${*$self}{'http_request_method'}}, $method);
136 my $ver = ${*$self}{'http_version'};
137 my $peer_ver = ${*$self}{'http_peer_http_version'} || "1.0";
141 my %given = (host => 0, "content-length" => 0, "te" => 0);
143 my($k, $v) = splice(@_, 0, 2);
145 if ($lc_k eq "connection") {
148 push(@connection, split(/\s*,\s*/, $v));
151 if (exists $given{$lc_k}) {
157 if (length($content) && !$given{'content-length'}) {
158 push(@h, "Content-Length: " . length($content));
163 push(@connection, "TE") unless grep lc($_) eq "te", @connection;
165 elsif ($self->send_te && gunzip_ok()) {
166 # gzip is less wanted since the IO::Uncompress::Gunzip interface for
167 # it does not really allow chunked decoding to take place easily.
168 push(@h2, "TE: deflate,gzip;q=0.3");
169 push(@connection, "TE");
172 unless (grep lc($_) eq "close", @connection) {
173 if ($self->keep_alive) {
174 if ($peer_ver eq "1.0") {
175 # from looking at Netscape's headers
176 push(@h2, "Keep-Alive: 300");
177 unshift(@connection, "Keep-Alive");
181 push(@connection, "close") if $ver ge "1.1";
184 push(@h2, "Connection: " . join(", ", @connection)) if @connection;
185 unless ($given{host}) {
186 my $h = ${*$self}{'http_host'};
187 push(@h2, "Host: $h") if $h;
190 return _bytes(join($CRLF, "$method $uri HTTP/$ver", @h2, @h, "", $content));
196 $self->print($self->format_request(@_));
201 return $_[0] unless defined($_[0]) && length($_[0]);
202 return _bytes(sprintf("%x", length($_[0])) . $CRLF . $_[0] . $CRLF);
207 return 1 unless defined($_[0]) && length($_[0]);
208 $self->print(_bytes(sprintf("%x", length($_[0])) . $CRLF . $_[0] . $CRLF));
211 sub format_chunk_eof {
215 push(@h, sprintf "%s: %s$CRLF", splice(@_, 0, 2));
217 return _bytes(join("", "0$CRLF", @h, $CRLF));
220 sub write_chunk_eof {
222 $self->print($self->format_chunk_eof(@_));
230 for (${*$self}{'http_buf'}) {
232 $_[0] = substr($_, 0, $len, "");
233 return length($_[0]);
236 return $self->sysread($_[0], $len);
245 for (${*$self}{'http_buf'}) {
246 my $max_line_length = ${*$self}{'http_max_line_length'};
250 $pos = index($_, "\012");
252 die "$what line too long (limit is $max_line_length)"
253 if $max_line_length && length($_) > $max_line_length;
255 # need to read more data to find a line ending
258 my $n = $self->sysread($_, 1024, length);
259 unless (defined $n) {
260 redo READ if $!{EINTR};
262 # Hmm, we must be reading from a non-blocking socket
263 # XXX Should really wait until this socket is readable,...
264 select(undef, undef, undef, 0.1); # but this will do for now
267 # if we have already accumulated some data let's at least
268 # return that as a line
269 die "$what read failed: $!" unless length;
272 return undef unless length;
273 return substr($_, 0, length, "");
277 die "$what line too long ($pos; limit is $max_line_length)"
278 if $max_line_length && $pos > $max_line_length;
280 my $line = substr($_, 0, $pos+1, "");
281 $line =~ s/(\015?\012)\z// || die "Assert";
282 return wantarray ? ($line, $1) : $line;
290 for (${*$self}{'http_buf'}) {
292 $old = $_ if defined wantarray;
298 return ${*$self}{'http_buf'};
304 return length ${*$self}{'http_buf'};
308 sub _read_header_lines {
310 my $junk_out = shift;
314 my $max_header_lines = ${*$self}{'http_max_header_lines'};
315 while (my $line = my_readline($self, 'Header')) {
316 if ($line =~ /^(\S+?)\s*:\s*(.*)/s) {
317 push(@headers, $1, $2);
319 elsif (@headers && $line =~ s/^\s+//) {
320 $headers[-1] .= " " . $line;
323 push(@$junk_out, $line);
326 die "Bad header: '$line'\n";
328 if ($max_header_lines) {
330 if ($line_count >= $max_header_lines) {
331 die "Too many header lines (limit is $max_header_lines)";
339 sub read_response_headers {
340 my($self, %opt) = @_;
341 my $laxed = $opt{laxed};
343 my($status, $eol) = my_readline($self, 'Status');
344 unless (defined $status) {
345 die "Server closed connection without sending any data back";
348 my($peer_ver, $code, $message) = split(/\s+/, $status, 3);
349 if (!$peer_ver || $peer_ver !~ s,^HTTP/,, || $code !~ /^[1-5]\d\d$/) {
350 die "Bad response status line: '$status'" unless $laxed;
352 ${*$self}{'http_peer_http_version'} = "0.9";
353 ${*$self}{'http_status'} = "200";
354 substr(${*$self}{'http_buf'}, 0, 0) = $status . ($eol || "");
355 return 200 unless wantarray;
356 return (200, "Assumed OK");
359 ${*$self}{'http_peer_http_version'} = $peer_ver;
360 ${*$self}{'http_status'} = $code;
364 $junk_out = $opt{junk_out} || [];
366 my @headers = $self->_read_header_lines($junk_out);
368 # pick out headers that read_entity_body might need
371 for (my $i = 0; $i < @headers; $i += 2) {
372 my $h = lc($headers[$i]);
373 if ($h eq 'transfer-encoding') {
374 my $te = $headers[$i+1];
377 push(@te, $te) if length($te);
379 elsif ($h eq 'content-length') {
380 # ignore bogus and overflow values
381 if ($headers[$i+1] =~ /^\s*(\d{1,15})(?:\s|$)/) {
382 $content_length = $1;
386 ${*$self}{'http_te'} = join(",", @te);
387 ${*$self}{'http_content_length'} = $content_length;
388 ${*$self}{'http_first_body'}++;
389 delete ${*$self}{'http_trailers'};
390 return $code unless wantarray;
391 return ($code, $message, @headers);
395 sub read_entity_body {
397 my $buf_ref = \$_[0];
399 die "Offset not supported yet" if $_[2];
404 if (${*$self}{'http_first_body'}) {
405 ${*$self}{'http_first_body'} = 0;
406 delete ${*$self}{'http_chunked'};
407 delete ${*$self}{'http_bytes'};
408 my $method = shift(@{${*$self}{'http_request_method'}});
409 my $status = ${*$self}{'http_status'};
410 if ($method eq "HEAD") {
411 # this response is always empty regardless of other headers
414 elsif (my $te = ${*$self}{'http_te'}) {
415 my @te = split(/\s*,\s*/, lc($te));
416 die "Chunked must be last Transfer-Encoding '$te'"
417 unless pop(@te) eq "chunked";
420 if ($_ eq "deflate" && inflate_ok()) {
421 #require Compress::Raw::Zlib;
422 my ($i, $status) = Compress::Raw::Zlib::Inflate->new();
423 die "Can't make inflator: $status" unless $i;
424 $_ = sub { my $out; $i->inflate($_[0], \$out); $out }
426 elsif ($_ eq "gzip" && gunzip_ok()) {
427 #require IO::Uncompress::Gunzip;
431 return "" unless $_[1];
432 my $input = join("", @buf);
434 IO::Uncompress::Gunzip::gunzip(\$input, \$output, Transparent => 0)
435 or die "Can't gunzip content: $IO::Uncompress::Gunzip::GunzipError";
439 elsif ($_ eq "identity") {
443 die "Can't handle transfer encoding '$te'";
449 ${*$self}{'http_te2'} = @te ? \@te : "";
452 elsif (defined(my $content_length = ${*$self}{'http_content_length'})) {
453 $bytes = $content_length;
455 elsif ($status =~ /^(?:1|[23]04)/) {
456 # RFC 2616 says that these responses should always be empty
457 # but that does not appear to be true in practice [RT#17907]
461 # XXX Multi-Part types are self delimiting, but RFC 2616 says we
462 # only has to deal with 'multipart/byteranges'
468 $chunked = ${*$self}{'http_chunked'};
469 $bytes = ${*$self}{'http_bytes'};
472 if (defined $chunked) {
473 # The state encoded in $chunked is:
474 # $chunked == 0: read CRLF after chunk, then chunk header
475 # $chunked == -1: read chunk header
476 # $chunked > 0: bytes left in current chunk to read
479 my $line = my_readline($self, 'Entity body');
481 die "Missing newline after chunk data: '$line'"
482 if !defined($line) || $line ne "";
483 $line = my_readline($self, 'Entity body');
485 die "EOF when chunk header expected" unless defined($line);
486 my $chunk_len = $line;
487 $chunk_len =~ s/;.*//; # ignore potential chunk parameters
488 unless ($chunk_len =~ /^([\da-fA-F]+)\s*$/) {
489 die "Bad chunk-size in HTTP response: $line";
493 ${*$self}{'http_trailers'} = [$self->_read_header_lines];
497 if (my $transforms = delete ${*$self}{'http_te2'}) {
499 $$buf_ref = &$_($$buf_ref, 1);
501 $n = length($$buf_ref);
504 # in case somebody tries to read more, make sure we continue
506 delete ${*$self}{'http_chunked'};
507 ${*$self}{'http_bytes'} = 0;
514 $n = $size if $size && $size < $n;
515 $n = my_read($self, $$buf_ref, $n);
516 return undef unless defined $n;
518 ${*$self}{'http_chunked'} = $chunked - $n;
521 if (my $transforms = ${*$self}{'http_te2'}) {
523 $$buf_ref = &$_($$buf_ref, 0);
525 $n = length($$buf_ref);
531 elsif (defined $bytes) {
537 $n = $size if $size && $size < $n;
538 $n = my_read($self, $$buf_ref, $n);
539 return undef unless defined $n;
540 ${*$self}{'http_bytes'} = $bytes - $n;
546 return my_read($self, $$buf_ref, $size);
552 @{${*$self}{'http_trailers'} || []};
560 return $gunzip_ok if defined $gunzip_ok;
562 # Try to load IO::Uncompress::Gunzip.
568 require IO::Uncompress::Gunzip;
576 return $inflate_ok if defined $inflate_ok;
578 # Try to load Compress::Raw::Zlib.
584 require Compress::Raw::Zlib;