Add the original source packages to maemo, source lenny
[dh-make-perl] / dev / i386 / libwww-perl / libwww-perl-5.813 / lib / LWP / Protocol / http.pm
1 package LWP::Protocol::http;
2
3 use strict;
4
5 require LWP::Debug;
6 require HTTP::Response;
7 require HTTP::Status;
8 require Net::HTTP;
9
10 use vars qw(@ISA @EXTRA_SOCK_OPTS);
11
12 require LWP::Protocol;
13 @ISA = qw(LWP::Protocol);
14
15 my $CRLF = "\015\012";
16
17 sub _new_socket
18 {
19     my($self, $host, $port, $timeout) = @_;
20     my $conn_cache = $self->{ua}{conn_cache};
21     if ($conn_cache) {
22         if (my $sock = $conn_cache->withdraw("http", "$host:$port")) {
23             return $sock if $sock && !$sock->can_read(0);
24             # if the socket is readable, then either the peer has closed the
25             # connection or there are some garbage bytes on it.  In either
26             # case we abandon it.
27             $sock->close;
28         }
29     }
30
31     local($^W) = 0;  # IO::Socket::INET can be noisy
32     my $sock = $self->socket_class->new(PeerAddr => $host,
33                                         PeerPort => $port,
34                                         Proto    => 'tcp',
35                                         Timeout  => $timeout,
36                                         KeepAlive => !!$conn_cache,
37                                         SendTE    => 1,
38                                         $self->_extra_sock_opts($host, $port),
39                                        );
40
41     unless ($sock) {
42         # IO::Socket::INET leaves additional error messages in $@
43         $@ =~ s/^.*?: //;
44         die "Can't connect to $host:$port ($@)";
45     }
46
47     # perl 5.005's IO::Socket does not have the blocking method.
48     eval { $sock->blocking(0); };
49
50     $sock;
51 }
52
53 sub socket_class
54 {
55     my $self = shift;
56     (ref($self) || $self) . "::Socket";
57 }
58
59 sub _extra_sock_opts  # to be overridden by subclass
60 {
61     return @EXTRA_SOCK_OPTS;
62 }
63
64 sub _check_sock
65 {
66     #my($self, $req, $sock) = @_;
67 }
68
69 sub _get_sock_info
70 {
71     my($self, $res, $sock) = @_;
72     if (defined(my $peerhost = $sock->peerhost)) {
73         $res->header("Client-Peer" => "$peerhost:" . $sock->peerport);
74     }
75 }
76
77 sub _fixup_header
78 {
79     my($self, $h, $url, $proxy) = @_;
80
81     # Extract 'Host' header
82     my $hhost = $url->authority;
83     if ($hhost =~ s/^([^\@]*)\@//) {  # get rid of potential "user:pass@"
84         # add authorization header if we need them.  HTTP URLs do
85         # not really support specification of user and password, but
86         # we allow it.
87         if (defined($1) && not $h->header('Authorization')) {
88             require URI::Escape;
89             $h->authorization_basic(map URI::Escape::uri_unescape($_),
90                                     split(":", $1, 2));
91         }
92     }
93     $h->init_header('Host' => $hhost);
94
95     if ($proxy) {
96         # Check the proxy URI's userinfo() for proxy credentials
97         # export http_proxy="http://proxyuser:proxypass@proxyhost:port"
98         my $p_auth = $proxy->userinfo();
99         if(defined $p_auth) {
100             require URI::Escape;
101             $h->proxy_authorization_basic(map URI::Escape::uri_unescape($_),
102                                           split(":", $p_auth, 2))
103         }
104     }
105 }
106
107 sub hlist_remove {
108     my($hlist, $k) = @_;
109     $k = lc $k;
110     for (my $i = @$hlist - 2; $i >= 0; $i -= 2) {
111         next unless lc($hlist->[$i]) eq $k;
112         splice(@$hlist, $i, 2);
113     }
114 }
115
116 sub request
117 {
118     my($self, $request, $proxy, $arg, $size, $timeout) = @_;
119     LWP::Debug::trace('()');
120
121     $size ||= 4096;
122
123     # check method
124     my $method = $request->method;
125     unless ($method =~ /^[A-Za-z0-9_!\#\$%&\'*+\-.^\`|~]+$/) {  # HTTP token
126         return new HTTP::Response &HTTP::Status::RC_BAD_REQUEST,
127                                   'Library does not allow method ' .
128                                   "$method for 'http:' URLs";
129     }
130
131     my $url = $request->url;
132     my($host, $port, $fullpath);
133
134     # Check if we're proxy'ing
135     if (defined $proxy) {
136         # $proxy is an URL to an HTTP server which will proxy this request
137         $host = $proxy->host;
138         $port = $proxy->port;
139         $fullpath = $method eq "CONNECT" ?
140                        ($url->host . ":" . $url->port) :
141                        $url->as_string;
142     }
143     else {
144         $host = $url->host;
145         $port = $url->port;
146         $fullpath = $url->path_query;
147         $fullpath = "/$fullpath" unless $fullpath =~ m,^/,;
148     }
149
150     # connect to remote site
151     my $socket = $self->_new_socket($host, $port, $timeout);
152     $self->_check_sock($request, $socket);
153
154     my @h;
155     my $request_headers = $request->headers->clone;
156     $self->_fixup_header($request_headers, $url, $proxy);
157
158     $request_headers->scan(sub {
159                                my($k, $v) = @_;
160                                $k =~ s/^://;
161                                $v =~ s/\n/ /g;
162                                push(@h, $k, $v);
163                            });
164
165     my $content_ref = $request->content_ref;
166     $content_ref = $$content_ref if ref($$content_ref);
167     my $chunked;
168     my $has_content;
169
170     if (ref($content_ref) eq 'CODE') {
171         my $clen = $request_headers->header('Content-Length');
172         $has_content++ if $clen;
173         unless (defined $clen) {
174             push(@h, "Transfer-Encoding" => "chunked");
175             $has_content++;
176             $chunked++;
177         }
178     }
179     else {
180         # Set (or override) Content-Length header
181         my $clen = $request_headers->header('Content-Length');
182         if (defined($$content_ref) && length($$content_ref)) {
183             $has_content = length($$content_ref);
184             if (!defined($clen) || $clen ne $has_content) {
185                 if (defined $clen) {
186                     warn "Content-Length header value was wrong, fixed";
187                     hlist_remove(\@h, 'Content-Length');
188                 }
189                 push(@h, 'Content-Length' => $has_content);
190             }
191         }
192         elsif ($clen) {
193             warn "Content-Length set when there is no content, fixed";
194             hlist_remove(\@h, 'Content-Length');
195         }
196     }
197
198     my $write_wait = 0;
199     $write_wait = 2
200         if ($request_headers->header("Expect") || "") =~ /100-continue/;
201
202     my $req_buf = $socket->format_request($method, $fullpath, @h);
203     #print "------\n$req_buf\n------\n";
204
205     if (!$has_content || $write_wait || $has_content > 8*1024) {
206         do {
207             # Since this just writes out the header block it should almost
208             # always succeed to send the whole buffer in a single write call.
209             my $n = $socket->syswrite($req_buf, length($req_buf));
210             unless (defined $n) {
211                 redo if $!{EINTR};
212                 if ($!{EAGAIN}) {
213                     select(undef, undef, undef, 0.1);
214                     redo;
215                 }
216                 die "write failed: $!";
217             }
218             if ($n) {
219                 substr($req_buf, 0, $n, "");
220             }
221             else {
222                 select(undef, undef, undef, 0.5);
223             }
224         }
225         while (length $req_buf);
226     }
227
228     my($code, $mess, @junk);
229     my $drop_connection;
230
231     if ($has_content) {
232         my $eof;
233         my $wbuf;
234         my $woffset = 0;
235         if (ref($content_ref) eq 'CODE') {
236             my $buf = &$content_ref();
237             $buf = "" unless defined($buf);
238             $buf = sprintf "%x%s%s%s", length($buf), $CRLF, $buf, $CRLF
239                 if $chunked;
240             substr($buf, 0, 0) = $req_buf if $req_buf;
241             $wbuf = \$buf;
242         }
243         else {
244             if ($req_buf) {
245                 my $buf = $req_buf . $$content_ref;
246                 $wbuf = \$buf;
247             }
248             else {
249                 $wbuf = $content_ref;
250             }
251             $eof = 1;
252         }
253
254         my $fbits = '';
255         vec($fbits, fileno($socket), 1) = 1;
256
257       WRITE:
258         while ($woffset < length($$wbuf)) {
259
260             my $sel_timeout = $timeout;
261             if ($write_wait) {
262                 $sel_timeout = $write_wait if $write_wait < $sel_timeout;
263             }
264             my $time_before;
265             $time_before = time if $sel_timeout;
266
267             my $rbits = $fbits;
268             my $wbits = $write_wait ? undef : $fbits;
269             my $sel_timeout_before = $sel_timeout;
270           SELECT:
271             {
272                 my $nfound = select($rbits, $wbits, undef, $sel_timeout);
273                 unless (defined $nfound) {
274                     if ($!{EINTR} || $!{EAGAIN}) {
275                         if ($time_before) {
276                             $sel_timeout = $sel_timeout_before - (time - $time_before);
277                             $sel_timeout = 0 if $sel_timeout < 0;
278                         }
279                         redo SELECT;
280                     }
281                     die "select failed: $!";
282                 }
283             }
284
285             if ($write_wait) {
286                 $write_wait -= time - $time_before;
287                 $write_wait = 0 if $write_wait < 0;
288             }
289
290             if (defined($rbits) && $rbits =~ /[^\0]/) {
291                 # readable
292                 my $buf = $socket->_rbuf;
293                 my $n = $socket->sysread($buf, 1024, length($buf));
294                 unless (defined $n) {
295                     die "read failed: $!" unless  $!{EINTR} || $!{EAGAIN};
296                     # if we get here the rest of the block will do nothing
297                     # and we will retry the read on the next round
298                 }
299                 elsif ($n == 0) {
300                     # the server closed the connection before we finished
301                     # writing all the request content.  No need to write any more.
302                     $drop_connection++;
303                     last WRITE;
304                 }
305                 $socket->_rbuf($buf);
306                 if (!$code && $buf =~ /\015?\012\015?\012/) {
307                     # a whole response header is present, so we can read it without blocking
308                     ($code, $mess, @h) = $socket->read_response_headers(laxed => 1,
309                                                                         junk_out => \@junk,
310                                                                        );
311                     if ($code eq "100") {
312                         $write_wait = 0;
313                         undef($code);
314                     }
315                     else {
316                         $drop_connection++;
317                         last WRITE;
318                         # XXX should perhaps try to abort write in a nice way too
319                     }
320                 }
321             }
322             if (defined($wbits) && $wbits =~ /[^\0]/) {
323                 my $n = $socket->syswrite($$wbuf, length($$wbuf), $woffset);
324                 unless (defined $n) {
325                     die "write failed: $!" unless $!{EINTR} || $!{EAGAIN};
326                     $n = 0;  # will retry write on the next round
327                 }
328                 elsif ($n == 0) {
329                     die "write failed: no bytes written";
330                 }
331                 $woffset += $n;
332
333                 if (!$eof && $woffset >= length($$wbuf)) {
334                     # need to refill buffer from $content_ref code
335                     my $buf = &$content_ref();
336                     $buf = "" unless defined($buf);
337                     $eof++ unless length($buf);
338                     $buf = sprintf "%x%s%s%s", length($buf), $CRLF, $buf, $CRLF
339                         if $chunked;
340                     $wbuf = \$buf;
341                     $woffset = 0;
342                 }
343             }
344         } # WRITE
345     }
346
347     ($code, $mess, @h) = $socket->read_response_headers(laxed => 1, junk_out => \@junk)
348         unless $code;
349     ($code, $mess, @h) = $socket->read_response_headers(laxed => 1, junk_out => \@junk)
350         if $code eq "100";
351
352     my $response = HTTP::Response->new($code, $mess);
353     my $peer_http_version = $socket->peer_http_version;
354     $response->protocol("HTTP/$peer_http_version");
355     while (@h) {
356         my($k, $v) = splice(@h, 0, 2);
357         $response->push_header($k, $v);
358     }
359     $response->push_header("Client-Junk" => \@junk) if @junk;
360
361     $response->request($request);
362     $self->_get_sock_info($response, $socket);
363
364     if ($method eq "CONNECT") {
365         $response->{client_socket} = $socket;  # so it can be picked up
366         return $response;
367     }
368
369     if (my @te = $response->remove_header('Transfer-Encoding')) {
370         $response->push_header('Client-Transfer-Encoding', \@te);
371     }
372     $response->push_header('Client-Response-Num', $socket->increment_response_count);
373
374     my $complete;
375     $response = $self->collect($arg, $response, sub {
376         my $buf = ""; #prevent use of uninitialized value in SSLeay.xs
377         my $n;
378       READ:
379         {
380             $n = $socket->read_entity_body($buf, $size);
381             unless (defined $n) {
382                 redo READ if $!{EINTR} || $!{EAGAIN};
383                 die "read failed: $!";
384             }
385             redo READ if $n == -1;
386         }
387         $complete++ if !$n;
388         return \$buf;
389     } );
390     $drop_connection++ unless $complete;
391
392     @h = $socket->get_trailers;
393     while (@h) {
394         my($k, $v) = splice(@h, 0, 2);
395         $response->push_header($k, $v);
396     }
397
398     # keep-alive support
399     unless ($drop_connection) {
400         if (my $conn_cache = $self->{ua}{conn_cache}) {
401             my %connection = map { (lc($_) => 1) }
402                              split(/\s*,\s*/, ($response->header("Connection") || ""));
403             if (($peer_http_version eq "1.1" && !$connection{close}) ||
404                 $connection{"keep-alive"})
405             {
406                 LWP::Debug::debug("Keep the http connection to $host:$port");
407                 $conn_cache->deposit("http", "$host:$port", $socket);
408             }
409         }
410     }
411
412     $response;
413 }
414
415
416 #-----------------------------------------------------------
417 package LWP::Protocol::http::SocketMethods;
418
419 sub sysread {
420     my $self = shift;
421     if (my $timeout = ${*$self}{io_socket_timeout}) {
422         die "read timeout" unless $self->can_read($timeout);
423     }
424     else {
425         # since we have made the socket non-blocking we
426         # use select to wait for some data to arrive
427         $self->can_read(undef) || die "Assert";
428     }
429     sysread($self, $_[0], $_[1], $_[2] || 0);
430 }
431
432 sub can_read {
433     my($self, $timeout) = @_;
434     my $fbits = '';
435     vec($fbits, fileno($self), 1) = 1;
436   SELECT:
437     {
438         my $before;
439         $before = time if $timeout;
440         my $nfound = select($fbits, undef, undef, $timeout);
441         unless (defined $nfound) {
442             if ($!{EINTR} || $!{EAGAIN}) {
443                 # don't really think EAGAIN can happen here
444                 if ($timeout) {
445                     $timeout -= time - $before;
446                     $timeout = 0 if $timeout < 0;
447                 }
448                 redo SELECT;
449             }
450             die "select failed: $!";
451         }
452         return $nfound > 0;
453     }
454 }
455
456 sub ping {
457     my $self = shift;
458     !$self->can_read(0);
459 }
460
461 sub increment_response_count {
462     my $self = shift;
463     return ++${*$self}{'myhttp_response_count'};
464 }
465
466 #-----------------------------------------------------------
467 package LWP::Protocol::http::Socket;
468 use vars qw(@ISA);
469 @ISA = qw(LWP::Protocol::http::SocketMethods Net::HTTP);
470
471 1;