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

  1. # $Id: Protocol.pm,v 1.39 2001/10/26 19:00:21 gisle Exp $
  2.  
  3. package LWP::Protocol;
  4.  
  5. =head1 NAME
  6.  
  7. LWP::Protocol - Base class for LWP protocols
  8.  
  9. =head1 SYNOPSIS
  10.  
  11.  package LWP::Protocol::foo;
  12.  require LWP::Protocol;
  13.  @ISA=qw(LWP::Protocol);
  14.  
  15. =head1 DESCRIPTION
  16.  
  17. This class is used a the base class for all protocol implementations
  18. supported by the LWP library.
  19.  
  20. When creating an instance of this class using
  21. C<LWP::Protocol::create($url)>, and you get an initialised subclass
  22. appropriate for that access method. In other words, the
  23. LWP::Protocol::create() function calls the constructor for one of its
  24. subclasses.
  25.  
  26. All derived LWP::Protocol classes need to override the request()
  27. method which is used to service a request. The overridden method can
  28. make use of the collect() function to collect together chunks of data
  29. as it is received.
  30.  
  31. The following methods and functions are provided:
  32.  
  33. =over 4
  34.  
  35. =cut
  36.  
  37. #####################################################################
  38.  
  39. require LWP::MemberMixin;
  40. @ISA = qw(LWP::MemberMixin);
  41. $VERSION = sprintf("%d.%02d", q$Revision: 1.39 $ =~ /(\d+)\.(\d+)/);
  42.  
  43. use strict;
  44. use Carp ();
  45. use HTTP::Status ();
  46. use HTTP::Response;
  47.  
  48. my %ImplementedBy = (); # scheme => classname
  49.  
  50.  
  51. =item $prot = LWP::Protocol->new()
  52.  
  53. The LWP::Protocol constructor is inherited by subclasses. As this is a
  54. virtual base class this method should B<not> be called directly.
  55.  
  56. =cut
  57.  
  58. sub new
  59. {
  60.     my($class, $scheme, $ua) = @_;
  61.  
  62.     my $self = bless {
  63.     scheme => $scheme,
  64.     ua => $ua,
  65.  
  66.     # historical/redundant
  67.         parse_head => $ua->{parse_head},
  68.         max_size => $ua->{max_size},
  69.     }, $class;
  70.  
  71.     $self;
  72. }
  73.  
  74.  
  75. =item $prot = LWP::Protocol::create($scheme)
  76.  
  77. Create an object of the class implementing the protocol to handle the
  78. given scheme. This is a function, not a method. It is more an object
  79. factory than a constructor. This is the function user agents should
  80. use to access protocols.
  81.  
  82. =cut
  83.  
  84. sub create
  85. {
  86.     my($scheme, $ua) = @_;
  87.     my $impclass = LWP::Protocol::implementor($scheme) or
  88.     Carp::croak("Protocol scheme '$scheme' is not supported");
  89.  
  90.     # hand-off to scheme specific implementation sub-class
  91.     my $protocol = $impclass->new($scheme, $ua);
  92.  
  93.     return $protocol;
  94. }
  95.  
  96.  
  97. =item $class = LWP::Protocol::implementor($scheme, [$class])
  98.  
  99. Get and/or set implementor class for a scheme.  Returns '' if the
  100. specified scheme is not supported.
  101.  
  102. =cut
  103.  
  104. sub implementor
  105. {
  106.     my($scheme, $impclass) = @_;
  107.  
  108.     if ($impclass) {
  109.     $ImplementedBy{$scheme} = $impclass;
  110.     }
  111.     my $ic = $ImplementedBy{$scheme};
  112.     return $ic if $ic;
  113.  
  114.     return '' unless $scheme =~ /^([.+\-\w]+)$/;  # check valid URL schemes
  115.     $scheme = $1; # untaint
  116.     $scheme =~ s/[.+\-]/_/g;  # make it a legal module name
  117.  
  118.     # scheme not yet known, look for a 'use'd implementation
  119.     $ic = "LWP::Protocol::$scheme";  # default location
  120.     $ic = "LWP::Protocol::nntp" if $scheme eq 'news'; #XXX ugly hack
  121.     no strict 'refs';
  122.     # check we actually have one for the scheme:
  123.     unless (@{"${ic}::ISA"}) {
  124.     # try to autoload it
  125.     eval "require $ic";
  126.     if ($@) {
  127.         if ($@ =~ /Can't locate/) { #' #emacs get confused by '
  128.         $ic = '';
  129.         } else {
  130.         die "$@\n";
  131.         }
  132.     }
  133.     }
  134.     $ImplementedBy{$scheme} = $ic if $ic;
  135.     $ic;
  136. }
  137.  
  138.  
  139. =item $prot->request(...)
  140.  
  141.  $response = $protocol->request($request, $proxy, undef);
  142.  $response = $protocol->request($request, $proxy, '/tmp/sss');
  143.  $response = $protocol->request($request, $proxy, \&callback, 1024);
  144.  
  145. Dispactches a request over the protocol, and returns a response
  146. object. This method needs to be overridden in subclasses.  Referer to
  147. L<LWP::UserAgent> for description of the arguments.
  148.  
  149. =cut
  150.  
  151. sub request
  152. {
  153.     my($self, $request, $proxy, $arg, $size, $timeout) = @_;
  154.     Carp::croak('LWP::Protocol::request() needs to be overridden in subclasses');
  155. }
  156.  
  157.  
  158. # legacy
  159. sub timeout    { shift->_elem('timeout',    @_); }
  160. sub parse_head { shift->_elem('parse_head', @_); }
  161. sub max_size   { shift->_elem('max_size',   @_); }
  162.  
  163.  
  164. =item $prot->collect($arg, $response, $collector)
  165.  
  166. Called to collect the content of a request, and process it
  167. appropriately into a scalar, file, or by calling a callback.  If $arg
  168. is undefined, then the content is stored within the $response.  If
  169. $arg is a simple scalar, then $arg is interpreted as a file name and
  170. the content is written to this file.  If $arg is a reference to a
  171. routine, then content is passed to this routine.
  172.  
  173. The $collector is a routine that will be called and which is
  174. reponsible for returning pieces (as ref to scalar) of the content to
  175. process.  The $collector signals EOF by returning a reference to an
  176. empty sting.
  177.  
  178. The return value from collect() is the $response object reference.
  179.  
  180. B<Note:> We will only use the callback or file argument if
  181. $response->is_success().  This avoids sendig content data for
  182. redirects and authentization responses to the callback which would be
  183. confusing.
  184.  
  185. =cut
  186.  
  187. sub collect
  188. {
  189.     my ($self, $arg, $response, $collector) = @_;
  190.     my $content;
  191.     my($parse_head, $max_size) = @{$self}{qw(parse_head max_size)};
  192.  
  193.     my $parser;
  194.     if ($parse_head && $response->content_type eq 'text/html') {
  195.     require HTML::HeadParser;
  196.     $parser = HTML::HeadParser->new($response->{'_headers'});
  197.     }
  198.     my $content_size = 0;
  199.  
  200.     if (!defined($arg) || !$response->is_success) {
  201.     # scalar
  202.     while ($content = &$collector, length $$content) {
  203.         if ($parser) {
  204.         $parser->parse($$content) or undef($parser);
  205.         }
  206.         LWP::Debug::debug("read " . length($$content) . " bytes");
  207.         $response->add_content($$content);
  208.         $content_size += length($$content);
  209.         if (defined($max_size) && $content_size > $max_size) {
  210.         LWP::Debug::debug("Aborting because size limit exceeded");
  211.         $response->push_header("Client-Aborted", "max_size");
  212.         #my $tot = $response->header("Content-Length") || 0;
  213.         #$response->header("X-Content-Range", "bytes 0-$content_size/$tot");
  214.         last;
  215.         }
  216.     }
  217.     }
  218.     elsif (!ref($arg)) {
  219.     # filename
  220.     open(OUT, ">$arg") or
  221.         return HTTP::Response->new(&HTTP::Status::RC_INTERNAL_SERVER_ERROR,
  222.               "Cannot write to '$arg': $!");
  223.         binmode(OUT);
  224.         local($\) = ""; # ensure standard $OUTPUT_RECORD_SEPARATOR
  225.     while ($content = &$collector, length $$content) {
  226.         if ($parser) {
  227.         $parser->parse($$content) or undef($parser);
  228.         }
  229.         LWP::Debug::debug("read " . length($$content) . " bytes");
  230.         print OUT $$content;
  231.         $content_size += length($$content);
  232.         if (defined($max_size) && $content_size > $max_size) {
  233.         LWP::Debug::debug("Aborting because size limit exceeded");
  234.         $response->push_header("Client-Aborted", "max_size");
  235.         #my $tot = $response->header("Content-Length") || 0;
  236.         #$response->header("X-Content-Range", "bytes 0-$content_size/$tot");
  237.         last;
  238.         }
  239.     }
  240.     close(OUT);
  241.     }
  242.     elsif (ref($arg) eq 'CODE') {
  243.     # read into callback
  244.     while ($content = &$collector, length $$content) {
  245.         if ($parser) {
  246.         $parser->parse($$content) or undef($parser);
  247.         }
  248.         LWP::Debug::debug("read " . length($$content) . " bytes");
  249.             eval {
  250.         &$arg($$content, $response, $self);
  251.         };
  252.         if ($@) {
  253.             chomp($@);
  254.         $response->push_header('X-Died' => $@);
  255.         $response->push_header("Client-Aborted", "die");
  256.         last;
  257.         }
  258.     }
  259.     }
  260.     else {
  261.     return HTTP::Response->new(&HTTP::Status::RC_INTERNAL_SERVER_ERROR,
  262.                   "Unexpected collect argument  '$arg'");
  263.     }
  264.     $response;
  265. }
  266.  
  267.  
  268. =item $prot->collect_once($arg, $response, $content)
  269.  
  270. Can be called when the whole response content is available as
  271. $content.  This will invoke collect() with a collector callback that
  272. returns a reference to $content the first time and an empty string the
  273. next.
  274.  
  275. =cut
  276.  
  277. sub collect_once
  278. {
  279.     my($self, $arg, $response) = @_;
  280.     my $content = \ $_[3];
  281.     my $first = 1;
  282.     $self->collect($arg, $response, sub {
  283.     return $content if $first--;
  284.     return \ "";
  285.     });
  286. }
  287.  
  288. 1;
  289.  
  290. =head1 SEE ALSO
  291.  
  292. Inspect the F<LWP/Protocol/file.pm> and F<LWP/Protocol/http.pm> files
  293. for examples of usage.
  294.  
  295. =head1 COPYRIGHT
  296.  
  297. Copyright 1995-2001 Gisle Aas.
  298.  
  299. This library is free software; you can redistribute it and/or
  300. modify it under the same terms as Perl itself.
  301.  
  302. =cut
  303.