home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2006 December / PCpro_2006_12.ISO / ossdvd / server / Perl2 / site / lib / lwp / Protocol / http.pm < prev    next >
Encoding:
Perl POD Document  |  2001-12-14  |  10.7 KB  |  410 lines

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