1 package LWP::Protocol::http;
5 require HTTP::Response;
9 use vars qw(@ISA @EXTRA_SOCK_OPTS);
11 require LWP::Protocol;
12 @ISA = qw(LWP::Protocol);
14 my $CRLF = "\015\012";
18 my($self, $host, $port, $timeout) = @_;
19 my $conn_cache = $self->{ua}{conn_cache};
21 if (my $sock = $conn_cache->withdraw($self->socket_type, "$host:$port")) {
22 return $sock if $sock && !$sock->can_read(0);
23 # if the socket is readable, then either the peer has closed the
24 # connection or there are some garbage bytes on it. In either
30 local($^W) = 0; # IO::Socket::INET can be noisy
31 my $sock = $self->socket_class->new(PeerAddr => $host,
33 LocalAddr => $self->{ua}{local_address},
36 KeepAlive => !!$conn_cache,
38 $self->_extra_sock_opts($host, $port),
42 # IO::Socket::INET leaves additional error messages in $@
44 die "Can't connect to $host:$port ($@)";
47 # perl 5.005's IO::Socket does not have the blocking method.
48 eval { $sock->blocking(0); };
61 (ref($self) || $self) . "::Socket";
64 sub _extra_sock_opts # to be overridden by subclass
66 return @EXTRA_SOCK_OPTS;
71 #my($self, $req, $sock) = @_;
76 my($self, $res, $sock) = @_;
77 if (defined(my $peerhost = $sock->peerhost)) {
78 $res->header("Client-Peer" => "$peerhost:" . $sock->peerport);
84 my($self, $h, $url, $proxy) = @_;
86 # Extract 'Host' header
87 my $hhost = $url->authority;
88 if ($hhost =~ s/^([^\@]*)\@//) { # get rid of potential "user:pass@"
89 # add authorization header if we need them. HTTP URLs do
90 # not really support specification of user and password, but
92 if (defined($1) && not $h->header('Authorization')) {
94 $h->authorization_basic(map URI::Escape::uri_unescape($_),
98 $h->init_header('Host' => $hhost);
101 # Check the proxy URI's userinfo() for proxy credentials
102 # export http_proxy="http://proxyuser:proxypass@proxyhost:port"
103 my $p_auth = $proxy->userinfo();
104 if(defined $p_auth) {
106 $h->proxy_authorization_basic(map URI::Escape::uri_unescape($_),
107 split(":", $p_auth, 2))
115 for (my $i = @$hlist - 2; $i >= 0; $i -= 2) {
116 next unless lc($hlist->[$i]) eq $k;
117 splice(@$hlist, $i, 2);
123 my($self, $request, $proxy, $arg, $size, $timeout) = @_;
128 my $method = $request->method;
129 unless ($method =~ /^[A-Za-z0-9_!\#\$%&\'*+\-.^\`|~]+$/) { # HTTP token
130 return new HTTP::Response &HTTP::Status::RC_BAD_REQUEST,
131 'Library does not allow method ' .
132 "$method for 'http:' URLs";
135 my $url = $request->uri;
136 my($host, $port, $fullpath);
138 # Check if we're proxy'ing
139 if (defined $proxy) {
140 # $proxy is an URL to an HTTP server which will proxy this request
141 $host = $proxy->host;
142 $port = $proxy->port;
143 $fullpath = $method eq "CONNECT" ?
144 ($url->host . ":" . $url->port) :
150 $fullpath = $url->path_query;
151 $fullpath = "/$fullpath" unless $fullpath =~ m,^/,;
154 # connect to remote site
155 my $socket = $self->_new_socket($host, $port, $timeout);
156 $self->_check_sock($request, $socket);
159 my $request_headers = $request->headers->clone;
160 $self->_fixup_header($request_headers, $url, $proxy);
162 $request_headers->scan(sub {
169 my $content_ref = $request->content_ref;
170 $content_ref = $$content_ref if ref($$content_ref);
174 if (ref($content_ref) eq 'CODE') {
175 my $clen = $request_headers->header('Content-Length');
176 $has_content++ if $clen;
177 unless (defined $clen) {
178 push(@h, "Transfer-Encoding" => "chunked");
184 # Set (or override) Content-Length header
185 my $clen = $request_headers->header('Content-Length');
186 if (defined($$content_ref) && length($$content_ref)) {
187 $has_content = length($$content_ref);
188 if (!defined($clen) || $clen ne $has_content) {
190 warn "Content-Length header value was wrong, fixed";
191 hlist_remove(\@h, 'Content-Length');
193 push(@h, 'Content-Length' => $has_content);
197 warn "Content-Length set when there is no content, fixed";
198 hlist_remove(\@h, 'Content-Length');
204 if ($request_headers->header("Expect") || "") =~ /100-continue/;
206 my $req_buf = $socket->format_request($method, $fullpath, @h);
207 #print "------\n$req_buf\n------\n";
209 if (!$has_content || $write_wait || $has_content > 8*1024) {
212 # Since this just writes out the header block it should almost
213 # always succeed to send the whole buffer in a single write call.
214 my $n = $socket->syswrite($req_buf, length($req_buf));
215 unless (defined $n) {
216 redo WRITE if $!{EINTR};
218 select(undef, undef, undef, 0.1);
221 die "write failed: $!";
224 substr($req_buf, 0, $n, "");
227 select(undef, undef, undef, 0.5);
229 redo WRITE if length $req_buf;
233 my($code, $mess, @junk);
240 if (ref($content_ref) eq 'CODE') {
241 my $buf = &$content_ref();
242 $buf = "" unless defined($buf);
243 $buf = sprintf "%x%s%s%s", length($buf), $CRLF, $buf, $CRLF
245 substr($buf, 0, 0) = $req_buf if $req_buf;
250 my $buf = $req_buf . $$content_ref;
254 $wbuf = $content_ref;
260 vec($fbits, fileno($socket), 1) = 1;
263 while ($woffset < length($$wbuf)) {
265 my $sel_timeout = $timeout;
267 $sel_timeout = $write_wait if $write_wait < $sel_timeout;
270 $time_before = time if $sel_timeout;
273 my $wbits = $write_wait ? undef : $fbits;
274 my $sel_timeout_before = $sel_timeout;
277 my $nfound = select($rbits, $wbits, undef, $sel_timeout);
279 if ($!{EINTR} || $!{EAGAIN}) {
281 $sel_timeout = $sel_timeout_before - (time - $time_before);
282 $sel_timeout = 0 if $sel_timeout < 0;
286 die "select failed: $!";
291 $write_wait -= time - $time_before;
292 $write_wait = 0 if $write_wait < 0;
295 if (defined($rbits) && $rbits =~ /[^\0]/) {
297 my $buf = $socket->_rbuf;
298 my $n = $socket->sysread($buf, 1024, length($buf));
299 unless (defined $n) {
300 die "read failed: $!" unless $!{EINTR} || $!{EAGAIN};
301 # if we get here the rest of the block will do nothing
302 # and we will retry the read on the next round
305 # the server closed the connection before we finished
306 # writing all the request content. No need to write any more.
310 $socket->_rbuf($buf);
311 if (!$code && $buf =~ /\015?\012\015?\012/) {
312 # a whole response header is present, so we can read it without blocking
313 ($code, $mess, @h) = $socket->read_response_headers(laxed => 1,
316 if ($code eq "100") {
323 # XXX should perhaps try to abort write in a nice way too
327 if (defined($wbits) && $wbits =~ /[^\0]/) {
328 my $n = $socket->syswrite($$wbuf, length($$wbuf), $woffset);
329 unless (defined $n) {
330 die "write failed: $!" unless $!{EINTR} || $!{EAGAIN};
331 $n = 0; # will retry write on the next round
334 die "write failed: no bytes written";
338 if (!$eof && $woffset >= length($$wbuf)) {
339 # need to refill buffer from $content_ref code
340 my $buf = &$content_ref();
341 $buf = "" unless defined($buf);
342 $eof++ unless length($buf);
343 $buf = sprintf "%x%s%s%s", length($buf), $CRLF, $buf, $CRLF
352 ($code, $mess, @h) = $socket->read_response_headers(laxed => 1, junk_out => \@junk)
354 ($code, $mess, @h) = $socket->read_response_headers(laxed => 1, junk_out => \@junk)
357 my $response = HTTP::Response->new($code, $mess);
358 my $peer_http_version = $socket->peer_http_version;
359 $response->protocol("HTTP/$peer_http_version");
361 local $HTTP::Headers::TRANSLATE_UNDERSCORE;
362 $response->push_header(@h);
364 $response->push_header("Client-Junk" => \@junk) if @junk;
366 $response->request($request);
367 $self->_get_sock_info($response, $socket);
369 if ($method eq "CONNECT") {
370 $response->{client_socket} = $socket; # so it can be picked up
374 if (my @te = $response->remove_header('Transfer-Encoding')) {
375 $response->push_header('Client-Transfer-Encoding', \@te);
377 $response->push_header('Client-Response-Num', scalar $socket->increment_response_count);
380 $response = $self->collect($arg, $response, sub {
381 my $buf = ""; #prevent use of uninitialized value in SSLeay.xs
385 $n = $socket->read_entity_body($buf, $size);
386 unless (defined $n) {
387 redo READ if $!{EINTR} || $!{EAGAIN};
388 die "read failed: $!";
390 redo READ if $n == -1;
395 $drop_connection++ unless $complete;
397 @h = $socket->get_trailers;
399 local $HTTP::Headers::TRANSLATE_UNDERSCORE;
400 $response->push_header(@h);
404 unless ($drop_connection) {
405 if (my $conn_cache = $self->{ua}{conn_cache}) {
406 my %connection = map { (lc($_) => 1) }
407 split(/\s*,\s*/, ($response->header("Connection") || ""));
408 if (($peer_http_version eq "1.1" && !$connection{close}) ||
409 $connection{"keep-alive"})
411 $conn_cache->deposit($self->socket_type, "$host:$port", $socket);
420 #-----------------------------------------------------------
421 package LWP::Protocol::http::SocketMethods;
425 if (my $timeout = ${*$self}{io_socket_timeout}) {
426 die "read timeout" unless $self->can_read($timeout);
429 # since we have made the socket non-blocking we
430 # use select to wait for some data to arrive
431 $self->can_read(undef) || die "Assert";
433 sysread($self, $_[0], $_[1], $_[2] || 0);
437 my($self, $timeout) = @_;
439 vec($fbits, fileno($self), 1) = 1;
443 $before = time if $timeout;
444 my $nfound = select($fbits, undef, undef, $timeout);
446 if ($!{EINTR} || $!{EAGAIN}) {
447 # don't really think EAGAIN can happen here
449 $timeout -= time - $before;
450 $timeout = 0 if $timeout < 0;
454 die "select failed: $!";
465 sub increment_response_count {
467 return ++${*$self}{'myhttp_response_count'};
470 #-----------------------------------------------------------
471 package LWP::Protocol::http::Socket;
473 @ISA = qw(LWP::Protocol::http::SocketMethods Net::HTTP);