blib/lib/HTTP/ProxySelector/Persistent.pm

filter: Statementstmt 86.6% 13 / 15 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 5 / 5 Podpod n/a totaltotal 90.0% 18 / 20 CC 1 SCAR 0.6
CC
1
Cov
87%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
↑ Summary
1 package HTTP::ProxySelector::Persistent;
2  
3 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 4 ▶use integer;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 4 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 0 ▶use BerkeleyDB;
Subroutine BEGIN: called CC=1 SCAR=2.6
8 use vars qw( %h );
9 use Date::Manip;
10  
11 # rand() is used, let's try to make the most of it...
12 srand;
13  
14 =head1 NAME
15  
16 HTTP::ProxySelector::Persistent - Locally cache and use a list of proxy servers for high volume, proxied LWP::UserAgent transactions
17  
18 =head1 VERSION
19  
20 Version 0.02
21  
22 =cut
23  
24 our $VERSION = '0.02';
25  
26 =head1 SYNOPSIS
27  
28 This module is a fork from HTTP::ProxySelector (written by Eyal Udassin) that is modified to:
29  
30 =over 1
31  
32 =item * Require less trips to look up proxy lists by caching them locally (bandwidth economy and speed).
33  
34 =item * Almost always set your useragent to a valid proxy (reliability).
35  
36 =item * Ensure that you never retry a failed proxy in a subsequent proxy selection call (minimum # of timeouts possible).
37  
38 =item * Leave the cache of proxy servers in place after execution for the next call to use (persistence).
39  
40 =back
41  
42 use HTTP::ProxySelector;
43 use LWP::UserAgent;
44  
45 # Instantiate
46 my $selector = HTTP::ProxySelector::Persistent->new( db_file => "/tmp/proxy_cache.bdb" );
47 my $ua = LWP::UserAgent->new();
48  
49 # Assign a _ proxy to the UserAgent object.
50 $selector->set_proxy($ua) or die $selector->error();
51
52 # Just in case you need to know the chosen proxy
53 print 'Selected proxy: ',$selector->get_proxy(),"\n";
54  
55 # Perform a quick proxied get. Lets you skip the useragent stuff.
56 my $html = $selector->proxied_get( url => "http://www.google.com" ) or die $selector->error();
57  
58 =head1 PREREQUISITES
59  
60 HTTP::ProxySelector::Persistent requires you to have these perl modules installed:
61  
62 =over 1
63  
64 =item * BerkeleyDB
65  
66 =item * LWP::UserAgent
67  
68 =item * Date::Manip
69  
70 =back
71  
72 =head1 PUBLIC METHODS
73  
74 =head2 new()
75  
76 B<new> is the constructor for HTTP::ProxySelector::Persistent objects.
77  
78 Returns a new HTTP::ProxySelector::Persistent object.
79  
80 Accepts a key-value list of options as arguments. The option keys are:
81  
82 =head3 db_file
83  
84 The full path and filename for the proxy cache database file. You must have permission to write in this directory. This option is mandatory, it has no default!
85  
86 =head4 Example :
87  
88 $select = HTTP::ProxySelector::Persistent->new( db_file => "/tmp/proxy_cache.bdb" );
89  
90 =head3 sites
91  
92 Reference to a list of sites containing the proxy lists.
93  
94 =head4 Example :
95  
96 $select = HTTP::ProxySelector::Persistent->new( sites => ['http://www.proxylist.com/list.htm'] );
97  
98 =head4 Default:
99  
100 [ 'http://hidemyass.com/free_proxy_lists.php?sort=DESC&country=1&limit=100' ]
101  
102 =head3 update_interval
103  
104 How often to update the cached list of proxy servers. Must be readable by Date::Manip.
105  
106 =head4 Example:
107  
108 $select = HTTP::ProxySelector::Persistent->new( update_interval => "20 minutes" )
109 or die "Couldn't create proxyselector!";
110  
111 =head4 Default
112  
113 "15 minutes"
114  
115 =head3 testsite
116  
117 Destination site to test the proxy with.
118  
119 =head4 Example :
120  
121 $select = HTTP::ProxySelector::Persistent->new( testsite => 'http://yahoo.com' );
122  
123 =head4 Default
124  
125 http://www.google.com
126  
127 =cut
128  
129 # Constructor. Enables Inheritance
130 sub new {
131 my $this = shift;
132 my $class = ref($this) || $this;
133 my $self = {};
134 bless $self, $class;
135 my $status;
136  
137 if (@_) {
138 my %options = @_;
139 $self->{options} = \%options;
140 }
141 # Defaults
142 unless ($self->{options}{sites}) {
143 @{$self->{options}{sites}} = ('http://hidemyass.com/free_proxy_lists.php?sort=DESC&country=1&limit=100');
144 }
145 $self->{options}{testsite} ||= 'http://www.google.com';
146 $self->{options}{update_interval} ||= "15 minutes";
147 # See if the database file exists
148 return "Error: please provide a database file to use as an argument to the new() function." unless ( $self->{options}{db_file} );
149 ( $self->{options}{db_file} ) = ( $self->{options}{db_file} =~ /(.*)/s ); # untaint the database filename so I can delete it later
150 if ( -e $self->{options}{db_file} ) {
151 # If it does exist, see if the data is still valid (check the date)
152 tie %h, "BerkeleyDB::Hash",
153 -Filename => $self->{options}{db_file},
154 -Flags => DB_CREATE
155 or die "Cannot open file $self->{options}{db_file}: $! $BerkeleyDB::Error\n" ;
156 if ( exists $h{"date"} ) { # cache file contains a date stamp
157 if ( Date_Cmp( $h{"date"}, DateCalc( "today", "-" . $self->{options}{update_interval} ) ) < 0 ) {
158 # It's too old, fetch new data
159 # removing the whole database file first prevents database files from getting too huge
160 untie %h;
161 unlink( $self->{options}{db_file} );
162 $status = $self->_fetch_proxies();
163 }
164 else { # The cache is good and current enough to be used
165 untie %h;
166 $status = 1;
167 }
168 }
169 else { # cache database file exists, but is malformed, let's rebuild it
170 untie %h;
171 unlink( $self->{options}{db_file} );
172 $status = $self->_fetch_proxies();
173 }
174 }
175 else { # If it doesn't exist, create and populate it
176 $status = $self->_fetch_proxies();
177 }
178 ( $status ) ? return $self : return $status;
179 }
180  
181 =head2 set_proxy()
182  
183 Chooses a proxy at random from the cache database and sets it as the proxy for a LWP::UserAgent. Automatically tests the proxy. If the proxy fails the test, it removes the proxy from the cache and chooses another one until it finds a working proxy. If necessary, this sub will try every proxy in the cache database.
184  
185 Arguments: A LWP::Useragent object
186  
187 Returns: 1 (success) or undef upon failure (sets an error).
188  
189 =head3 Example:
190  
191 $select->set_proxy( $ua ) or die $select->error();
192  
193 =cut
194  
195 # Accept a proxy
196 sub set_proxy {
197 my ($self, $ua) = @_;
198 # Open the cache database
199 tie %h, "BerkeleyDB::Hash", -Filename => $self->{options}{db_file},
200 or $self->error( "Cannot open file $self->{options}{db_file}: $! $BerkeleyDB::Error" ) and return undef ;
201 my $proxytest = 0;
202 do {
203 # Select a random proxy from the cache
204 my $proxy;
205 my @proxies = keys( %h );
206 do { $proxy = $proxies[ int( rand( scalar( @proxies ) ) ) ]; } until ( $proxy ne "date" );
207 $self->{selected_proxy} = $proxy;
208 $ua->proxy(['http', 'ftp'], 'http://' . $self->{selected_proxy});
209 # Test the proxy
210 $proxytest = $self->test_proxy( $ua );
211 # Delete the proxy if it failed the test
212 delete $h{ $proxy } unless ( $proxytest );
213 } until ( $proxytest || ( scalar( keys( %h ) ) <= 1 ) );
214 untie %h;
215 if ( $proxytest ) {
216 return 1;
217 }
218 else {
219 # delete the proxy file to force the next new() call to create a new cache
220 unlink $self->{options}{db_file};
221 $self->error( 'All proxies were bad' ) and return undef;
222 }
223 }
224  
225 =head2 get_proxy()
226  
227 Arguments: none.
228  
229 Returns: a scalar string containing the address of the selected proxy.
230  
231 =head3 Example:
232  
233 $proxy_address = $select->get_proxy();
234  
235 =cut
236  
237 sub get_proxy {
238 my $self = shift;
239 return $self->{selected_proxy};
240 }
241  
242  
243 =head2 test_proxy()
244  
245 Tests the proxy by trying to access a site (specified using the "testsite" option when constructing an HTTP::ProxySelector::Persistent object). It temporarily sets the timeout to be 1/2 of the timeout set in the useragent that's passed to it. If the useragent that's passed doesn't have a timeout set, it defaults to 5 seconds.
246  
247 Arguments: an LWP::UserAgent object.
248  
249 Returns: 1 for success or undef for failure (sets an error).
250  
251 Example:
252  
253 ( $select->test_proxy( $ua ) ) ? print "Good test\n" : die $select->error();
254  
255 =cut
256  
257 sub test_proxy {
258 my ($self, $ua) = @_;
259 my ( $original_timeout, $test_timeout ) = ( $ua->timeout(), int( $ua->timeout() / 2 ) );
260 $test_timeout = 5 if ( $original_timeout == 180 );
261 $test_timeout = 1 if ( $test_timeout == 0 ); # prevent 0 second timeouts
262  
263 $ua->timeout( $test_timeout );
264 my $response = $ua->get($self->{options}{testsite});
265 $ua->timeout( $original_timeout );
266
267 return 1 if ( $response->is_success() ); # successful exit
268
269 # Error out
270 $response->is_error() ? $self->error( $response->error_as_HTML() ) : $self->error( "Unknown error while testing proxy" );
271 return undef;
272 }
273  
274 =head2 proxied_get()
275  
276 Selects a proxy and attempts to download the URL passed to this function as an argument. If the download fails, it will remove the proxy from the cache, select another one, and retry until the download succeeds. When it does succeed, this function returns the content of the response. If all you need to do is download one webpage one time, this should take about half as long as manually setting a useragent and then using that useragent to do a second grab after the automatic proxy test.
277  
278 If all you're doing is a single HTTP get in your script and that's it, this is a faster way to do it. Setting the useragent proxy involves at least one mandatory test before the module even gives you a proxy to make your real get with. This way uses your actual HTTP get instead of testing first. It just persistently attempts to make your get and doesn't quit until it either runs out of proxies or succeeds in the HTTP get.
279  
280 Each call to this method chooses a new proxy server from the cache. Using two calls to proxied_get() in the same script will most likely use two completely different proxy servers.
281  
282 =head3 Arguments are options in a single hash with these keys:
283  
284 =over 1
285  
286 =item B<url> - a scalar URL to be downloaded. Mandatory.
287  
288 =item B<timeout> - a scalar integer number of how many seconds to allow before declaring the attempt a failure and trying a new proxy. Optional, defaults to 2.
289  
290 =item B<ua> - An LWP::UserAgent that you'd like to use for the transaction. Optional. This sub constructs a default LWP useragent if you don't provide one.
291  
292 =back
293  
294 =head3 Returns:
295  
296 The content of the page located at $url upon success, or undef upon failure (sets an error).
297  
298 =head3 Example
299  
300 my $html = $selector->proxied_get( url => $url, timeout => 5 ) or die $selector->error();
301  
302 =cut
303  
304 sub proxied_get {
305 my ( $self, %options ) = @_;
306 $options{timeout} ||= 2; # Set default timeout
307 my $ua = $options{ua} || LWP::UserAgent->new( timeout => $options{timeout} );
308 $self->error( "Did not provide a URL to proxied_get" ) and return undef unless defined $options{url};
309  
310 # Open the cache database
311 tie %h, "BerkeleyDB::Hash", -Filename => $self->{options}{db_file}
312 or $self->error( "Cannot open file $self->{options}{db_file}: $! $BerkeleyDB::Error" ) and return undef;
313 my $response;
314 do {
315 # Select a random proxy from the cache
316 my $proxy;
317 my @proxies = keys( %h );
318 do { $proxy = $proxies[ int( rand( scalar( @proxies ) ) ) ]; } until ( $proxy ne "date" );
319 $self->{selected_proxy} = $proxy;
320 $ua->proxy(['http', 'ftp'], 'http://' . $self->{selected_proxy});
321 $response = $ua->get( $options{url} ); # Download using the proxy
322 delete $h{ $proxy } unless ( $response->is_success() ); # Delete the proxy if it failed to download
323 } until ( $response->is_success() || ( scalar( keys( %h ) ) <= 1 ) );
324 untie %h;
325 if ( $response->is_success() ) {
326 return $response->content();
327 }
328 else {
329 # delete the proxy file to force the next new() call to create a new cache
330 unlink $self->{options}{db_file};
331 $self->error( "All proxies were bad" ) and return undef;
332 }
333 }
334  
335 =head2 error()
336  
337 If any portion of the module encounters an error, calling this function will return a string describing the last error. Read-only. No arguments.
338  
339 =head3 Example
340  
341 my $html = $selector->proxied_get( $url_that_doesnt_exist ) or die $selector->error();
342  
343 =cut
344  
345 sub error {
346 my ( $self, $msg ) = @_;
347 if ( !defined($msg) or ! $self->isa(__PACKAGE__) ) {
348 my $error = $self->{error};
349 $self->{error} = undef;
350 return $error;
351 }
352 else {
353 $self->{error} = $msg;
354 }
355 }
356  
357 =head1 PRIVATE FUNCTIONS
358  
359 =head2 _fetch_proxies()
360  
361 Retrieves the proxy lists, extracts the proxy servers and caches them locally in a BerkeleyDB. This sub assumes that the cache database file does not exist. If this function were called before the cache database file were deleted, you would have duplicate entries in the cache and a bunch of old, potentially inoperative proxies stored in the cache. You should never have to call this method yourself. The B<new()> method of the HTTP::ProxySelector::Persistent object uses this sub when the proxy cache database is either expired, malformed, empty or missing.
362  
363 =head3 Arguments: none.
364  
365 =head3 Returns:
366  
367 1 upon success, or undef upon failure.
368  
369 =cut
370  
371 sub _fetch_proxies {
372 my $self = shift;
373 tie %h, "BerkeleyDB::Hash",
374 -Filename => $self->{options}{db_file},
375 -Flags => DB_CREATE
376 or self->error("_fetch_proxies: Cannot open file $self->{options}{db_file}: $! $BerkeleyDB::Error") and return undef;
377  
378 # Fetch the proxy lists
379 my $ua = LWP::UserAgent->new;
380 my $proxytext = "";
381 foreach my $page ( @{ $self->{options}{sites} } ) {
382 my $response = $ua->get( $page );
383 $proxytext .= $response->content();
384 }
385 # Extract the proxies from the downloaded web pages
386 # Strip any HTML from the proxylists
387 $proxytext =~ s#</?p.*?>|<br ?/?>|</?li>#\n#gis;
388 $proxytext =~ s#<.+?>##gis;
389 $proxytext =~ s#\n+#\n#gs;
390 # Standardize port annotation
391 $proxytext =~ s#((?:[\w\-]+\.)+[\w\-]+):?\s+(\d{1,5})\s*#$1:$2\n#gs;
392 my @proxy_list = $proxytext =~ m#(?:\w+://)?((?:[\w\-]+\.)+[\w\-]+:\d{1,5})#g; # text or IP addresses of proxy servers
393 unless (@proxy_list) { $self->error( "_fetch_proxies: Couldn't find any proxies" ) and return undef; }
394 $h{"date"} = ParseDate( "today" );
395 foreach my $proxy ( @proxy_list ) { $h{ $proxy } = 1; }
396 untie %h;
397 return 1;
398 }
399  
400 =head1 TODO
401  
402 =over 2
403  
404 =item * Need to find better proxylists for the test scripts. By and large, the free proxylists I found had a bunch of bad proxy servers in them. This makes my tests look bad because 'garbage in = garbage out.'
405  
406 =back
407  
408 =head1 AUTHOR
409  
410 Michael Trowbridge, C<< <michael.a.trowbridge at gmail.com> >>
411  
412 =head1 BUGS
413  
414 Please report any bugs or feature requests to
415 C<bug-http-proxyselector-persistent at rt.cpan.org>, or through the web interface at
416 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=HTTP-ProxySelector-Persistent>.
417 I will be notified, and then you'll automatically be notified of progress on
418 your bug as I make changes.
419  
420 =head1 SUPPORT
421  
422 You can find documentation for this module with the perldoc command.
423  
424 perldoc HTTP::ProxySelector::Persistent
425  
426 You can also look for information at:
427  
428 =over 4
429  
430 =item * AnnoCPAN: Annotated CPAN documentation
431  
432 L<http://annocpan.org/dist/HTTP-ProxySelector-Persistent>
433  
434 =item * CPAN Ratings
435  
436 L<http://cpanratings.perl.org/d/HTTP-ProxySelector-Persistent>
437  
438 =item * RT: CPAN's request tracker
439  
440 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=HTTP-ProxySelector-Persistent>
441  
442 =item * Search CPAN
443  
444 L<http://search.cpan.org/dist/HTTP-ProxySelector-Persistent>
445  
446 =back
447  
448 =head1 ACKNOWLEDGEMENTS
449  
450 This module is a fork from HTTP::ProxySelector v0.02. HTTP::ProxySelector v0.02 is copyright 2003 Eyal Udassin.
451  
452 Error method was written by Allen Day and borrowed from Geo::Google.
453  
454 =head1 COPYRIGHT & LICENSE
455  
456 Copyright 2007 Michael Trowbridge, all rights reserved.
457  
458 This program is free software; you can redistribute it and/or modify it
459 under the same terms as Perl itself.
460  
461 =cut
462  
463 1; # End of HTTP::ProxySelector::Persistent
↑ Summary