home *** CD-ROM | disk | FTP | other *** search
/ Netrunner 2004 October / NETRUNNER0410.ISO / regular / ActivePerl-5.8.4.810-MSWin32-x86.msi / _ee8c97d2a50a4594985f036906862c88 < prev    next >
Encoding:
Text File  |  2004-06-01  |  8.2 KB  |  320 lines

  1. package LWP::RobotUA;
  2.  
  3. # $Id: RobotUA.pm,v 1.27 2004/04/06 13:14:37 gisle Exp $
  4.  
  5. require LWP::UserAgent;
  6. @ISA = qw(LWP::UserAgent);
  7. $VERSION = sprintf("%d.%02d", q$Revision: 1.27 $ =~ /(\d+)\.(\d+)/);
  8.  
  9. require WWW::RobotRules;
  10. require HTTP::Request;
  11. require HTTP::Response;
  12.  
  13. use Carp ();
  14. use LWP::Debug ();
  15. use HTTP::Status ();
  16. use HTTP::Date qw(time2str);
  17. use strict;
  18.  
  19.  
  20. #
  21. # Additional attributes in addition to those found in LWP::UserAgent:
  22. #
  23. # $self->{'delay'}    Required delay between request to the same
  24. #                     server in minutes.
  25. #
  26. # $self->{'rules'}     A WWW::RobotRules object
  27. #
  28.  
  29. sub new
  30. {
  31.     my $class = shift;
  32.     my %cnf;
  33.     if (@_ < 4) {
  34.     # legacy args
  35.     @cnf{qw(agent from rules)} = @_;
  36.     }
  37.     else {
  38.     %cnf = @_;
  39.     }
  40.  
  41.     Carp::croak('LWP::RobotUA agent required') unless $cnf{agent};
  42.     Carp::croak('LWP::RobotUA from address required')
  43.     unless $cnf{from} && $cnf{from} =~ m/\@/;
  44.  
  45.     my $delay = delete $cnf{delay} || 1;
  46.     my $use_sleep = delete $cnf{use_sleep};
  47.     $use_sleep = 1 unless defined($use_sleep);
  48.     my $rules = delete $cnf{rules};
  49.  
  50.     my $self = LWP::UserAgent->new(%cnf);
  51.     $self = bless $self, $class;
  52.  
  53.     $self->{'delay'} = 1;   # minutes
  54.     $self->{'use_sleep'} = 1;
  55.  
  56.     if ($rules) {
  57.     $rules->agent($cnf{agent});
  58.     $self->{'rules'} = $rules;
  59.     }
  60.     else {
  61.     $self->{'rules'} = WWW::RobotRules->new($cnf{agent});
  62.     }
  63.  
  64.     $self;
  65. }
  66.  
  67.  
  68. sub delay     { shift->_elem('delay',     @_); }
  69. sub use_sleep { shift->_elem('use_sleep', @_); }
  70.  
  71.  
  72. sub agent
  73. {
  74.     my $self = shift;
  75.     my $old = $self->SUPER::agent(@_);
  76.     if (@_) {
  77.     # Changing our name means to start fresh
  78.     $self->{'rules'}->agent($self->{'agent'}); 
  79.     }
  80.     $old;
  81. }
  82.  
  83.  
  84. sub rules {
  85.     my $self = shift;
  86.     my $old = $self->_elem('rules', @_);
  87.     $self->{'rules'}->agent($self->{'agent'}) if @_;
  88.     $old;
  89. }
  90.  
  91.  
  92. sub no_visits
  93. {
  94.     my($self, $netloc) = @_;
  95.     $self->{'rules'}->no_visits($netloc) || 0;
  96. }
  97.  
  98. *host_count = \&no_visits;  # backwards compatibility with LWP-5.02
  99.  
  100.  
  101. sub host_wait
  102. {
  103.     my($self, $netloc) = @_;
  104.     return undef unless defined $netloc;
  105.     my $last = $self->{'rules'}->last_visit($netloc);
  106.     if ($last) {
  107.     my $wait = int($self->{'delay'} * 60 - (time - $last));
  108.     $wait = 0 if $wait < 0;
  109.     return $wait;
  110.     }
  111.     return 0;
  112. }
  113.  
  114.  
  115. sub simple_request
  116. {
  117.     my($self, $request, $arg, $size) = @_;
  118.  
  119.     LWP::Debug::trace('()');
  120.  
  121.     # Do we try to access a new server?
  122.     my $allowed = $self->{'rules'}->allowed($request->url);
  123.  
  124.     if ($allowed < 0) {
  125.     LWP::Debug::debug("Host is not visited before, or robots.txt expired.");
  126.     # fetch "robots.txt"
  127.     my $robot_url = $request->url->clone;
  128.     $robot_url->path("robots.txt");
  129.     $robot_url->query(undef);
  130.     LWP::Debug::debug("Requesting $robot_url");
  131.  
  132.     # make access to robot.txt legal since this will be a recursive call
  133.     $self->{'rules'}->parse($robot_url, ""); 
  134.  
  135.     my $robot_req = new HTTP::Request 'GET', $robot_url;
  136.     my $robot_res = $self->request($robot_req);
  137.     my $fresh_until = $robot_res->fresh_until;
  138.     if ($robot_res->is_success) {
  139.         my $c = $robot_res->content;
  140.         if ($robot_res->content_type =~ m,^text/, && $c =~ /^\s*Disallow\s*:/mi) {
  141.         LWP::Debug::debug("Parsing robot rules");
  142.         $self->{'rules'}->parse($robot_url, $c, $fresh_until);
  143.         }
  144.         else {
  145.         LWP::Debug::debug("Ignoring robots.txt");
  146.         $self->{'rules'}->parse($robot_url, "", $fresh_until);
  147.         }
  148.  
  149.     }
  150.     else {
  151.         LWP::Debug::debug("No robots.txt file found");
  152.         $self->{'rules'}->parse($robot_url, "", $fresh_until);
  153.     }
  154.  
  155.     # recalculate allowed...
  156.     $allowed = $self->{'rules'}->allowed($request->url);
  157.     }
  158.  
  159.     # Check rules
  160.     unless ($allowed) {
  161.     my $res = new HTTP::Response
  162.       &HTTP::Status::RC_FORBIDDEN, 'Forbidden by robots.txt';
  163.     $res->request( $request ); # bind it to that request
  164.     return $res;
  165.     }
  166.  
  167.     my $netloc = eval { local $SIG{__DIE__}; $request->url->host_port; };
  168.     my $wait = $self->host_wait($netloc);
  169.  
  170.     if ($wait) {
  171.     LWP::Debug::debug("Must wait $wait seconds");
  172.     if ($self->{'use_sleep'}) {
  173.         sleep($wait)
  174.     }
  175.     else {
  176.         my $res = new HTTP::Response
  177.           &HTTP::Status::RC_SERVICE_UNAVAILABLE, 'Please, slow down';
  178.         $res->header('Retry-After', time2str(time + $wait));
  179.         $res->request( $request ); # bind it to that request
  180.         return $res;
  181.     }
  182.     }
  183.  
  184.     # Perform the request
  185.     my $res = $self->SUPER::simple_request($request, $arg, $size);
  186.  
  187.     $self->{'rules'}->visit($netloc);
  188.  
  189.     $res;
  190. }
  191.  
  192.  
  193. sub as_string
  194. {
  195.     my $self = shift;
  196.     my @s;
  197.     push(@s, "Robot: $self->{'agent'} operated by $self->{'from'}  [$self]");
  198.     push(@s, "    Minimum delay: " . int($self->{'delay'}*60) . "s");
  199.     push(@s, "    Will sleep if too early") if $self->{'use_sleep'};
  200.     push(@s, "    Rules = $self->{'rules'}");
  201.     join("\n", @s, '');
  202. }
  203.  
  204. 1;
  205.  
  206.  
  207. __END__
  208.  
  209. =head1 NAME
  210.  
  211. LWP::RobotUA - a class for well-behaved Web robots
  212.  
  213. =head1 SYNOPSIS
  214.  
  215.   use LWP::RobotUA;
  216.   my $ua = LWP::RobotUA->new('my-robot/0.1', 'me@foo.com');
  217.   $ua->delay(10);  # be very nice -- max one hit every ten minutes!
  218.   ...
  219.  
  220.   # Then just use it just like a normal LWP::UserAgent:
  221.   my $response = $ua->get('http://whatever.int/...');
  222.   ...
  223.  
  224. =head1 DESCRIPTION
  225.  
  226. This class implements a user agent that is suitable for robot
  227. applications.  Robots should be nice to the servers they visit.  They
  228. should consult the F</robots.txt> file to ensure that they are welcomed
  229. and they should not make requests too frequently.
  230.  
  231. But before you consider writing a robot, take a look at
  232. <URL:http://www.robotstxt.org/>.
  233.  
  234. When you use a I<LWP::RobotUA> object as your user agent, then you do not
  235. really have to think about these things yourself; C<robots.txt> files
  236. are automatically consulted and obeyed, the server isn't queried
  237. too rapidly, and so on.  Just send requests
  238. as you do when you are using a normal I<LWP::UserAgent>
  239. object (using C<< $ua->get(...) >>, C<< $ua->head(...) >>,
  240. C<< $ua->request(...) >>, etc.), and this
  241. special agent will make sure you are nice.
  242.  
  243. =head1 METHODS
  244.  
  245. The LWP::RobotUA is a sub-class of LWP::UserAgent and implements the
  246. same methods. In addition the following methods are provided:
  247.  
  248. =over 4
  249.  
  250. =item $ua = LWP::RobotUA->new( %options )
  251.  
  252. =item $ua = LWP::RobotUA->new( $agent, $from )
  253.  
  254. =item $ua = LWP::RobotUA->new( $agent, $from, $rules )
  255.  
  256. The LWP::UserAgent options C<agent> and C<from> are mandatory.  The
  257. options C<delay>, C<use_sleep> and C<rules> initialize attributes
  258. private to the RobotUA.  If C<rules> are not provided, then
  259. C<WWW::RobotRules> is instantiated providing an internal database of
  260. F<robots.txt>.
  261.  
  262. It is also possible to just pass the value of C<agent>, C<from> and
  263. optionally C<rules> as plain positional arguments.
  264.  
  265. =item $ua->delay
  266.  
  267. =item $ua->delay( $minutes )
  268.  
  269. Get/set the minimum delay between requests to the same server, in
  270. I<minutes>.  The default is 1 minute.  Note that this number doesn't
  271. have to be an integer; for example, this sets the delay to 10 seconds:
  272.  
  273.     $ua->delay(10/60);
  274.  
  275. =item $ua->use_sleep
  276.  
  277. =item $ua->use_sleep( $boolean )
  278.  
  279. Get/set a value indicating whether the UA should sleep() if requests
  280. arrive too fast, defined as $ua->delay minutes not passed since
  281. last request to the given server.  The default is TRUE.  If this value is
  282. FALSE then an internal SERVICE_UNAVAILABLE response will be generated.
  283. It will have an Retry-After header that indicates when it is OK to
  284. send another request to this server.
  285.  
  286. =item $ua->rules
  287.  
  288. =item $ua->rules( $rules )
  289.  
  290. Set/get which I<WWW::RobotRules> object to use.
  291.  
  292. =item $ua->no_visits( $netloc )
  293.  
  294. Returns the number of documents fetched from this server host. Yeah I
  295. know, this method should probably have been named num_visits() or
  296. something like that. :-(
  297.  
  298. =item $ua->host_wait( $netloc )
  299.  
  300. Returns the number of I<seconds> (from now) you must wait before you can
  301. make a new request to this host.
  302.  
  303. =item $ua->as_string
  304.  
  305. Returns a string that describes the state of the UA.
  306. Mainly useful for debugging.
  307.  
  308. =back
  309.  
  310. =head1 SEE ALSO
  311.  
  312. L<LWP::UserAgent>, L<WWW::RobotRules>
  313.  
  314. =head1 COPYRIGHT
  315.  
  316. Copyright 1996-2004 Gisle Aas.
  317.  
  318. This library is free software; you can redistribute it and/or
  319. modify it under the same terms as Perl itself.
  320.