From 40b4b6e177c62a14c166dbba6adf3abc415af4b2 Mon Sep 17 00:00:00 2001 From: Karl Berry Date: Tue, 18 Apr 2017 23:10:57 +0000 Subject: tlperl 5.24.1 from siep git-svn-id: svn://tug.org/texlive/trunk@43914 c570f23f-e606-0410-a88d-b1316a301751 --- Master/tlpkg/tlperl/site/lib/HTTP/Cookies.pm | 157 ++- .../tlperl/site/lib/HTTP/Cookies/Microsoft.pm | 313 +++-- .../tlpkg/tlperl/site/lib/HTTP/Cookies/Netscape.pm | 91 +- Master/tlpkg/tlperl/site/lib/LWP.pm | 46 +- Master/tlpkg/tlperl/site/lib/LWP/Authen/Basic.pm | 1 + Master/tlpkg/tlperl/site/lib/LWP/Authen/Digest.pm | 4 +- Master/tlpkg/tlperl/site/lib/LWP/Authen/Ntlm.pm | 45 +- Master/tlpkg/tlperl/site/lib/LWP/ConnCache.pm | 111 +- Master/tlpkg/tlperl/site/lib/LWP/Debug.pm | 83 +- .../tlpkg/tlperl/site/lib/LWP/Debug/TraceHTTP.pm | 26 + Master/tlpkg/tlperl/site/lib/LWP/DebugFile.pm | 2 +- Master/tlpkg/tlperl/site/lib/LWP/MemberMixin.pm | 22 +- Master/tlpkg/tlperl/site/lib/LWP/Protocol.pm | 128 ++- Master/tlpkg/tlperl/site/lib/LWP/Protocol/GHTTP.pm | 73 -- Master/tlpkg/tlperl/site/lib/LWP/Protocol/cpan.pm | 12 +- Master/tlpkg/tlperl/site/lib/LWP/Protocol/data.pm | 12 +- Master/tlpkg/tlperl/site/lib/LWP/Protocol/file.pm | 23 +- Master/tlpkg/tlperl/site/lib/LWP/Protocol/ftp.pm | 647 +++++------ .../tlpkg/tlperl/site/lib/LWP/Protocol/gopher.pm | 16 +- Master/tlpkg/tlperl/site/lib/LWP/Protocol/http.pm | 22 +- .../tlpkg/tlperl/site/lib/LWP/Protocol/loopback.pm | 6 +- .../tlpkg/tlperl/site/lib/LWP/Protocol/mailto.pm | 29 +- Master/tlpkg/tlperl/site/lib/LWP/Protocol/nntp.pm | 129 ++- Master/tlpkg/tlperl/site/lib/LWP/Protocol/nogo.pm | 11 +- Master/tlpkg/tlperl/site/lib/LWP/RobotUA.pm | 77 +- Master/tlpkg/tlperl/site/lib/LWP/Simple.pm | 94 +- Master/tlpkg/tlperl/site/lib/LWP/UserAgent.pm | 1212 +++++++++++--------- Master/tlpkg/tlperl/site/lib/Net/HTTP.pm | 35 +- Master/tlpkg/tlperl/site/lib/Net/HTTP/Methods.pm | 43 +- Master/tlpkg/tlperl/site/lib/Net/HTTP/NB.pm | 35 +- Master/tlpkg/tlperl/site/lib/Net/HTTPS.pm | 42 +- Master/tlpkg/tlperl/site/lib/Socket.pm | 32 +- Master/tlpkg/tlperl/site/lib/Test/Fatal.pm | 364 ++++++ .../tlpkg/tlperl/site/lib/Test/RequiresInternet.pm | 131 +++ Master/tlpkg/tlperl/site/lib/Try/Tiny.pm | 804 +++++++++++++ .../tlperl/site/lib/auto/Digest/SHA1/SHA1.dll | Bin 25088 -> 23552 bytes .../tlperl/site/lib/auto/HTML/Parser/Parser.dll | Bin 55808 -> 52224 bytes Master/tlpkg/tlperl/site/lib/auto/LWP/.packlist | 33 - .../tlperl/site/lib/auto/Math/Int64/Int64.dll | Bin 80896 -> 71680 bytes .../tlpkg/tlperl/site/lib/auto/Socket/Socket.dll | Bin 35840 -> 40448 bytes .../tlperl/site/lib/auto/Test/Fatal/.packlist | 1 + .../site/lib/auto/Test/RequiresInternet/.packlist | 1 + .../tlperl/site/lib/auto/Tk/Canvas/Canvas.dll | Bin 211968 -> 204288 bytes .../tlperl/site/lib/auto/Tk/Compound/Compound.dll | Bin 27136 -> 27648 bytes .../lib/auto/Tk/DragDrop/Win32Site/Win32Site.dll | Bin 16896 -> 17920 bytes .../tlpkg/tlperl/site/lib/auto/Tk/Entry/Entry.dll | Bin 53248 -> 50176 bytes .../tlpkg/tlperl/site/lib/auto/Tk/Event/Event.dll | Bin 64512 -> 62976 bytes .../tlpkg/tlperl/site/lib/auto/Tk/HList/HList.dll | Bin 67072 -> 66560 bytes Master/tlpkg/tlperl/site/lib/auto/Tk/IO/IO.dll | Bin 16896 -> 16384 bytes Master/tlpkg/tlperl/site/lib/auto/Tk/JPEG/JPEG.dll | Bin 129024 -> 145920 bytes .../tlperl/site/lib/auto/Tk/Listbox/Listbox.dll | Bin 40448 -> 38400 bytes .../site/lib/auto/Tk/Menubutton/Menubutton.dll | Bin 28160 -> 28672 bytes .../tlperl/site/lib/auto/Tk/NBFrame/NBFrame.dll | Bin 30720 -> 29696 bytes Master/tlpkg/tlperl/site/lib/auto/Tk/PNG/PNG.dll | Bin 218112 -> 242176 bytes .../tlperl/site/lib/auto/Tk/Pixmap/Pixmap.dll | Bin 34304 -> 32768 bytes .../tlpkg/tlperl/site/lib/auto/Tk/Scale/Scale.dll | Bin 31744 -> 32256 bytes .../site/lib/auto/Tk/Scrollbar/Scrollbar.dll | Bin 28672 -> 29184 bytes .../tlpkg/tlperl/site/lib/auto/Tk/TList/TList.dll | Bin 37888 -> 38912 bytes Master/tlpkg/tlperl/site/lib/auto/Tk/Text/Text.dll | Bin 131072 -> 132096 bytes .../tlperl/site/lib/auto/Tk/TixGrid/TixGrid.dll | Bin 84992 -> 83968 bytes Master/tlpkg/tlperl/site/lib/auto/Tk/Tk.dll | Bin 944640 -> 940544 bytes Master/tlpkg/tlperl/site/lib/auto/Tk/X/X.dll | Bin 30720 -> 33792 bytes Master/tlpkg/tlperl/site/lib/auto/Tk/Xlib/Xlib.dll | Bin 37376 -> 34816 bytes .../tlpkg/tlperl/site/lib/auto/Try/Tiny/.packlist | 1 + .../tlpkg/tlperl/site/lib/auto/Win32/API/API.dll | Bin 32768 -> 32256 bytes .../site/lib/auto/Win32/API/Callback/Callback.dll | Bin 24576 -> 25600 bytes .../tlperl/site/lib/auto/Win32/Console/Console.dll | Bin 59392 -> 48640 bytes .../tlpkg/tlperl/site/lib/auto/Win32/OLE/OLE.dll | Bin 149504 -> 135680 bytes .../tlperl/site/lib/auto/Win32/Process/Process.dll | Bin 31232 -> 28672 bytes .../site/lib/auto/Win32/Shortcut/Shortcut.dll | Bin 55808 -> 52224 bytes .../site/lib/auto/Win32API/Registry/Registry.dll | Bin 223744 -> 165888 bytes .../tlperl/site/lib/auto/libwww/perl/.packlist | 33 + Master/tlpkg/tlperl/site/lib/libwww/lwpcook.pod | 308 +++++ Master/tlpkg/tlperl/site/lib/libwww/lwptut.pod | 820 +++++++++++++ Master/tlpkg/tlperl/site/lib/lwpcook.pod | 311 ----- Master/tlpkg/tlperl/site/lib/lwptut.pod | 839 -------------- 76 files changed, 4415 insertions(+), 2810 deletions(-) create mode 100644 Master/tlpkg/tlperl/site/lib/LWP/Debug/TraceHTTP.pm delete mode 100644 Master/tlpkg/tlperl/site/lib/LWP/Protocol/GHTTP.pm create mode 100644 Master/tlpkg/tlperl/site/lib/Test/Fatal.pm create mode 100644 Master/tlpkg/tlperl/site/lib/Test/RequiresInternet.pm create mode 100644 Master/tlpkg/tlperl/site/lib/Try/Tiny.pm delete mode 100644 Master/tlpkg/tlperl/site/lib/auto/LWP/.packlist create mode 100644 Master/tlpkg/tlperl/site/lib/auto/Test/Fatal/.packlist create mode 100644 Master/tlpkg/tlperl/site/lib/auto/Test/RequiresInternet/.packlist create mode 100644 Master/tlpkg/tlperl/site/lib/auto/Try/Tiny/.packlist create mode 100644 Master/tlpkg/tlperl/site/lib/auto/libwww/perl/.packlist create mode 100644 Master/tlpkg/tlperl/site/lib/libwww/lwpcook.pod create mode 100644 Master/tlpkg/tlperl/site/lib/libwww/lwptut.pod delete mode 100644 Master/tlpkg/tlperl/site/lib/lwpcook.pod delete mode 100644 Master/tlpkg/tlperl/site/lib/lwptut.pod (limited to 'Master/tlpkg/tlperl/site/lib') diff --git a/Master/tlpkg/tlperl/site/lib/HTTP/Cookies.pm b/Master/tlpkg/tlperl/site/lib/HTTP/Cookies.pm index 79ac4f27f84..98bd7421012 100644 --- a/Master/tlpkg/tlperl/site/lib/HTTP/Cookies.pm +++ b/Master/tlpkg/tlperl/site/lib/HTTP/Cookies.pm @@ -1,5 +1,5 @@ package HTTP::Cookies; - +$HTTP::Cookies::VERSION = '6.03'; use strict; use HTTP::Date qw(str2time parse_date time2str); use HTTP::Headers::Util qw(_split_header_words join_header_words); @@ -165,12 +165,32 @@ sub add_cookie_header unshift(@cval, $old); } $request->header(Cookie => join("; ", @cval)); + if (my $hash = $request->{_http_cookies}) { + %$hash = (map split(/=/, $_, 2), @cval); + } } $request; } +sub get_cookies +{ + my $self = shift; + my $url = shift; + $url = "https://$url" unless $url =~ m,^[a-zA-Z][a-zA-Z0-9.+\-]*:,; + require HTTP::Request; + my $req = HTTP::Request->new(GET => $url); + my $cookies = $req->{_http_cookies} = {}; + $self->add_cookie_header($req); + if (@_) { + return map $cookies->{$_}, @_ if wantarray; + return $cookies->{$_[0]}; + } + return $cookies; +} + + sub extract_cookies { my $self = shift; @@ -411,11 +431,9 @@ sub save { my $self = shift; my $file = shift || $self->{'file'} || return; - local(*FILE); - open(FILE, ">$file") or die "Can't open $file: $!"; - print FILE "#LWP-Cookies-1.0\n"; - print FILE $self->as_string(!$self->{ignore_discard}); - close(FILE); + open(my $fh, '>', $file) or die "Can't open $file: $!"; + print {$fh} "#LWP-Cookies-1.0\n"; + print {$fh} $self->as_string(!$self->{ignore_discard}); 1; } @@ -424,43 +442,47 @@ sub load { my $self = shift; my $file = shift || $self->{'file'} || return; - local(*FILE, $_); + local $/ = "\n"; # make sure we got standard record separator - open(FILE, $file) or return; - my $magic = ; - unless ($magic =~ /^\#LWP-Cookies-(\d+\.\d+)/) { - warn "$file does not seem to contain cookies"; - return; + open(my $fh, '<', $file) or return; + + # check that we have the proper header + my $magic = <$fh>; + chomp $magic; + unless ($magic =~ /^#LWP-Cookies-\d+\.\d+/) { + warn "$file does not seem to contain cookies"; + return; } - while () { - next unless s/^Set-Cookie3:\s*//; - chomp; - my $cookie; - for $cookie (_split_header_words($_)) { - my($key,$val) = splice(@$cookie, 0, 2); - my %hash; - while (@$cookie) { - my $k = shift @$cookie; - my $v = shift @$cookie; - $hash{$k} = $v; - } - my $version = delete $hash{version}; - my $path = delete $hash{path}; - my $domain = delete $hash{domain}; - my $port = delete $hash{port}; - my $expires = str2time(delete $hash{expires}); - - my $path_spec = exists $hash{path_spec}; delete $hash{path_spec}; - my $secure = exists $hash{secure}; delete $hash{secure}; - my $discard = exists $hash{discard}; delete $hash{discard}; - - my @array = ($version,$val,$port, - $path_spec,$secure,$expires,$discard); - push(@array, \%hash) if %hash; - $self->{COOKIES}{$domain}{$path}{$key} = \@array; - } + + # go through the file + while (my $line = <$fh>) { + chomp $line; + next unless $line =~ s/^Set-Cookie3:\s*//; + my $cookie; + for $cookie (_split_header_words($line)) { + my($key,$val) = splice(@$cookie, 0, 2); + my %hash; + while (@$cookie) { + my $k = shift @$cookie; + my $v = shift @$cookie; + $hash{$k} = $v; + } + my $version = delete $hash{version}; + my $path = delete $hash{path}; + my $domain = delete $hash{domain}; + my $port = delete $hash{port}; + my $expires = str2time(delete $hash{expires}); + + my $path_spec = exists $hash{path_spec}; delete $hash{path_spec}; + my $secure = exists $hash{secure}; delete $hash{secure}; + my $discard = exists $hash{discard}; delete $hash{discard}; + + my @array = ($version, $val, $port, $path_spec, $secure, $expires, + $discard); + push(@array, \%hash) if %hash; + $self->{COOKIES}{$domain}{$path}{$key} = \@array; + } } - close(FILE); 1; } @@ -600,12 +622,18 @@ sub _normalize_path # so that plain string compare can be used 1; -__END__ +=pod + +=encoding UTF-8 =head1 NAME HTTP::Cookies - HTTP cookie jars +=head1 VERSION + +version 6.03 + =head1 SYNOPSIS use HTTP::Cookies; @@ -635,7 +663,7 @@ to both store and retrieve information on the client side of the connection. For more information about cookies refer to and . This module also implements the -new style cookies described in I. +new style cookies described in L. The two variants of cookies are supposed to be able to coexist happily. Instances of the class I are able to store a collection @@ -644,6 +672,22 @@ information to initialize Cookie-headers in I objects. The state of a I object can be saved in and restored from files. +=head1 LIMITATIONS + +This module does not support L<< Public Suffix|https://publicsuffix.org/ +>> encouraged by a more recent standard, L<< RFC +6265|https://tools.ietf.org/html/rfc6265 >>. + +This module's shortcomings mean that a malicious Web site can set +cookies to track your user agent across all sites under a top level +domain. See F<< t/publicsuffix.t >> in this module's distribution for +details. + +L<< HTTP::CookieJar::LWP >> supports Public Suffix, but only provides a +limited subset of this module's functionality and L<< does not +support|HTTP::CookieJar/LIMITATIONS-AND-CAVEATS >> standards older than +I. + =head1 METHODS The following methods are provided: @@ -668,6 +712,16 @@ Future parameters might include (not yet implemented): no_cookies list of domain names that we never return cookies to +=item $cookie_jar->get_cookies( $url_or_domain ) + +=item $cookie_jar->get_cookies( $url_or_domain, $cookie_key,... ) + +Returns a hash of the cookies that applies to the given URL. If a +domainname is given as argument, then a prefix of "https://" is assumed. + +If one or more $cookie_key parameters are provided return the given values, +or C if the cookie isn't available. + =item $cookie_jar->add_cookie_header( $request ) The add_cookie_header() method will set the appropriate Cookie:-header @@ -687,7 +741,7 @@ The set_cookie() method updates the state of the $cookie_jar. The $key, $val, $domain, $port and $path arguments are strings. The $path_spec, $secure, $discard arguments are boolean values. The $maxage value is a number indicating number of seconds that this cookie will -live. A value <= 0 will delete this cookie. %rest defines +live. A value of $maxage <= 0 will delete this cookie. %rest defines various other attributes like "Comment" and "CommentURL". =item $cookie_jar->save @@ -772,10 +826,19 @@ cookies with the I attribute. L, L -=head1 COPYRIGHT +=head1 AUTHOR + +Gisle Aas -Copyright 1997-2002 Gisle Aas +=head1 COPYRIGHT AND LICENSE -This library is free software; you can redistribute it and/or -modify it under the same terms as Perl itself. +This software is copyright (c) 2002-2017 by Gisle Aas. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut + +__END__ +#ABSTRACT: HTTP cookie jars diff --git a/Master/tlpkg/tlperl/site/lib/HTTP/Cookies/Microsoft.pm b/Master/tlpkg/tlperl/site/lib/HTTP/Cookies/Microsoft.pm index 9c69fa364cf..bffa587adf9 100644 --- a/Master/tlpkg/tlperl/site/lib/HTTP/Cookies/Microsoft.pm +++ b/Master/tlpkg/tlperl/site/lib/HTTP/Cookies/Microsoft.pm @@ -1,56 +1,56 @@ package HTTP::Cookies::Microsoft; - +$HTTP::Cookies::Microsoft::VERSION = '6.03'; use strict; use vars qw(@ISA $VERSION); -$VERSION = "6.00"; +$VERSION = "6.01"; require HTTP::Cookies; @ISA=qw(HTTP::Cookies); sub load_cookies_from_file { - my ($file) = @_; - my @cookies; - my ($key, $value, $domain_path, $flags, $lo_expire, $hi_expire); - my ($lo_create, $hi_create, $sep); - - open(COOKIES, $file) || return; - - while ($key = ) - { - chomp($key); - chomp($value = ); - chomp($domain_path= ); - chomp($flags = ); # 0x0001 bit is for secure - chomp($lo_expire = ); - chomp($hi_expire = ); - chomp($lo_create = ); - chomp($hi_create = ); - chomp($sep = ); - - if (!defined($key) || !defined($value) || !defined($domain_path) || - !defined($flags) || !defined($hi_expire) || !defined($lo_expire) || - !defined($hi_create) || !defined($lo_create) || !defined($sep) || - ($sep ne '*')) - { - last; - } - - if ($domain_path =~ /^([^\/]+)(\/.*)$/) - { - my $domain = $1; - my $path = $2; - - push(@cookies, {KEY => $key, VALUE => $value, DOMAIN => $domain, - PATH => $path, FLAGS =>$flags, HIXP =>$hi_expire, - LOXP => $lo_expire, HICREATE => $hi_create, - LOCREATE => $lo_create}); - } - } - - return \@cookies; + my ($file) = @_; + my @cookies; + + open (my $fh, '<', $file) || return; + + while (my $key = <$fh>) { + chomp $key; + my ($value, $domain_path, $flags, $lo_expire, $hi_expire); + my ($lo_create, $hi_create, $sep); + chomp($value = <$fh>); + chomp($domain_path= <$fh>); + chomp($flags = <$fh>); # 0x0001 bit is for secure + chomp($lo_expire = <$fh>); + chomp($hi_expire = <$fh>); + chomp($lo_create = <$fh>); + chomp($hi_create = <$fh>); + chomp($sep = <$fh>); + + if (!defined($key) || !defined($value) || !defined($domain_path) || + !defined($flags) || !defined($hi_expire) || !defined($lo_expire) || + !defined($hi_create) || !defined($lo_create) || !defined($sep) || + ($sep ne '*')) + { + last; + } + + if ($domain_path =~ /^([^\/]+)(\/.*)$/) { + my $domain = $1; + my $path = $2; + + push @cookies, { + KEY => $key, VALUE => $value, DOMAIN => $domain, + PATH => $path, FLAGS =>$flags, HIXP =>$hi_expire, + LOXP => $lo_expire, HICREATE => $hi_create, + LOCREATE => $lo_create + }; + } + } + + return \@cookies; } sub get_user_name @@ -78,7 +78,7 @@ sub epoch_time_offset_from_win32_filetime # 0x019db1de 0xd53e8000 is 1970 Jan 01 00:00:00 in Win32 FILETIME # # 100 nanosecond intervals == 0.1 microsecond intervals - + my $filetime_low32_1970 = 0xd53e8000; my $filetime_high32_1970 = 0x019db1de; @@ -135,7 +135,7 @@ sub load_cookie my $secure = ($cookie->{FLAGS} & 1) != 0; my $expires = epoch_time_offset_from_win32_filetime($cookie->{HIXP}, $cookie->{LOXP}); - $self->set_cookie(undef, $cookie->{KEY}, $cookie->{VALUE}, + $self->set_cookie(undef, $cookie->{KEY}, $cookie->{VALUE}, $cookie->{PATH}, $cookie->{DOMAIN}, undef, 0, $secure, $expires-$now, 0); } @@ -144,127 +144,109 @@ sub load_cookie sub load { - my($self, $cookie_index) = @_; - my $now = time() - $HTTP::Cookies::EPOCH_OFFSET; - my $cookie_dir = ''; - my $delay_load = (defined($self->{'delayload'}) && $self->{'delayload'}); - my $user_name = get_user_name(); - my $data; - - $cookie_index ||= $self->{'file'} || return; - if ($cookie_index =~ /[\\\/][^\\\/]+$/) - { - $cookie_dir = $` . "\\"; - } - - local(*INDEX, $_); - - open(INDEX, $cookie_index) || return; - binmode(INDEX); - if (256 != read(INDEX, $data, 256)) - { - warn "$cookie_index file is not large enough"; - close(INDEX); - return; - } - - # Cookies' index.dat file starts with 32 bytes of signature - # followed by an offset to the first record, stored as a little-endian DWORD - my ($sig, $size) = unpack('a32 V', $data); - - if (($sig !~ /^Client UrlCache MMF Ver 5\.2/) || # check that sig is valid (only tested in IE6.0) - (0x4000 != $size)) - { - warn "$cookie_index ['$sig' $size] does not seem to contain cookies"; - close(INDEX); - return; - } - - if (0 == seek(INDEX, $size, 0)) # move the file ptr to start of the first record - { - close(INDEX); - return; - } - - # Cookies are usually stored in 'URL ' records in two contiguous 0x80 byte sectors (256 bytes) - # so read in two 0x80 byte sectors and adjust if not a Cookie. - while (256 == read(INDEX, $data, 256)) - { - # each record starts with a 4-byte signature - # and a count (little-endian DWORD) of 0x80 byte sectors for the record - ($sig, $size) = unpack('a4 V', $data); - - # Cookies are found in 'URL ' records - if ('URL ' ne $sig) - { - # skip over uninteresting record: I've seen 'HASH' and 'LEAK' records - if (($sig eq 'HASH') || ($sig eq 'LEAK')) - { - # '-2' takes into account the two 0x80 byte sectors we've just read in - if (($size > 0) && ($size != 2)) - { - if (0 == seek(INDEX, ($size-2)*0x80, 1)) - { - # Seek failed. Something's wrong. Gonna stop. - last; - } - } - } - next; - } - - #$REMOVE Need to check if URL records in Cookies' index.dat will - # ever use more than two 0x80 byte sectors - if ($size > 2) - { - my $more_data = ($size-2)*0x80; - - if ($more_data != read(INDEX, $data, $more_data, 256)) - { - last; - } - } - - (my $user_name2 = $user_name) =~ s/ /_/g; - if ($data =~ /Cookie\:\Q$user_name\E\@([\x21-\xFF]+).*?((?:\Q$user_name\E|\Q$user_name2\E)\@[\x21-\xFF]+\.txt)/) - { - my $cookie_file = $cookie_dir . $2; # form full pathname - - if (!$delay_load) - { - $self->load_cookie($cookie_file); - } - else - { - my $domain = $1; - - # grab only the domain name, drop everything from the first dir sep on - if ($domain =~ m{[\\/]}) - { - $domain = $`; - } - - # set the delayload cookie for this domain with - # the cookie_file as cookie for later-loading info - $self->set_cookie(undef, 'cookie', $cookie_file, - '//+delayload', $domain, undef, - 0, 0, $now+86400, 0); - } - } - } - - close(INDEX); - - 1; + my($self, $cookie_index) = @_; + my $now = time() - $HTTP::Cookies::EPOCH_OFFSET; + my $cookie_dir = ''; + my $delay_load = (defined($self->{'delayload'}) && $self->{'delayload'}); + my $user_name = get_user_name(); + my $data; + + $cookie_index ||= $self->{'file'} || return; + if ($cookie_index =~ /[\\\/][^\\\/]+$/) { + $cookie_dir = $` . "\\"; + } + + open (my $fh, '<:raw', $cookie_index) || return; + if (256 != read($fh, $data, 256)) { + warn "$cookie_index file is not large enough"; + return; + } + + # Cookies' index.dat file starts with 32 bytes of signature + # followed by an offset to the first record, stored as a little-endian DWORD + my ($sig, $size) = unpack('a32 V', $data); + + # check that sig is valid (only tested in IE6.0) + if (($sig !~ /^Client UrlCache MMF Ver 5\.2/) || (0x4000 != $size)) { + warn "$cookie_index ['$sig' $size] does not seem to contain cookies"; + return; + } + + # move the file ptr to start of the first record + if (0 == seek($fh, $size, 0)) { + return; + } + + # Cookies are usually stored in 'URL ' records in two contiguous 0x80 byte sectors (256 bytes) + # so read in two 0x80 byte sectors and adjust if not a Cookie. + while (256 == read($fh, $data, 256)) { + # each record starts with a 4-byte signature + # and a count (little-endian DWORD) of 0x80 byte sectors for the record + ($sig, $size) = unpack('a4 V', $data); + + # Cookies are found in 'URL ' records + if ('URL ' ne $sig) { + # skip over uninteresting record: I've seen 'HASH' and 'LEAK' records + if (($sig eq 'HASH') || ($sig eq 'LEAK')) { + # '-2' takes into account the two 0x80 byte sectors we've just read in + if (($size > 0) && ($size != 2)) { + if (0 == seek($fh, ($size-2)*0x80, 1)) { + # Seek failed. Something's wrong. Gonna stop. + last; + } + } + } + next; + } + + #$REMOVE Need to check if URL records in Cookies' index.dat will + # ever use more than two 0x80 byte sectors + if ($size > 2) { + my $more_data = ($size-2)*0x80; + + if ($more_data != read($fh, $data, $more_data, 256)) { + last; + } + } + + (my $user_name2 = $user_name) =~ s/ /_/g; + if ($data =~ /Cookie:\Q$user_name\E@([\x21-\xFF]+).*?((?:\Q$user_name\E|\Q$user_name2\E)@[\x21-\xFF]+\.txt)/) { + my $cookie_file = $cookie_dir . $2; # form full pathname + + if (!$delay_load) { + $self->load_cookie($cookie_file); + } + else { + my $domain = $1; + + # grab only the domain name, drop everything from the first dir sep on + if ($domain =~ m{[\\/]}) { + $domain = $`; + } + + # set the delayload cookie for this domain with + # the cookie_file as cookie for later-loading info + $self->set_cookie(undef, 'cookie', $cookie_file, '//+delayload', $domain, undef, 0, 0, $now+86400, 0); + } + } + } + + 1; } 1; -__END__ +=pod + +=encoding UTF-8 =head1 NAME -HTTP::Cookies::Microsoft - access to Microsoft cookies files +HTTP::Cookies::Microsoft - Access to Microsoft cookies files + +=head1 VERSION + +version 6.03 =head1 SYNOPSIS @@ -325,5 +307,20 @@ Copyright 2002 Johnny Lee This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. +=head1 AUTHOR + +Gisle Aas + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2002-2017 by Gisle Aas. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + =cut +__END__ + +#ABSTRACT: Access to Microsoft cookies files + diff --git a/Master/tlpkg/tlperl/site/lib/HTTP/Cookies/Netscape.pm b/Master/tlpkg/tlperl/site/lib/HTTP/Cookies/Netscape.pm index 5972029e558..180d5ff8116 100644 --- a/Master/tlpkg/tlperl/site/lib/HTTP/Cookies/Netscape.pm +++ b/Master/tlpkg/tlperl/site/lib/HTTP/Cookies/Netscape.pm @@ -1,38 +1,37 @@ package HTTP::Cookies::Netscape; - +$HTTP::Cookies::Netscape::VERSION = '6.03'; use strict; use vars qw(@ISA $VERSION); -$VERSION = "6.00"; +$VERSION = "6.01"; require HTTP::Cookies; @ISA=qw(HTTP::Cookies); sub load { - my($self, $file) = @_; + my ($self, $file) = @_; $file ||= $self->{'file'} || return; - local(*FILE, $_); + local $/ = "\n"; # make sure we got standard record separator - my @cookies; - open(FILE, $file) || return; - my $magic = ; - unless ($magic =~ /^\#(?: Netscape)? HTTP Cookie File/) { - warn "$file does not look like a netscape cookies file" if $^W; - close(FILE); - return; + open (my $fh, '<', $file) || return; + my $magic = <$fh>; + chomp $magic; + unless ($magic =~ /^#(?: Netscape)? HTTP Cookie File/) { + warn "$file does not look like a netscape cookies file"; + return; } + my $now = time() - $HTTP::Cookies::EPOCH_OFFSET; - while () { - next if /^\s*\#/; - next if /^\s*$/; - tr/\n\r//d; - my($domain,$bool1,$path,$secure, $expires,$key,$val) = split(/\t/, $_); - $secure = ($secure eq "TRUE"); - $self->set_cookie(undef,$key,$val,$path,$domain,undef, - 0,$secure,$expires-$now, 0); + while (my $line = <$fh>) { + chomp($line); + next if $line =~ /^\s*\#/; + next if $line =~ /^\s*$/; + $line =~ tr/\n\r//d; + my($domain,$bool1,$path,$secure, $expires,$key,$val) = split(/\t/, $line); + $secure = ($secure eq "TRUE"); + $self->set_cookie(undef, $key, $val, $path, $domain, undef, 0, $secure, $expires-$now, 0); } - close(FILE); 1; } @@ -40,12 +39,12 @@ sub save { my($self, $file) = @_; $file ||= $self->{'file'} || return; - local(*FILE, $_); - open(FILE, ">$file") || return; + + open(my $fh, '>', $file) || return; # Use old, now broken link to the old cookie spec just in case something # else (not us!) requires the comment block exactly this way. - print FILE <scan(sub { - my($version,$key,$val,$path,$domain,$port, - $path_spec,$secure,$expires,$discard,$rest) = @_; - return if $discard && !$self->{ignore_discard}; - $expires = $expires ? $expires - $HTTP::Cookies::EPOCH_OFFSET : 0; - return if $now > $expires; - $secure = $secure ? "TRUE" : "FALSE"; - my $bool = $domain =~ /^\./ ? "TRUE" : "FALSE"; - print FILE join("\t", $domain, $bool, $path, $secure, $expires, $key, $val), "\n"; + my ($version, $key, $val, $path, $domain, $port, $path_spec, $secure, $expires, $discard, $rest) = @_; + return if $discard && !$self->{ignore_discard}; + $expires = $expires ? $expires - $HTTP::Cookies::EPOCH_OFFSET : 0; + return if $now > $expires; + $secure = $secure ? "TRUE" : "FALSE"; + my $bool = $domain =~ /^\./ ? "TRUE" : "FALSE"; + print {$fh} join("\t", $domain, $bool, $path, $secure, $expires, $key, $val), "\n"; }); - close(FILE); 1; } 1; -__END__ + +=pod + +=encoding UTF-8 =head1 NAME -HTTP::Cookies::Netscape - access to Netscape cookies files +HTTP::Cookies::Netscape - Access to Netscape cookies files + +=head1 VERSION + +version 6.03 =head1 SYNOPSIS @@ -97,18 +101,27 @@ Please note that the Netscape/Mozilla cookie file format can't store all the information available in the Set-Cookie2 headers, so you will probably lose some information if you save in this format. -At time of writing, this module seems to work fine with Mozilla +At time of writing, this module seems to work fine with Mozilla Phoenix/Firebird. =head1 SEE ALSO L -=head1 COPYRIGHT +=head1 AUTHOR + +Gisle Aas + +=head1 COPYRIGHT AND LICENSE -Copyright 2002-2003 Gisle Aas +This software is copyright (c) 2002-2017 by Gisle Aas. -This library is free software; you can redistribute it and/or -modify it under the same terms as Perl itself. +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. =cut + +__END__ + +#ABSTRACT: Access to Netscape cookies files + diff --git a/Master/tlpkg/tlperl/site/lib/LWP.pm b/Master/tlpkg/tlperl/site/lib/LWP.pm index 6210d5911c8..b3a174af3ad 100644 --- a/Master/tlpkg/tlperl/site/lib/LWP.pm +++ b/Master/tlpkg/tlperl/site/lib/LWP.pm @@ -1,15 +1,17 @@ package LWP; -$VERSION = "6.15"; -sub Version { $VERSION; } +our $VERSION = '6.25'; -require 5.008; require LWP::UserAgent; # this should load everything you need +sub Version { $VERSION; } + 1; __END__ +=pod + =encoding utf-8 =head1 NAME @@ -49,8 +51,8 @@ used separately or together. =item * Provides an object oriented model of HTTP-style communication. Within -this framework we currently support access to http, https, gopher, ftp, news, -file, and mailto resources. +this framework we currently support access to C, C, C, +C, C, C, and C resources. =item * @@ -141,11 +143,11 @@ It is as simple as that! =head2 The Request Object -The libwww-perl request object has the class name C. +The libwww-perl request object has the class name L. The fact that the class name uses C as a prefix only implies that we use the HTTP model of communication. It does not limit the kind of services we can try to pass this I -to. For instance, we will send Cs both to ftp and +to. For instance, we will send Ls both to ftp and gopher servers, as well as to the local file system. The main attributes of the request objects are: @@ -178,7 +180,7 @@ B is an arbitrary amount of data. =head2 The Response Object -The libwww-perl response object has the class name C. +The libwww-perl response object has the class name L. The main attributes of objects of this class are: =over 3 @@ -239,11 +241,11 @@ The user agent is an interface layer between your application code and the network. Through this interface you are able to access the various servers on the network. -The class name for the user agent is C. Every +The class name for the user agent is L. Every libwww-perl application that wants to communicate should create at least one object of this class. The main method provided by this -object is request(). This method takes an C object as -argument and (eventually) returns a C object. +object is request(). This method takes an L object as +argument and (eventually) returns a L object. The user agent has many other attributes that let you configure how it will interact with the network and with your @@ -287,8 +289,8 @@ passwords needed to access certain services. Many applications want even more control over how they interact with the network and they get this by sub-classing -C. The library includes a -sub-class, C, for robot applications. +L. The library includes a +sub-class, L, for robot applications. =head2 An Example @@ -405,7 +407,7 @@ using the "Range" header. Directory listings are by default returned unprocessed (as returned from the ftp server) with the content media type reported to be -"text/ftp-dir-listing". The C module provides methods +"text/ftp-dir-listing". The L module provides methods for parsing of these directory listing. The ftp module is also able to convert directory listings to HTML and @@ -417,7 +419,7 @@ For normal file retrievals, the "Content-Type" is guessed based on the file name suffix. See L. The "If-Modified-Since" request header works for servers that implement -the MDTM command. It will probably not work for directory listings though. +the C command. It will probably not work for directory listings though. Example: @@ -497,7 +499,7 @@ Example: =head2 CPAN Requests -URLs with scheme C are redirected to the a suitable CPAN +URLs with scheme C are redirected to a suitable CPAN mirror. If you have your own local mirror of CPAN you might tell LWP to use it for C URLs by an assignment like this: @@ -569,7 +571,7 @@ The following environment variables are used by LWP: =item HOME -The C functions will look for the F<.media.types> and +The L functions will look for the F<.media.types> and F<.mime.types> files relative to you home directory. =item http_proxy @@ -586,13 +588,13 @@ L. =item PERL_LWP_ENV_PROXY -If set to a TRUE value, then the C will by default call +If set to a TRUE value, then the L will by default call C during initialization. This makes LWP honor the proxy variables described above. =item PERL_LWP_SSL_VERIFY_HOSTNAME -The default C setting for C. If +The default C setting for L. If not set the default will be 1. Set it as 0 to disable hostname verification (the default prior to libwww-perl 5.840. @@ -606,8 +608,8 @@ is located. See L for details. =item PERL_HTTP_URI_CLASS -Used to decide what URI objects to instantiate. The default is C. -You might want to set it to C for compatibility with old times. +Used to decide what URI objects to instantiate. The default is L. +You might want to set it to L for compatibility with old times. =back @@ -632,7 +634,7 @@ Markus B Krüger, Markus Laker, Martijn Koster, Martin Thurn, Matthew Eldridge, Matthew.van.Eerde, Matt Sergeant, Michael A. Chase, Michael Quaranta, Michael Thompson, Mike Schilli, Moshe Kaminsky, Nathan Torkington, Nicolai Langfeldt, Norton Allen, Olly Betts, Paul -J. Schinder, peterm, Philip GuentherDaniel Buenzli, Pon Hwa Lin, +J. Schinder, peterm, Philip Guenther, Daniel Buenzli, Pon Hwa Lin, Radoslaw Zielinski, Radu Greab, Randal L. Schwartz, Richard Chen, Robin Barker, Roy Fielding, Sander van Zoest, Sean M. Burke, shildreth, Slaven Rezic, Steve A Fink, Steve Hay, Steven Butler, diff --git a/Master/tlpkg/tlperl/site/lib/LWP/Authen/Basic.pm b/Master/tlpkg/tlperl/site/lib/LWP/Authen/Basic.pm index e7815bd247f..18fe8cd5f1c 100644 --- a/Master/tlpkg/tlperl/site/lib/LWP/Authen/Basic.pm +++ b/Master/tlpkg/tlperl/site/lib/LWP/Authen/Basic.pm @@ -1,4 +1,5 @@ package LWP::Authen::Basic; +$LWP::Authen::Basic::VERSION = '6.25'; use strict; require MIME::Base64; diff --git a/Master/tlpkg/tlperl/site/lib/LWP/Authen/Digest.pm b/Master/tlpkg/tlperl/site/lib/LWP/Authen/Digest.pm index 6fe542e29b3..2e80af49729 100644 --- a/Master/tlpkg/tlperl/site/lib/LWP/Authen/Digest.pm +++ b/Master/tlpkg/tlperl/site/lib/LWP/Authen/Digest.pm @@ -1,5 +1,5 @@ package LWP::Authen::Digest; - +$LWP::Authen::Digest::VERSION = '6.25'; use strict; use base 'LWP::Authen::Basic'; @@ -59,7 +59,7 @@ sub auth_header { for (@order) { next unless defined $resp{$_}; - # RFC2617 sais that qop-value and nc-value should be unquoted. + # RFC2617 says that qop-value and nc-value should be unquoted. if ( $_ eq 'qop' || $_ eq 'nc' ) { push(@pairs, "$_=" . $resp{$_}); } diff --git a/Master/tlpkg/tlperl/site/lib/LWP/Authen/Ntlm.pm b/Master/tlpkg/tlperl/site/lib/LWP/Authen/Ntlm.pm index 7cdbf34ef57..7fd0a827f3d 100644 --- a/Master/tlpkg/tlperl/site/lib/LWP/Authen/Ntlm.pm +++ b/Master/tlpkg/tlperl/site/lib/LWP/Authen/Ntlm.pm @@ -1,9 +1,8 @@ package LWP::Authen::Ntlm; use strict; -use vars qw/$VERSION/; -$VERSION = "6.15"; +our $VERSION = '6.25'; use Authen::NTLM "1.02"; use MIME::Base64 "2.12"; @@ -32,9 +31,9 @@ sub authenticate { my $auth_header = $proxy ? "Proxy-Authorization" : "Authorization"; - # my ($challenge) = $response->header('WWW-Authenticate'); + # my ($challenge) = $response->header('WWW-Authenticate'); my $challenge; - foreach ($response->header('WWW-Authenticate')) { + foreach ($response->header('WWW-Authenticate')) { last if /^NTLM/ && ($challenge=$_); } @@ -62,7 +61,7 @@ sub authenticate { $referral->header($auth_header => $auth_value); return $ua->request($referral, $arg, $size, $response); } - + else { # Second phase, use the response challenge (unless non-401 code # was returned, in which case, we just send back the response @@ -73,7 +72,7 @@ sub authenticate { } else { my $challenge; - foreach ($response->header('WWW-Authenticate')) { + foreach ($response->header('WWW-Authenticate')) { last if /^NTLM/ && ($challenge=$_); } $challenge =~ s/^NTLM //; @@ -90,7 +89,9 @@ sub authenticate { } 1; +__END__ +=pod =head1 NAME @@ -116,26 +117,26 @@ LWP::Authen::Ntlm - Library for enabling NTLM authentication (Microsoft) in LWP =head1 DESCRIPTION -C allows LWP to authenticate against servers that are using the -NTLM authentication scheme popularized by Microsoft. This type of authentication is +L allows LWP to authenticate against servers that are using the +NTLM authentication scheme popularized by Microsoft. This type of authentication is common on intranets of Microsoft-centric organizations. -The module takes advantage of the Authen::NTLM module by Mark Bush. Since there -is also another Authen::NTLM module available from CPAN by Yee Man Chan with an -entirely different interface, it is necessary to ensure that you have the correct +The module takes advantage of the Authen::NTLM module by Mark Bush. Since there +is also another Authen::NTLM module available from CPAN by Yee Man Chan with an +entirely different interface, it is necessary to ensure that you have the correct NTLM module. -In addition, there have been problems with incompatibilities between different -versions of Mime::Base64, which Bush's Authen::NTLM makes use of. Therefore, it is -necessary to ensure that your Mime::Base64 module supports exporting of the +In addition, there have been problems with incompatibilities between different +versions of Mime::Base64, which Bush's Authen::NTLM makes use of. Therefore, it is +necessary to ensure that your Mime::Base64 module supports exporting of the encode_base64 and decode_base64 functions. =head1 USAGE -The module is used indirectly through LWP, rather than including it directly in your -code. The LWP system will invoke the NTLM authentication when it encounters the -authentication scheme while attempting to retrieve a URL from a server. In order -for the NTLM authentication to work, you must have a few things set up in your +The module is used indirectly through LWP, rather than including it directly in your +code. The LWP system will invoke the NTLM authentication when it encounters the +authentication scheme while attempting to retrieve a URL from a server. In order +for the NTLM authentication to work, you must have a few things set up in your code prior to attempting to retrieve the URL: =over 4 @@ -156,9 +157,9 @@ The credentials must be set like this: $ua->credentials('www.company.com:80', '', "MyDomain\\MyUserCode", 'MyPassword'); -Note that you cannot use the HTTP::Request object's authorization_basic() method to set -the credentials. Note, too, that the 'www.company.com:80' portion only sets credentials -on the specified port AND it is case-sensitive (this is due to the way LWP is coded, and +Note that you cannot use the HTTP::Request object's authorization_basic() method to set +the credentials. Note, too, that the 'www.company.com:80' portion only sets credentials +on the specified port AND it is case-sensitive (this is due to the way LWP is coded, and has nothing to do with LWP::Authen::Ntlm) =back @@ -178,3 +179,5 @@ under the same terms as Perl itself. =head1 SEE ALSO L, L, L. + +=cut diff --git a/Master/tlpkg/tlperl/site/lib/LWP/ConnCache.pm b/Master/tlpkg/tlperl/site/lib/LWP/ConnCache.pm index 9c7753db8de..172e2f49a5b 100644 --- a/Master/tlpkg/tlperl/site/lib/LWP/ConnCache.pm +++ b/Master/tlpkg/tlperl/site/lib/LWP/ConnCache.pm @@ -1,10 +1,9 @@ package LWP::ConnCache; use strict; -use vars qw($VERSION $DEBUG); - -$VERSION = "6.15"; +our $VERSION = '6.25'; +our $DEBUG; sub new { my($class, %cnf) = @_; @@ -169,6 +168,8 @@ sub _looks_like_number { __END__ +=pod + =head1 NAME LWP::ConnCache - Connection cache manager @@ -188,32 +189,58 @@ change in the future. =head1 DESCRIPTION The C class is the standard connection cache manager -for LWP::UserAgent. +for L. + +=head1 METHODS The following basic methods are provided: -=over +=head2 new + + my $cache = LWP::ConnCache->new( %options ) -=item $cache = LWP::ConnCache->new( %options ) +This method constructs a new L object. The only +option currently accepted is C. If specified it +initialize the L option. It defaults to C<1>. -This method constructs a new C object. The only -option currently accepted is 'total_capacity'. If specified it -initialize the total_capacity option. It defaults to the value 1. +=head2 total_capacity -=item $cache->total_capacity( [$num_connections] ) + my $cap = $cache->total_capacity; + $cache->total_capacity(0); # drop all immediately + $cache->total_capacity(undef); # no limit + $cache->total_capacity($number); Get/sets the number of connection that will be cached. Connections will start to be dropped when this limit is reached. If set to C<0>, then all connections are immediately dropped. If set to C, then there is no limit. -=item $cache->capacity($type, [$num_connections] ) +=head2 capacity + + my $http_capacity = $cache->capacity('http'); + $cache->capacity('http', 2 ); Get/set a limit for the number of connections of the specified type -that can be cached. The $type will typically be a short string like +that can be cached. The first parameter is a short string like "http" or "ftp". -=item $cache->drop( [$checker, [$reason]] ) +=head2 drop + + $cache->drop(); # Drop ALL connections + # which is just a synonym for: + $cache->drop(sub{1}); # Drop ALL connections + # drop all connections older than 22 seconds and add a reason for it! + $cache->drop(22, "Older than 22 secs dropped"); + # which is just a synonym for: + $cache->drop(sub { + my ($conn, $type, $key, $deposit_time) = @_; + if ($deposit_time < 22) { + # true values drop the connection + return 1; + } + # false values don't drop the connection + return 0; + }, "Older than 22 secs dropped" ); Drop connections by some criteria. The $checker argument is a subroutine that is called for each connection. If the routine returns @@ -226,41 +253,49 @@ connections untouched that the given number of seconds or more are dropped. If $checker is a string then all connections of the given type are dropped. -The $reason argument is passed on to the dropped() method. +The C is passed on to the L method. + +=head2 prune -=item $cache->prune + $cache->prune(); Calling this method will drop all connections that are dead. This is -tested by calling the ping() method on the connections. If the ping() -method exists and returns a FALSE value, then the connection is -dropped. +tested by calling the L method on the connections. If +the L method exists and returns a false value, then the +connection is dropped. + +=head2 get_types -=item $cache->get_types + my @types = $cache->get_types(); -This returns all the 'type' fields used for the currently cached +This returns all the C fields used for the currently cached connections. -=item $cache->get_connections( [$type] ) +=head2 get_connections + + my @conns = $cache->get_connections(); # all connections + my @conns = $cache->get_connections('http'); # connections for http This returns all connection objects of the specified type. If no type is specified then all connections are returned. In scalar context the number of cached connections of the specified type is returned. -=back - +=head1 PROTOCOL METHODS The following methods are called by low-level protocol modules to try to save away connections and to get them back. -=over +=head2 deposit -=item $cache->deposit($type, $key, $conn) + $cache->deposit($type, $key, $conn); -This method adds a new connection to the cache. As a result other +This method adds a new connection to the cache. As a result, other already cached connections might be dropped. Multiple connections with -the same $type/$key might added. +the same type/key might be added. + +=head2 withdraw -=item $conn = $cache->withdraw($type, $key) + my $conn = $cache->withdraw($type, $key); This method tries to fetch back a connection that was previously deposited. If no cached connection with the specified $type/$key is @@ -268,35 +303,35 @@ found, then C is returned. There is not guarantee that a deposited connection can be withdrawn, as the cache manger is free to drop connections at any time. -=back +=head1 INTERNAL METHODS The following methods are called internally. Subclasses might want to override them. -=over +=head2 enforce_limits -=item $conn->enforce_limits([$type]) + $conn->enforce_limits([$type]) This method is called with after a new connection is added (deposited) in the cache or capacity limits are adjusted. The default implementation drops connections until the specified capacity limits are not exceeded. -=item $conn->dropping($conn_record, $reason) +=head2 dropping + + $conn->dropping($conn_record, $reason) This method is called when a connection is dropped. The record belonging to the dropped connection is passed as the first argument and a string describing the reason for the drop is passed as the second argument. The default implementation makes some noise if the -$LWP::ConnCache::DEBUG variable is set and nothing more. - -=back +C<$LWP::ConnCache::DEBUG> variable is set and nothing more. =head1 SUBCLASSING For specialized cache policy it makes sense to subclass -C and perhaps override the deposit(), enforce_limits() -and dropping() methods. +C and perhaps override the L, +L, and L methods. The object itself is a hash. Keys prefixed with C are reserved for the base class. @@ -311,3 +346,5 @@ Copyright 2001 Gisle Aas. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. + +=cut diff --git a/Master/tlpkg/tlperl/site/lib/LWP/Debug.pm b/Master/tlpkg/tlperl/site/lib/LWP/Debug.pm index 99011d57ab7..f7334c425df 100644 --- a/Master/tlpkg/tlperl/site/lib/LWP/Debug.pm +++ b/Master/tlpkg/tlperl/site/lib/LWP/Debug.pm @@ -1,65 +1,58 @@ -package LWP::Debug; # legacy - +package LWP::Debug; # legacy +$LWP::Debug::VERSION = '6.25'; require Exporter; -@ISA = qw(Exporter); -@EXPORT_OK = qw(level trace debug conns); +our @ISA = qw(Exporter); +our @EXPORT_OK = qw(level trace debug conns); use Carp (); my @levels = qw(trace debug conns); -%current_level = (); - +our %current_level = (); -sub import -{ - my $pack = shift; +sub import { + my $pack = shift; my $callpkg = caller(0); my @symbols = (); - my @levels = (); + my @levels = (); for (@_) { - if (/^[-+]/) { - push(@levels, $_); - } - else { - push(@symbols, $_); - } + if (/^[-+]/) { + push(@levels, $_); + } + else { + push(@symbols, $_); + } } Exporter::export($pack, $callpkg, @symbols); level(@levels); } - -sub level -{ +sub level { for (@_) { - if ($_ eq '+') { # all on - # switch on all levels - %current_level = map { $_ => 1 } @levels; - } - elsif ($_ eq '-') { # all off - %current_level = (); - } - elsif (/^([-+])(\w+)$/) { - $current_level{$2} = $1 eq '+'; - } - else { - Carp::croak("Illegal level format $_"); - } + if ($_ eq '+') { # all on + # switch on all levels + %current_level = map { $_ => 1 } @levels; + } + elsif ($_ eq '-') { # all off + %current_level = (); + } + elsif (/^([-+])(\w+)$/) { + $current_level{$2} = $1 eq '+'; + } + else { + Carp::croak("Illegal level format $_"); + } } } +sub trace { _log(@_) if $current_level{'trace'}; } +sub debug { _log(@_) if $current_level{'debug'}; } +sub conns { _log(@_) if $current_level{'conns'}; } -sub trace { _log(@_) if $current_level{'trace'}; } -sub debug { _log(@_) if $current_level{'debug'}; } -sub conns { _log(@_) if $current_level{'conns'}; } - - -sub _log -{ +sub _log { my $msg = shift; - $msg .= "\n" unless $msg =~ /\n$/; # ensure trailing "\n" + $msg .= "\n" unless $msg =~ /\n$/; # ensure trailing "\n" - my($package,$filename,$line,$sub) = caller(2); + my ($package, $filename, $line, $sub) = caller(2); print STDERR "$sub: $msg"; } @@ -67,6 +60,8 @@ sub _log __END__ +=pod + =head1 NAME LWP::Debug - deprecated @@ -85,8 +80,8 @@ section provides some hints about recommended replacements. =head2 Network traffic monitoring The best way to monitor the network traffic that LWP generates is to -use an external TCP monitoring program. The Wireshark program -(L) is highly recommended for this. +use an external TCP monitoring program. The +L program is highly recommended for this. Another approach it to use a debugging HTTP proxy server and make LWP direct all its traffic via this one. Call C<< $ua->proxy >> to @@ -108,3 +103,5 @@ request and response objects that pass through LWP: =head1 SEE ALSO L + +=cut diff --git a/Master/tlpkg/tlperl/site/lib/LWP/Debug/TraceHTTP.pm b/Master/tlpkg/tlperl/site/lib/LWP/Debug/TraceHTTP.pm new file mode 100644 index 00000000000..4dc70a096f7 --- /dev/null +++ b/Master/tlpkg/tlperl/site/lib/LWP/Debug/TraceHTTP.pm @@ -0,0 +1,26 @@ +package LWP::Debug::TraceHTTP; +$LWP::Debug::TraceHTTP::VERSION = '6.25'; +# Just call: +# +# require LWP::Debug::TraceHTTP; +# LWP::Protocol::implementor('http', 'LWP::Debug::TraceHTTP'); +# +# to use this module to trace all calls to the HTTP socket object in +# programs that use LWP. + +use strict; +use base 'LWP::Protocol::http'; + +package LWP::Debug::TraceHTTP::Socket; +$LWP::Debug::TraceHTTP::Socket::VERSION = '6.25'; +use Data::Dump 1.13; +use Data::Dump::Trace qw(autowrap mcall); + +autowrap("LWP::Protocol::http::Socket" => "sock"); + +sub new { + my $class = shift; + return mcall("LWP::Protocol::http::Socket" => "new", undef, @_); +} + +1; diff --git a/Master/tlpkg/tlperl/site/lib/LWP/DebugFile.pm b/Master/tlpkg/tlperl/site/lib/LWP/DebugFile.pm index aacdfca0fe5..681415f4ccd 100644 --- a/Master/tlpkg/tlperl/site/lib/LWP/DebugFile.pm +++ b/Master/tlpkg/tlperl/site/lib/LWP/DebugFile.pm @@ -1,5 +1,5 @@ package LWP::DebugFile; - +$LWP::DebugFile::VERSION = '6.25'; # legacy stub 1; diff --git a/Master/tlpkg/tlperl/site/lib/LWP/MemberMixin.pm b/Master/tlpkg/tlperl/site/lib/LWP/MemberMixin.pm index e5ee6f6382e..d56a2e8abad 100644 --- a/Master/tlpkg/tlperl/site/lib/LWP/MemberMixin.pm +++ b/Master/tlpkg/tlperl/site/lib/LWP/MemberMixin.pm @@ -1,10 +1,9 @@ package LWP::MemberMixin; - -sub _elem -{ +$LWP::MemberMixin::VERSION = '6.25'; +sub _elem { my $self = shift; my $elem = shift; - my $old = $self->{$elem}; + my $old = $self->{$elem}; $self->{$elem} = shift if @_; return $old; } @@ -13,6 +12,8 @@ sub _elem __END__ +=pod + =head1 NAME LWP::MemberMixin - Member access mixin class @@ -20,20 +21,21 @@ LWP::MemberMixin - Member access mixin class =head1 SYNOPSIS package Foo; - require LWP::MemberMixin; - @ISA=qw(LWP::MemberMixin); + use base qw(LWP::MemberMixin); =head1 DESCRIPTION A mixin class to get methods that provide easy access to member -variables in the %$self. +variables in the C<%$self>. Ideally there should be better Perl language support for this. +=head1 METHODS + There is only one method provided: -=over 4 +=head2 _elem -=item _elem($elem [, $val]) + _elem($elem [, $val]) Internal method to get/set the value of member variable C<$elem>. If C<$val> is present it is used as the new value @@ -41,4 +43,4 @@ for the member variable. If it is not present the current value is not touched. In both cases the previous value of the member variable is returned. -=back +=cut diff --git a/Master/tlpkg/tlperl/site/lib/LWP/Protocol.pm b/Master/tlpkg/tlperl/site/lib/LWP/Protocol.pm index 626bb005c83..3adbaf3de49 100644 --- a/Master/tlpkg/tlperl/site/lib/LWP/Protocol.pm +++ b/Master/tlpkg/tlperl/site/lib/LWP/Protocol.pm @@ -1,18 +1,17 @@ package LWP::Protocol; -require LWP::MemberMixin; -@ISA = qw(LWP::MemberMixin); -$VERSION = "6.15"; +use base 'LWP::MemberMixin'; + +our $VERSION = '6.25'; use strict; use Carp (); use HTTP::Status (); -use HTTP::Response; +use HTTP::Response (); +use Try::Tiny qw(try catch); my %ImplementedBy = (); # scheme => classname - - sub new { my($class, $scheme, $ua) = @_; @@ -62,16 +61,21 @@ sub implementor no strict 'refs'; # check we actually have one for the scheme: unless (@{"${ic}::ISA"}) { - # try to autoload it - eval "require $ic"; - if ($@) { - if ($@ =~ /Can't locate/) { #' #emacs get confused by ' - $ic = ''; - } - else { - die "$@\n"; - } - } + # try to autoload it + try { + (my $class = $ic) =~ s{::}{/}g; + $class .= '.pm' unless $class =~ /\.pm$/; + require $class; + } + catch { + my $error = $_; + if ($error =~ /Can't locate/) { + $ic = ''; + } + else { + die "$error\n"; + } + }; } $ImplementedBy{$scheme} = $ic if $ic; $ic; @@ -96,8 +100,8 @@ sub collect my $content; my($ua, $max_size) = @{$self}{qw(ua max_size)}; - eval { - local $\; # protect the print below from surprises + try { + local $\; # protect the print below from surprises if (!defined($arg) || !$response->is_success) { $response->{default_add_content} = 1; } @@ -160,17 +164,15 @@ sub collect last; } } + } + catch { + my $error = $_; + chomp($error); + $response->push_header('X-Died' => $error); + $response->push_header("Client-Aborted", "die"); }; - my $err = $@; delete $response->{handlers}{response_data}; delete $response->{handlers} unless %{$response->{handlers}}; - if ($err) { - chomp($err); - $response->push_header('X-Died' => $err); - $response->push_header("Client-Aborted", "die"); - return $response; - } - return $response; } @@ -191,6 +193,8 @@ sub collect_once __END__ +=pod + =head1 NAME LWP::Protocol - Base class for LWP protocols @@ -198,85 +202,93 @@ LWP::Protocol - Base class for LWP protocols =head1 SYNOPSIS package LWP::Protocol::foo; - require LWP::Protocol; - @ISA=qw(LWP::Protocol); + use base qw(LWP::Protocol); =head1 DESCRIPTION -This class is used a the base class for all protocol implementations +This class is used as the base class for all protocol implementations supported by the LWP library. When creating an instance of this class using C, and you get an initialized subclass appropriate for that access method. In other words, the -LWP::Protocol::create() function calls the constructor for one of its +L function calls the constructor for one of its subclasses. -All derived LWP::Protocol classes need to override the request() +All derived C classes need to override the request() method which is used to service a request. The overridden method can make use of the collect() function to collect together chunks of data as it is received. +=head1 METHODS + The following methods and functions are provided: -=over 4 +=head2 new -=item $prot = LWP::Protocol->new() + my $prot = LWP::Protocol->new(); The LWP::Protocol constructor is inherited by subclasses. As this is a virtual base class this method should B be called directly. -=item $prot = LWP::Protocol::create($scheme) +=head2 create + + my $prot = LWP::Protocol::create($scheme) Create an object of the class implementing the protocol to handle the given scheme. This is a function, not a method. It is more an object factory than a constructor. This is the function user agents should use to access protocols. -=item $class = LWP::Protocol::implementor($scheme, [$class]) +=head2 implementor + + my $class = LWP::Protocol::implementor($scheme, [$class]) -Get and/or set implementor class for a scheme. Returns '' if the +Get and/or set implementor class for a scheme. Returns C<''> if the specified scheme is not supported. -=item $prot->request(...) +=head2 request - $response = $protocol->request($request, $proxy, undef); - $response = $protocol->request($request, $proxy, '/tmp/sss'); - $response = $protocol->request($request, $proxy, \&callback, 1024); + $response = $protocol->request($request, $proxy, undef); + $response = $protocol->request($request, $proxy, '/tmp/sss'); + $response = $protocol->request($request, $proxy, \&callback, 1024); Dispatches a request over the protocol, and returns a response object. This method needs to be overridden in subclasses. Refer to L for description of the arguments. -=item $prot->collect($arg, $response, $collector) +=head2 collect -Called to collect the content of a request, and process it -appropriately into a scalar, file, or by calling a callback. If $arg -is undefined, then the content is stored within the $response. If -$arg is a simple scalar, then $arg is interpreted as a file name and -the content is written to this file. If $arg is a reference to a -routine, then content is passed to this routine. + my $res = $prot->collect(undef, $response, $collector); # stored in $response + my $res = $prot->collect($filename, $response, $collector); + my $res = $prot->collect(sub { ... }, $response, $collector); -The $collector is a routine that will be called and which is +Collect the content of a request, and process it appropriately into a scalar, +file, or by calling a callback. If the first parameter is undefined, then the +content is stored within the C<$response>. If it's a simple scalar, then it's +interpreted as a file name and the content is written to this file. If it's a +code reference, then content is passed to this routine. + +The collector is a routine that will be called and which is responsible for returning pieces (as ref to scalar) of the content to -process. The $collector signals EOF by returning a reference to an +process. The C<$collector> signals C by returning a reference to an empty string. -The return value from collect() is the $response object reference. +The return value is the L object reference. B We will only use the callback or file argument if -$response->is_success(). This avoids sending content data for +C<< $response->is_success() >>. This avoids sending content data for redirects and authentication responses to the callback which would be confusing. -=item $prot->collect_once($arg, $response, $content) +=head2 collect_once -Can be called when the whole response content is available as -$content. This will invoke collect() with a collector callback that -returns a reference to $content the first time and an empty string the -next. + $prot->collect_once($arg, $response, $content) -=back +Can be called when the whole response content is available as content. This +will invoke L with a collector callback that +returns a reference to C<$content> the first time and an empty string the +next. =head1 SEE ALSO @@ -289,3 +301,5 @@ Copyright 1995-2001 Gisle Aas. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. + +=cut diff --git a/Master/tlpkg/tlperl/site/lib/LWP/Protocol/GHTTP.pm b/Master/tlpkg/tlperl/site/lib/LWP/Protocol/GHTTP.pm deleted file mode 100644 index 2a356b5fcb1..00000000000 --- a/Master/tlpkg/tlperl/site/lib/LWP/Protocol/GHTTP.pm +++ /dev/null @@ -1,73 +0,0 @@ -package LWP::Protocol::GHTTP; - -# You can tell LWP to use this module for 'http' requests by running -# code like this before you make requests: -# -# require LWP::Protocol::GHTTP; -# LWP::Protocol::implementor('http', 'LWP::Protocol::GHTTP'); -# - -use strict; -use vars qw(@ISA); - -require LWP::Protocol; -@ISA=qw(LWP::Protocol); - -require HTTP::Response; -require HTTP::Status; - -use HTTP::GHTTP qw(METHOD_GET METHOD_HEAD METHOD_POST); - -my %METHOD = -( - GET => METHOD_GET, - HEAD => METHOD_HEAD, - POST => METHOD_POST, -); - -sub request -{ - my($self, $request, $proxy, $arg, $size, $timeout) = @_; - - my $method = $request->method; - unless (exists $METHOD{$method}) { - return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST, - "Bad method '$method'"); - } - - my $r = HTTP::GHTTP->new($request->uri); - - # XXX what headers for repeated headers here? - $request->headers->scan(sub { $r->set_header(@_)}); - - $r->set_type($METHOD{$method}); - - # XXX should also deal with subroutine content. - my $cref = $request->content_ref; - $r->set_body($$cref) if length($$cref); - - # XXX is this right - $r->set_proxy($proxy->as_string) if $proxy; - - $r->process_request; - - my $response = HTTP::Response->new($r->get_status); - - # XXX How can get the headers out of $r?? This way is too stupid. - my @headers; - eval { - # Wrapped in eval because this method is not always available - @headers = $r->get_headers; - }; - @headers = qw(Date Connection Server Content-type - Accept-Ranges Server - Content-Length Last-Modified ETag) if $@; - for (@headers) { - my $v = $r->get_header($_); - $response->header($_ => $v) if defined $v; - } - - return $self->collect_once($arg, $response, $r->get_body); -} - -1; diff --git a/Master/tlpkg/tlperl/site/lib/LWP/Protocol/cpan.pm b/Master/tlpkg/tlperl/site/lib/LWP/Protocol/cpan.pm index 66d8f213b98..3288abdbc12 100644 --- a/Master/tlpkg/tlperl/site/lib/LWP/Protocol/cpan.pm +++ b/Master/tlpkg/tlperl/site/lib/LWP/Protocol/cpan.pm @@ -1,10 +1,8 @@ package LWP::Protocol::cpan; - +$LWP::Protocol::cpan::VERSION = '6.25'; use strict; -use vars qw(@ISA); -require LWP::Protocol; -@ISA = qw(LWP::Protocol); +use base qw(LWP::Protocol); require URI; require HTTP::Status; @@ -49,14 +47,14 @@ sub request { # check proxy if (defined $proxy) { - return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST, + return HTTP::Response->new(HTTP::Status::RC_BAD_REQUEST, 'You can not proxy with cpan'); } # check method my $method = $request->method; unless ($method eq 'GET' || $method eq 'HEAD') { - return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST, + return HTTP::Response->new(HTTP::Status::RC_BAD_REQUEST, 'Library does not allow method ' . "$method for 'cpan:' URLs"); } @@ -64,7 +62,7 @@ sub request { my $path = $request->uri->path; $path =~ s,^/,,; - my $response = HTTP::Response->new(&HTTP::Status::RC_FOUND); + my $response = HTTP::Response->new(HTTP::Status::RC_FOUND); $response->header("Location" => URI->new_abs($path, $CPAN)); $response; } diff --git a/Master/tlpkg/tlperl/site/lib/LWP/Protocol/data.pm b/Master/tlpkg/tlperl/site/lib/LWP/Protocol/data.pm index c29c3b4f919..3b256528a4f 100644 --- a/Master/tlpkg/tlperl/site/lib/LWP/Protocol/data.pm +++ b/Master/tlpkg/tlperl/site/lib/LWP/Protocol/data.pm @@ -1,15 +1,13 @@ package LWP::Protocol::data; - +$LWP::Protocol::data::VERSION = '6.25'; # Implements access to data:-URLs as specified in RFC 2397 use strict; -use vars qw(@ISA); require HTTP::Response; require HTTP::Status; -require LWP::Protocol; -@ISA = qw(LWP::Protocol); +use base qw(LWP::Protocol); use HTTP::Date qw(time2str); require LWP; # needs version number @@ -21,20 +19,20 @@ sub request # check proxy if (defined $proxy) { - return HTTP::Response->new( &HTTP::Status::RC_BAD_REQUEST, + return HTTP::Response->new( HTTP::Status::RC_BAD_REQUEST, 'You can not proxy with data'); } # check method my $method = $request->method; unless ($method eq 'GET' || $method eq 'HEAD') { - return HTTP::Response->new( &HTTP::Status::RC_BAD_REQUEST, + return HTTP::Response->new( HTTP::Status::RC_BAD_REQUEST, 'Library does not allow method ' . "$method for 'data:' URLs"); } my $url = $request->uri; - my $response = HTTP::Response->new( &HTTP::Status::RC_OK, "Document follows"); + my $response = HTTP::Response->new( HTTP::Status::RC_OK, "Document follows"); my $media_type = $url->media_type; diff --git a/Master/tlpkg/tlperl/site/lib/LWP/Protocol/file.pm b/Master/tlpkg/tlperl/site/lib/LWP/Protocol/file.pm index f2887f4b2f3..e83149dbd90 100644 --- a/Master/tlpkg/tlperl/site/lib/LWP/Protocol/file.pm +++ b/Master/tlpkg/tlperl/site/lib/LWP/Protocol/file.pm @@ -1,7 +1,6 @@ package LWP::Protocol::file; - -require LWP::Protocol; -@ISA = qw(LWP::Protocol); +$LWP::Protocol::file::VERSION = '6.25'; +use base qw(LWP::Protocol); use strict; @@ -21,14 +20,14 @@ sub request # check proxy if (defined $proxy) { - return HTTP::Response->new( &HTTP::Status::RC_BAD_REQUEST, + return HTTP::Response->new( HTTP::Status::RC_BAD_REQUEST, 'You can not proxy through the filesystem'); } # check method my $method = $request->method; unless ($method eq 'GET' || $method eq 'HEAD') { - return HTTP::Response->new( &HTTP::Status::RC_BAD_REQUEST, + return HTTP::Response->new( HTTP::Status::RC_BAD_REQUEST, 'Library does not allow method ' . "$method for 'file:' URLs"); } @@ -38,7 +37,7 @@ sub request my $scheme = $url->scheme; if ($scheme ne 'file') { - return HTTP::Response->new( &HTTP::Status::RC_INTERNAL_SERVER_ERROR, + return HTTP::Response->new( HTTP::Status::RC_INTERNAL_SERVER_ERROR, "LWP::Protocol::file::request called for '$scheme'"); } @@ -47,11 +46,11 @@ sub request # test file exists and is readable unless (-e $path) { - return HTTP::Response->new( &HTTP::Status::RC_NOT_FOUND, + return HTTP::Response->new( HTTP::Status::RC_NOT_FOUND, "File `$path' does not exist"); } unless (-r _) { - return HTTP::Response->new( &HTTP::Status::RC_FORBIDDEN, + return HTTP::Response->new( HTTP::Status::RC_FORBIDDEN, 'User does not have read permission'); } @@ -67,13 +66,13 @@ sub request if (defined $ims) { my $time = HTTP::Date::str2time($ims); if (defined $time and $time >= $mtime) { - return HTTP::Response->new( &HTTP::Status::RC_NOT_MODIFIED, + return HTTP::Response->new( HTTP::Status::RC_NOT_MODIFIED, "$method $path"); } } # Ok, should be an OK response by now... - my $response = HTTP::Response->new( &HTTP::Status::RC_OK ); + my $response = HTTP::Response->new( HTTP::Status::RC_OK ); # fill in response headers $response->header('Last-Modified', HTTP::Date::time2str($mtime)); @@ -81,7 +80,7 @@ sub request if (-d _) { # If the path is a directory, process it # generate the HTML for directory opendir(D, $path) or - return HTTP::Response->new( &HTTP::Status::RC_INTERNAL_SERVER_ERROR, + return HTTP::Response->new( HTTP::Status::RC_INTERNAL_SERVER_ERROR, "Cannot read directory '$path': $!"); my(@files) = sort readdir(D); closedir(D); @@ -128,7 +127,7 @@ sub request # read the file if ($method ne "HEAD") { open(F, $path) or return new - HTTP::Response(&HTTP::Status::RC_INTERNAL_SERVER_ERROR, + HTTP::Response(HTTP::Status::RC_INTERNAL_SERVER_ERROR, "Cannot read file '$path': $!"); binmode(F); $response = $self->collect($arg, $response, sub { diff --git a/Master/tlpkg/tlperl/site/lib/LWP/Protocol/ftp.pm b/Master/tlpkg/tlperl/site/lib/LWP/Protocol/ftp.pm index f478c6ee732..2a96c1b7c55 100644 --- a/Master/tlpkg/tlperl/site/lib/LWP/Protocol/ftp.pm +++ b/Master/tlpkg/tlperl/site/lib/LWP/Protocol/ftp.pm @@ -1,115 +1,114 @@ package LWP::Protocol::ftp; - +$LWP::Protocol::ftp::VERSION = '6.25'; # Implementation of the ftp protocol (RFC 959). We let the Net::FTP # package do all the dirty work. +use base qw(LWP::Protocol); +use strict; -use Carp (); - -use HTTP::Status (); +use Carp (); +use HTTP::Status (); use HTTP::Negotiate (); -use HTTP::Response (); +use HTTP::Response (); use LWP::MediaTypes (); -use File::Listing (); +use File::Listing (); -require LWP::Protocol; -@ISA = qw(LWP::Protocol); -use strict; -eval { +{ + package LWP::Protocol::MyFTP; +$LWP::Protocol::MyFTP::VERSION = '6.25'; +use strict; + use base qw(Net::FTP); - require Net::FTP; - Net::FTP->require_version(2.00); + sub new { + my $class = shift; - use vars qw(@ISA); - @ISA=qw(Net::FTP); + my $self = $class->SUPER::new(@_) || return undef; - sub new { - my $class = shift; + my $mess = $self->message; # welcome message + $mess =~ s|\n.*||s; # only first line left + $mess =~ s|\s*ready\.?$||; - my $self = $class->SUPER::new(@_) || return undef; + # Make the version number more HTTP like + $mess =~ s|\s*\(Version\s*|/| and $mess =~ s|\)$||; + ${*$self}{myftp_server} = $mess; - my $mess = $self->message; # welcome message - $mess =~ s|\n.*||s; # only first line left - $mess =~ s|\s*ready\.?$||; - # Make the version number more HTTP like - $mess =~ s|\s*\(Version\s*|/| and $mess =~ s|\)$||; - ${*$self}{myftp_server} = $mess; - #$response->header("Server", $mess); + #$response->header("Server", $mess); - $self; + $self; } sub http_server { - my $self = shift; - ${*$self}{myftp_server}; + my $self = shift; + ${*$self}{myftp_server}; } sub home { - my $self = shift; - my $old = ${*$self}{myftp_home}; - if (@_) { - ${*$self}{myftp_home} = shift; - } - $old; + my $self = shift; + my $old = ${*$self}{myftp_home}; + if (@_) { + ${*$self}{myftp_home} = shift; + } + $old; } sub go_home { - my $self = shift; - $self->cwd(${*$self}{myftp_home}); + my $self = shift; + $self->cwd(${*$self}{myftp_home}); } sub request_count { - my $self = shift; - ++${*$self}{myftp_reqcount}; + my $self = shift; + ++${*$self}{myftp_reqcount}; } sub ping { - my $self = shift; - return $self->go_home; + my $self = shift; + return $self->go_home; } - -}; -my $init_failed = $@; - +} sub _connect { - my($self, $host, $port, $user, $account, $password, $timeout) = @_; + my ($self, $host, $port, $user, $account, $password, $timeout) = @_; my $key; my $conn_cache = $self->{ua}{conn_cache}; if ($conn_cache) { - $key = "$host:$port:$user"; - $key .= ":$account" if defined($account); - if (my $ftp = $conn_cache->withdraw("ftp", $key)) { - if ($ftp->ping) { - # save it again - $conn_cache->deposit("ftp", $key, $ftp); - return $ftp; - } - } + $key = "$host:$port:$user"; + $key .= ":$account" if defined($account); + if (my $ftp = $conn_cache->withdraw("ftp", $key)) { + if ($ftp->ping) { + + # save it again + $conn_cache->deposit("ftp", $key, $ftp); + return $ftp; + } + } } # try to make a connection - my $ftp = LWP::Protocol::MyFTP->new($host, - Port => $port, - Timeout => $timeout, - LocalAddr => $self->{ua}{local_address}, - ); + my $ftp = LWP::Protocol::MyFTP->new( + $host, + Port => $port, + Timeout => $timeout, + LocalAddr => $self->{ua}{local_address}, + ); + # XXX Should be some what to pass on 'Passive' (header??) unless ($ftp) { - $@ =~ s/^Net::FTP: //; - return HTTP::Response->new(&HTTP::Status::RC_INTERNAL_SERVER_ERROR, $@); + $@ =~ s/^Net::FTP: //; + return HTTP::Response->new(HTTP::Status::RC_INTERNAL_SERVER_ERROR, $@); } unless ($ftp->login($user, $password, $account)) { - # Unauthorized. Let's fake a RC_UNAUTHORIZED response - my $mess = scalar($ftp->message); - $mess =~ s/\n$//; - my $res = HTTP::Response->new(&HTTP::Status::RC_UNAUTHORIZED, $mess); - $res->header("Server", $ftp->http_server); - $res->header("WWW-Authenticate", qq(Basic Realm="FTP login")); - return $res; + + # Unauthorized. Let's fake a RC_UNAUTHORIZED response + my $mess = scalar($ftp->message); + $mess =~ s/\n$//; + my $res = HTTP::Response->new(HTTP::Status::RC_UNAUTHORIZED, $mess); + $res->header("Server", $ftp->http_server); + $res->header("WWW-Authenticate", qq(Basic Realm="FTP login")); + return $res; } my $home = $ftp->pwd; @@ -121,38 +120,30 @@ sub _connect { } -sub request -{ - my($self, $request, $proxy, $arg, $size, $timeout) = @_; +sub request { + my ($self, $request, $proxy, $arg, $size, $timeout) = @_; $size = 4096 unless $size; # check proxy - if (defined $proxy) - { - return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST, - 'You can not proxy through the ftp'); + if (defined $proxy) { + return HTTP::Response->new(HTTP::Status::RC_BAD_REQUEST, + 'You can not proxy through the ftp'); } my $url = $request->uri; if ($url->scheme ne 'ftp') { - my $scheme = $url->scheme; - return HTTP::Response->new(&HTTP::Status::RC_INTERNAL_SERVER_ERROR, - "LWP::Protocol::ftp::request called for '$scheme'"); + my $scheme = $url->scheme; + return HTTP::Response->new(HTTP::Status::RC_INTERNAL_SERVER_ERROR, + "LWP::Protocol::ftp::request called for '$scheme'"); } # check method my $method = $request->method; unless ($method eq 'GET' || $method eq 'HEAD' || $method eq 'PUT') { - return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST, - 'Library does not allow method ' . - "$method for 'ftp:' URLs"); - } - - if ($init_failed) { - return HTTP::Response->new(&HTTP::Status::RC_INTERNAL_SERVER_ERROR, - $init_failed); + return HTTP::Response->new(HTTP::Status::RC_BAD_REQUEST, + 'Library does not allow method ' . "$method for 'ftp:' URLs"); } my $host = $url->host; @@ -163,272 +154,290 @@ sub request # If a basic authorization header is present than we prefer these over # the username/password specified in the URL. { - my($u,$p) = $request->authorization_basic; - if (defined $u) { - $user = $u; - $password = $p; - } + my ($u, $p) = $request->authorization_basic; + if (defined $u) { + $user = $u; + $password = $p; + } } # We allow the account to be specified in the "Account" header my $account = $request->header('Account'); - my $ftp = $self->_connect($host, $port, $user, $account, $password, $timeout); - return $ftp if ref($ftp) eq "HTTP::Response"; # ugh! + my $ftp + = $self->_connect($host, $port, $user, $account, $password, $timeout); + return $ftp if ref($ftp) eq "HTTP::Response"; # ugh! # Create an initial response object - my $response = HTTP::Response->new(&HTTP::Status::RC_OK, "OK"); - $response->header(Server => $ftp->http_server); + my $response = HTTP::Response->new(HTTP::Status::RC_OK, "OK"); + $response->header(Server => $ftp->http_server); $response->header('Client-Request-Num' => $ftp->request_count); $response->request($request); # Get & fix the path - my @path = grep { length } $url->path_segments; + my @path = grep {length} $url->path_segments; my $remote_file = pop(@path); $remote_file = '' unless defined $remote_file; my $type; if (ref $remote_file) { - my @params; - ($remote_file, @params) = @$remote_file; - for (@params) { - $type = $_ if s/^type=//; - } + my @params; + ($remote_file, @params) = @$remote_file; + for (@params) { + $type = $_ if s/^type=//; + } } if ($type && $type eq 'a') { - $ftp->ascii; + $ftp->ascii; } else { - $ftp->binary; + $ftp->binary; } for (@path) { - unless ($ftp->cwd($_)) { - return HTTP::Response->new(&HTTP::Status::RC_NOT_FOUND, - "Can't chdir to $_"); - } + unless ($ftp->cwd($_)) { + return HTTP::Response->new(HTTP::Status::RC_NOT_FOUND, + "Can't chdir to $_"); + } } if ($method eq 'GET' || $method eq 'HEAD') { - if (my $mod_time = $ftp->mdtm($remote_file)) { - $response->last_modified($mod_time); - if (my $ims = $request->if_modified_since) { - if ($mod_time <= $ims) { - $response->code(&HTTP::Status::RC_NOT_MODIFIED); - $response->message("Not modified"); - return $response; - } - } - } - - # We'll use this later to abort the transfer if necessary. - # if $max_size is defined, we need to abort early. Otherwise, it's - # a normal transfer - my $max_size = undef; - - # Set resume location, if the client requested it - if ($request->header('Range') && $ftp->supported('REST')) - { - my $range_info = $request->header('Range'); - - # Change bytes=2772992-6781209 to just 2772992 - my ($start_byte,$end_byte) = $range_info =~ /.*=\s*(\d+)-(\d+)?/; - if ( defined $start_byte && !defined $end_byte ) { - - # open range -- only the start is specified - - $ftp->restart( $start_byte ); - # don't define $max_size, we don't want to abort early - } - elsif ( defined $start_byte && defined $end_byte && - $start_byte >= 0 && $end_byte >= $start_byte ) { - - $ftp->restart( $start_byte ); - $max_size = $end_byte - $start_byte; - } - else { - - return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST, - 'Incorrect syntax for Range request'); - } - } - elsif ($request->header('Range') && !$ftp->supported('REST')) - { - return HTTP::Response->new(&HTTP::Status::RC_NOT_IMPLEMENTED, - "Server does not support resume."); - } - - my $data; # the data handle - if (length($remote_file) and $data = $ftp->retr($remote_file)) { - my($type, @enc) = LWP::MediaTypes::guess_media_type($remote_file); - $response->header('Content-Type', $type) if $type; - for (@enc) { - $response->push_header('Content-Encoding', $_); - } - my $mess = $ftp->message; - if ($mess =~ /\((\d+)\s+bytes\)/) { - $response->header('Content-Length', "$1"); - } - - if ($method ne 'HEAD') { - # Read data from server - $response = $self->collect($arg, $response, sub { - my $content = ''; - my $result = $data->read($content, $size); - - # Stop early if we need to. - if (defined $max_size) - { - # We need an interface to Net::FTP::dataconn for getting - # the number of bytes already read - my $bytes_received = $data->bytes_read(); - - # We were already over the limit. (Should only happen - # once at the end.) - if ($bytes_received - length($content) > $max_size) - { - $content = ''; - } - # We just went over the limit - elsif ($bytes_received > $max_size) - { - # Trim content - $content = substr($content, 0, - $max_size - ($bytes_received - length($content)) ); - } - # We're under the limit - else - { - } + if (my $mod_time = $ftp->mdtm($remote_file)) { + $response->last_modified($mod_time); + if (my $ims = $request->if_modified_since) { + if ($mod_time <= $ims) { + $response->code(HTTP::Status::RC_NOT_MODIFIED); + $response->message("Not modified"); + return $response; + } + } + } + + # We'll use this later to abort the transfer if necessary. + # if $max_size is defined, we need to abort early. Otherwise, it's + # a normal transfer + my $max_size = undef; + + # Set resume location, if the client requested it + if ($request->header('Range') && $ftp->supported('REST')) { + my $range_info = $request->header('Range'); + + # Change bytes=2772992-6781209 to just 2772992 + my ($start_byte, $end_byte) = $range_info =~ /.*=\s*(\d+)-(\d+)?/; + if (defined $start_byte && !defined $end_byte) { + + # open range -- only the start is specified + + $ftp->restart($start_byte); + + # don't define $max_size, we don't want to abort early + } + elsif (defined $start_byte + && defined $end_byte + && $start_byte >= 0 + && $end_byte >= $start_byte) + { + + $ftp->restart($start_byte); + $max_size = $end_byte - $start_byte; + } + else { + + return HTTP::Response->new(HTTP::Status::RC_BAD_REQUEST, + 'Incorrect syntax for Range request'); + } + } + elsif ($request->header('Range') && !$ftp->supported('REST')) { + return HTTP::Response->new(HTTP::Status::RC_NOT_IMPLEMENTED, + "Server does not support resume." + ); + } + + my $data; # the data handle + if (length($remote_file) and $data = $ftp->retr($remote_file)) { + my ($type, @enc) = LWP::MediaTypes::guess_media_type($remote_file); + $response->header('Content-Type', $type) if $type; + for (@enc) { + $response->push_header('Content-Encoding', $_); + } + my $mess = $ftp->message; + if ($mess =~ /\((\d+)\s+bytes\)/) { + $response->header('Content-Length', "$1"); + } + + if ($method ne 'HEAD') { + + # Read data from server + $response = $self->collect( + $arg, + $response, + sub { + my $content = ''; + my $result = $data->read($content, $size); + + # Stop early if we need to. + if (defined $max_size) { + + # We need an interface to Net::FTP::dataconn for getting + # the number of bytes already read + my $bytes_received = $data->bytes_read(); + + # We were already over the limit. (Should only happen + # once at the end.) + if ($bytes_received - length($content) > $max_size) + { + $content = ''; + } + + # We just went over the limit + elsif ($bytes_received > $max_size) { + + # Trim content + $content = substr($content, 0, + $max_size + - ($bytes_received - length($content))); + } + + # We're under the limit + else { + } + } + + return \$content; } - - return \$content; - } ); - } - # abort is needed for HEAD, it's == close if the transfer has - # already completed. - unless ($data->abort) { - # Something did not work too well. Note that we treat - # responses to abort() with code 0 in case of HEAD as ok - # (at least wu-ftpd 2.6.1(1) does that). - if ($method ne 'HEAD' || $ftp->code != 0) { - $response->code(&HTTP::Status::RC_INTERNAL_SERVER_ERROR); - $response->message("FTP close response: " . $ftp->code . - " " . $ftp->message); - } - } - } - elsif (!length($remote_file) || ( $ftp->code >= 400 && $ftp->code < 600 )) { - # not a plain file, try to list instead - if (length($remote_file) && !$ftp->cwd($remote_file)) { - return HTTP::Response->new(&HTTP::Status::RC_NOT_FOUND, - "File '$remote_file' not found"); - } - - # It should now be safe to try to list the directory - my @lsl = $ftp->dir; - - # Try to figure out if the user want us to convert the - # directory listing to HTML. - my @variants = - ( - ['html', 0.60, 'text/html' ], - ['dir', 1.00, 'text/ftp-dir-listing' ] - ); - #$HTTP::Negotiate::DEBUG=1; - my $prefer = HTTP::Negotiate::choose(\@variants, $request); - - my $content = ''; - - if (!defined($prefer)) { - return HTTP::Response->new(&HTTP::Status::RC_NOT_ACCEPTABLE, - "Neither HTML nor directory listing wanted"); - } - elsif ($prefer eq 'html') { - $response->header('Content-Type' => 'text/html'); - $content = "File Listing\n"; - my $base = $request->uri->clone; - my $path = $base->path; - $base->path("$path/") unless $path =~ m|/$|; - $content .= qq(\n\n); - $content .= "\n
    \n"; - for (File::Listing::parse_dir(\@lsl, 'GMT')) { - my($name, $type, $size, $mtime, $mode) = @$_; - $content .= qq(
  • $name); - $content .= " $size bytes" if $type eq 'f'; - $content .= "\n"; - } - $content .= "
\n"; - } - else { - $response->header('Content-Type', 'text/ftp-dir-listing'); - $content = join("\n", @lsl, ''); - } - - $response->header('Content-Length', length($content)); - - if ($method ne 'HEAD') { - $response = $self->collect_once($arg, $response, $content); - } - } - else { - my $res = HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST, - "FTP return code " . $ftp->code); - $res->content_type("text/plain"); - $res->content($ftp->message); - return $res; - } + ); + } + + # abort is needed for HEAD, it's == close if the transfer has + # already completed. + unless ($data->abort) { + + # Something did not work too well. Note that we treat + # responses to abort() with code 0 in case of HEAD as ok + # (at least wu-ftpd 2.6.1(1) does that). + if ($method ne 'HEAD' || $ftp->code != 0) { + $response->code(HTTP::Status::RC_INTERNAL_SERVER_ERROR); + $response->message("FTP close response: " + . $ftp->code . " " + . $ftp->message); + } + } + } + elsif (!length($remote_file) || ($ftp->code >= 400 && $ftp->code < 600)) + { + # not a plain file, try to list instead + if (length($remote_file) && !$ftp->cwd($remote_file)) { + return HTTP::Response->new(HTTP::Status::RC_NOT_FOUND, + "File '$remote_file' not found" + ); + } + + # It should now be safe to try to list the directory + my @lsl = $ftp->dir; + + # Try to figure out if the user want us to convert the + # directory listing to HTML. + my @variants = ( + ['html', 0.60, 'text/html'], + ['dir', 1.00, 'text/ftp-dir-listing'] + ); + + #$HTTP::Negotiate::DEBUG=1; + my $prefer = HTTP::Negotiate::choose(\@variants, $request); + + my $content = ''; + + if (!defined($prefer)) { + return HTTP::Response->new(HTTP::Status::RC_NOT_ACCEPTABLE, + "Neither HTML nor directory listing wanted"); + } + elsif ($prefer eq 'html') { + $response->header('Content-Type' => 'text/html'); + $content = "File Listing\n"; + my $base = $request->uri->clone; + my $path = $base->path; + $base->path("$path/") unless $path =~ m|/$|; + $content .= qq(\n\n); + $content .= "\n
    \n"; + for (File::Listing::parse_dir(\@lsl, 'GMT')) { + my ($name, $type, $size, $mtime, $mode) = @$_; + $content .= qq(
  • $name); + $content .= " $size bytes" if $type eq 'f'; + $content .= "\n"; + } + $content .= "
\n"; + } + else { + $response->header('Content-Type', 'text/ftp-dir-listing'); + $content = join("\n", @lsl, ''); + } + + $response->header('Content-Length', length($content)); + + if ($method ne 'HEAD') { + $response = $self->collect_once($arg, $response, $content); + } + } + else { + my $res = HTTP::Response->new(HTTP::Status::RC_BAD_REQUEST, + "FTP return code " . $ftp->code); + $res->content_type("text/plain"); + $res->content($ftp->message); + return $res; + } } elsif ($method eq 'PUT') { - # method must be PUT - unless (length($remote_file)) { - return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST, - "Must have a file name to PUT to"); - } - my $data; - if ($data = $ftp->stor($remote_file)) { - my $content = $request->content; - my $bytes = 0; - if (defined $content) { - if (ref($content) eq 'SCALAR') { - $bytes = $data->write($$content, length($$content)); - } - elsif (ref($content) eq 'CODE') { - my($buf, $n); - while (length($buf = &$content)) { - $n = $data->write($buf, length($buf)); - last unless $n; - $bytes += $n; - } - } - elsif (!ref($content)) { - if (defined $content && length($content)) { - $bytes = $data->write($content, length($content)); - } - } - else { - die "Bad content"; - } - } - $data->close; - - $response->code(&HTTP::Status::RC_CREATED); - $response->header('Content-Type', 'text/plain'); - $response->content("$bytes bytes stored as $remote_file on $host\n") - - } - else { - my $res = HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST, - "FTP return code " . $ftp->code); - $res->content_type("text/plain"); - $res->content($ftp->message); - return $res; - } + + # method must be PUT + unless (length($remote_file)) { + return HTTP::Response->new(HTTP::Status::RC_BAD_REQUEST, + "Must have a file name to PUT to" + ); + } + my $data; + if ($data = $ftp->stor($remote_file)) { + my $content = $request->content; + my $bytes = 0; + if (defined $content) { + if (ref($content) eq 'SCALAR') { + $bytes = $data->write($$content, length($$content)); + } + elsif (ref($content) eq 'CODE') { + my ($buf, $n); + while (length($buf = &$content)) { + $n = $data->write($buf, length($buf)); + last unless $n; + $bytes += $n; + } + } + elsif (!ref($content)) { + if (defined $content && length($content)) { + $bytes = $data->write($content, length($content)); + } + } + else { + die "Bad content"; + } + } + $data->close; + + $response->code(HTTP::Status::RC_CREATED); + $response->header('Content-Type', 'text/plain'); + $response->content("$bytes bytes stored as $remote_file on $host\n") + + } + else { + my $res = HTTP::Response->new(HTTP::Status::RC_BAD_REQUEST, + "FTP return code " . $ftp->code); + $res->content_type("text/plain"); + $res->content($ftp->message); + return $res; + } } else { - return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST, - "Illegal method $method"); + return HTTP::Response->new(HTTP::Status::RC_BAD_REQUEST, + "Illegal method $method"); } $response; diff --git a/Master/tlpkg/tlperl/site/lib/LWP/Protocol/gopher.pm b/Master/tlpkg/tlperl/site/lib/LWP/Protocol/gopher.pm index db6c0bfba9d..e6fe5ce8473 100644 --- a/Master/tlpkg/tlperl/site/lib/LWP/Protocol/gopher.pm +++ b/Master/tlpkg/tlperl/site/lib/LWP/Protocol/gopher.pm @@ -1,5 +1,5 @@ package LWP::Protocol::gopher; - +$LWP::Protocol::gopher::VERSION = '6.25'; # Implementation of the gopher protocol (RFC 1436) # # This code is based on 'wwwgopher.pl,v 0.10 1994/10/17 18:12:34 shelden' @@ -8,15 +8,13 @@ package LWP::Protocol::gopher; # including contributions from Marc van Heyningen and Martijn Koster. use strict; -use vars qw(@ISA); require HTTP::Response; require HTTP::Status; require IO::Socket; require IO::Select; -require LWP::Protocol; -@ISA = qw(LWP::Protocol); +use base qw(LWP::Protocol); my %gopher2mimetype = ( @@ -47,7 +45,7 @@ sub request # check proxy if (defined $proxy) { - return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST, + return HTTP::Response->new(HTTP::Status::RC_BAD_REQUEST, 'You can not proxy through the gopher'); } @@ -57,19 +55,19 @@ sub request my $method = $request->method; unless ($method eq 'GET' || $method eq 'HEAD') { - return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST, + return HTTP::Response->new(HTTP::Status::RC_BAD_REQUEST, 'Library does not allow method ' . "$method for 'gopher:' URLs"); } my $gophertype = $url->gopher_type; unless (exists $gopher2mimetype{$gophertype}) { - return HTTP::Response->new(&HTTP::Status::RC_NOT_IMPLEMENTED, + return HTTP::Response->new(HTTP::Status::RC_NOT_IMPLEMENTED, 'Library does not support gophertype ' . $gophertype); } - my $response = HTTP::Response->new(&HTTP::Status::RC_OK, "OK"); + my $response = HTTP::Response->new(HTTP::Status::RC_OK, "OK"); $response->header('Content-type' => $gopher2mimetype{$gophertype} || 'text/plain'); $response->header('Content-Encoding' => $gopher2encoding{$gophertype}) @@ -80,7 +78,7 @@ sub request $response->header('Client-Warning' => 'Client answer only'); return $response; } - + if ($gophertype eq '7' && ! $url->search) { # the url is the prompt for a gopher search; supply boiler-plate return $self->collect_once($arg, $response, <<"EOT"); diff --git a/Master/tlpkg/tlperl/site/lib/LWP/Protocol/http.pm b/Master/tlpkg/tlperl/site/lib/LWP/Protocol/http.pm index 23c361f7055..2266b1e9ea6 100644 --- a/Master/tlpkg/tlperl/site/lib/LWP/Protocol/http.pm +++ b/Master/tlpkg/tlperl/site/lib/LWP/Protocol/http.pm @@ -1,16 +1,14 @@ package LWP::Protocol::http; - +$LWP::Protocol::http::VERSION = '6.25'; use strict; require HTTP::Response; require HTTP::Status; require Net::HTTP; -use vars qw(@ISA @EXTRA_SOCK_OPTS); - -require LWP::Protocol; -@ISA = qw(LWP::Protocol); +use base qw(LWP::Protocol); +our @EXTRA_SOCK_OPTS; my $CRLF = "\015\012"; sub _new_socket @@ -39,6 +37,7 @@ sub _new_socket my $status = "Can't connect to $host:$port"; if ($@ =~ /\bconnect: (.*)/ || $@ =~ /\b(Bad hostname)\b/ || + $@ =~ /\b(nodename nor servname provided, or not known)\b/ || $@ =~ /\b(certificate verify failed)\b/ || $@ =~ /\b(Crypt-SSLeay can't verify hostnames)\b/ ) { @@ -131,7 +130,7 @@ sub request # check method my $method = $request->method; unless ($method =~ /^[A-Za-z0-9_!\#\$%&\'*+\-.^\`|~]+$/) { # HTTP token - return HTTP::Response->new( &HTTP::Status::RC_BAD_REQUEST, + return HTTP::Response->new( HTTP::Status::RC_BAD_REQUEST, 'Library does not allow method ' . "$method for 'http:' URLs"); } @@ -168,7 +167,7 @@ sub request my $cache_key; if ( $conn_cache ) { $cache_key = "$host:$port"; - # For https we reuse the socket immediatly only if it has an established + # For https we reuse the socket immediately only if it has an established # tunnel to the target. Otherwise a CONNECT request followed by an SSL # upgrade need to be done first. The request itself might reuse an # existing non-ssl connection to the proxy @@ -181,6 +180,9 @@ sub request $socket->close; $socket = undef; } # else use $socket + else { + $socket->timeout($timeout); + } } } @@ -496,7 +498,7 @@ sub request #----------------------------------------------------------- package LWP::Protocol::http::SocketMethods; - +$LWP::Protocol::http::SocketMethods::VERSION = '6.25'; sub ping { my $self = shift; !$self->can_read(0); @@ -509,7 +511,7 @@ sub increment_response_count { #----------------------------------------------------------- package LWP::Protocol::http::Socket; -use vars qw(@ISA); -@ISA = qw(LWP::Protocol::http::SocketMethods Net::HTTP); +$LWP::Protocol::http::Socket::VERSION = '6.25'; +use base qw(LWP::Protocol::http::SocketMethods Net::HTTP); 1; diff --git a/Master/tlpkg/tlperl/site/lib/LWP/Protocol/loopback.pm b/Master/tlpkg/tlperl/site/lib/LWP/Protocol/loopback.pm index 2cd67ae3608..f1e4c9f918e 100644 --- a/Master/tlpkg/tlperl/site/lib/LWP/Protocol/loopback.pm +++ b/Master/tlpkg/tlperl/site/lib/LWP/Protocol/loopback.pm @@ -1,11 +1,9 @@ package LWP::Protocol::loopback; - +$LWP::Protocol::loopback::VERSION = '6.25'; use strict; -use vars qw(@ISA); require HTTP::Response; -require LWP::Protocol; -@ISA = qw(LWP::Protocol); +use base qw(LWP::Protocol); sub request { my($self, $request, $proxy, $arg, $size, $timeout) = @_; diff --git a/Master/tlpkg/tlperl/site/lib/LWP/Protocol/mailto.pm b/Master/tlpkg/tlperl/site/lib/LWP/Protocol/mailto.pm index 46db7162e44..9358695d57d 100644 --- a/Master/tlpkg/tlperl/site/lib/LWP/Protocol/mailto.pm +++ b/Master/tlpkg/tlperl/site/lib/LWP/Protocol/mailto.pm @@ -1,19 +1,18 @@ package LWP::Protocol::mailto; - +$LWP::Protocol::mailto::VERSION = '6.25'; # This module implements the mailto protocol. It is just a simple # frontend to the Unix sendmail program except on MacOS, where it uses # Mail::Internet. -require LWP::Protocol; require HTTP::Request; require HTTP::Response; require HTTP::Status; use Carp; use strict; -use vars qw(@ISA $SENDMAIL); -@ISA = qw(LWP::Protocol); +use base qw(LWP::Protocol); +our $SENDMAIL; unless ($SENDMAIL = $ENV{SENDMAIL}) { for my $sm (qw(/usr/sbin/sendmail @@ -39,7 +38,7 @@ sub request # check proxy if (defined $proxy) { - return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST, + return HTTP::Response->new(HTTP::Status::RC_BAD_REQUEST, 'You can not proxy with mail'); } @@ -47,7 +46,7 @@ sub request my $method = $request->method; if ($method ne 'POST') { - return HTTP::Response->new( &HTTP::Status::RC_BAD_REQUEST, + return HTTP::Response->new( HTTP::Status::RC_BAD_REQUEST, 'Library does not allow method ' . "$method for 'mailto:' URLs"); } @@ -57,7 +56,7 @@ sub request my $scheme = $url->scheme; if ($scheme ne 'mailto') { - return HTTP::Response->new( &HTTP::Status::RC_INTERNAL_SERVER_ERROR, + return HTTP::Response->new( HTTP::Status::RC_INTERNAL_SERVER_ERROR, "LWP::Protocol::mailto::request called for '$scheme'"); } if ($^O eq "MacOS") { @@ -65,28 +64,28 @@ sub request require Mail::Internet; }; if($@) { - return HTTP::Response->new( &HTTP::Status::RC_INTERNAL_SERVER_ERROR, + return HTTP::Response->new( HTTP::Status::RC_INTERNAL_SERVER_ERROR, "You don't have MailTools installed"); } unless ($ENV{SMTPHOSTS}) { - return HTTP::Response->new( &HTTP::Status::RC_INTERNAL_SERVER_ERROR, + return HTTP::Response->new( HTTP::Status::RC_INTERNAL_SERVER_ERROR, "You don't have SMTPHOSTS defined"); } } else { unless (-x $SENDMAIL) { - return HTTP::Response->new( &HTTP::Status::RC_INTERNAL_SERVER_ERROR, + return HTTP::Response->new( HTTP::Status::RC_INTERNAL_SERVER_ERROR, "You don't have $SENDMAIL"); } } if ($^O eq "MacOS") { $mail = Mail::Internet->new or - return HTTP::Response->new( &HTTP::Status::RC_INTERNAL_SERVER_ERROR, + return HTTP::Response->new( HTTP::Status::RC_INTERNAL_SERVER_ERROR, "Can't get a Mail::Internet object"); } else { open(SENDMAIL, "| $SENDMAIL -oi -t") or - return HTTP::Response->new( &HTTP::Status::RC_INTERNAL_SERVER_ERROR, + return HTTP::Response->new( HTTP::Status::RC_INTERNAL_SERVER_ERROR, "Can't run $SENDMAIL: $!"); } if ($^O eq "MacOS") { @@ -151,20 +150,20 @@ sub request if ($^O eq "MacOS") { $mail->body(\@text); unless ($mail->smtpsend) { - return HTTP::Response->new(&HTTP::Status::RC_INTERNAL_SERVER_ERROR, + return HTTP::Response->new(HTTP::Status::RC_INTERNAL_SERVER_ERROR, "Mail::Internet->smtpsend unable to send message to <$addr>"); } } else { unless (close(SENDMAIL)) { my $err = $! ? "$!" : "Exit status $?"; - return HTTP::Response->new(&HTTP::Status::RC_INTERNAL_SERVER_ERROR, + return HTTP::Response->new(HTTP::Status::RC_INTERNAL_SERVER_ERROR, "$SENDMAIL: $err"); } } - my $response = HTTP::Response->new(&HTTP::Status::RC_ACCEPTED, + my $response = HTTP::Response->new(HTTP::Status::RC_ACCEPTED, "Mail accepted"); $response->header('Content-Type', 'text/plain'); if ($^O eq "MacOS") { diff --git a/Master/tlpkg/tlperl/site/lib/LWP/Protocol/nntp.pm b/Master/tlpkg/tlperl/site/lib/LWP/Protocol/nntp.pm index 788477d488a..9727a247a51 100644 --- a/Master/tlpkg/tlperl/site/lib/LWP/Protocol/nntp.pm +++ b/Master/tlpkg/tlperl/site/lib/LWP/Protocol/nntp.pm @@ -1,9 +1,8 @@ package LWP::Protocol::nntp; - +$LWP::Protocol::nntp::VERSION = '6.25'; # Implementation of the Network News Transfer Protocol (RFC 977) -require LWP::Protocol; -@ISA = qw(LWP::Protocol); +use base qw(LWP::Protocol); require HTTP::Response; require HTTP::Status; @@ -12,56 +11,57 @@ require Net::NNTP; use strict; -sub request -{ - my($self, $request, $proxy, $arg, $size, $timeout) = @_; +sub request { + my ($self, $request, $proxy, $arg, $size, $timeout) = @_; $size = 4096 unless $size; # Check for proxy if (defined $proxy) { - return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST, - 'You can not proxy through NNTP'); + return HTTP::Response->new(HTTP::Status::RC_BAD_REQUEST, + 'You can not proxy through NNTP'); } # Check that the scheme is as expected - my $url = $request->uri; + my $url = $request->uri; my $scheme = $url->scheme; unless ($scheme eq 'news' || $scheme eq 'nntp') { - return HTTP::Response->new(&HTTP::Status::RC_INTERNAL_SERVER_ERROR, - "LWP::Protocol::nntp::request called for '$scheme'"); + return HTTP::Response->new(HTTP::Status::RC_INTERNAL_SERVER_ERROR, + "LWP::Protocol::nntp::request called for '$scheme'"); } # check for a valid method my $method = $request->method; unless ($method eq 'GET' || $method eq 'HEAD' || $method eq 'POST') { - return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST, - 'Library does not allow method ' . - "$method for '$scheme:' URLs"); + return HTTP::Response->new(HTTP::Status::RC_BAD_REQUEST, + 'Library does not allow method ' . "$method for '$scheme:' URLs"); } # extract the identifier and check against posting to an article my $groupart = $url->_group; - my $is_art = $groupart =~ /@/; + my $is_art = $groupart =~ /@/; if ($is_art && $method eq 'POST') { - return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST, - "Can't post to an article <$groupart>"); + return HTTP::Response->new(HTTP::Status::RC_BAD_REQUEST, + "Can't post to an article <$groupart>"); } - my $nntp = Net::NNTP->new($url->host, - #Port => 18574, - Timeout => $timeout, - #Debug => 1, - ); + my $nntp = Net::NNTP->new( + $url->host, + + #Port => 18574, + Timeout => $timeout, + + #Debug => 1, + ); die "Can't connect to nntp server" unless $nntp; # Check the initial welcome message from the NNTP server if ($nntp->status != 2) { - return HTTP::Response->new(&HTTP::Status::RC_SERVICE_UNAVAILABLE, - $nntp->message); + return HTTP::Response->new(HTTP::Status::RC_SERVICE_UNAVAILABLE, + $nntp->message); } - my $response = HTTP::Response->new(&HTTP::Status::RC_OK, "OK"); + my $response = HTTP::Response->new(HTTP::Status::RC_OK, "OK"); my $mess = $nntp->message; @@ -74,66 +74,69 @@ sub request # First we handle posting of articles if ($method eq 'POST') { - $nntp->quit; $nntp = undef; - $response->code(&HTTP::Status::RC_NOT_IMPLEMENTED); - $response->message("POST not implemented yet"); - return $response; + $nntp->quit; + $nntp = undef; + $response->code(HTTP::Status::RC_NOT_IMPLEMENTED); + $response->message("POST not implemented yet"); + return $response; } # The method must be "GET" or "HEAD" by now if (!$is_art) { - if (!$nntp->group($groupart)) { - $response->code(&HTTP::Status::RC_NOT_FOUND); - $response->message($nntp->message); - } - $nntp->quit; $nntp = undef; - # HEAD: just check if the group exists - if ($method eq 'GET' && $response->is_success) { - $response->code(&HTTP::Status::RC_NOT_IMPLEMENTED); - $response->message("GET newsgroup not implemented yet"); - } - return $response; + if (!$nntp->group($groupart)) { + $response->code(HTTP::Status::RC_NOT_FOUND); + $response->message($nntp->message); + } + $nntp->quit; + $nntp = undef; + + # HEAD: just check if the group exists + if ($method eq 'GET' && $response->is_success) { + $response->code(HTTP::Status::RC_NOT_IMPLEMENTED); + $response->message("GET newsgroup not implemented yet"); + } + return $response; } # Send command to server to retrieve an article (or just the headers) my $get = $method eq 'HEAD' ? "head" : "article"; my $art = $nntp->$get("<$groupart>"); unless ($art) { - $nntp->quit; $nntp = undef; - $response->code(&HTTP::Status::RC_NOT_FOUND); - $response->message($nntp->message); - return $response; + $nntp->quit; + $response->code(HTTP::Status::RC_NOT_FOUND); + $response->message($nntp->message); + $nntp = undef; + return $response; } # Parse headers - my($key, $val); + my ($key, $val); local $_; while ($_ = shift @$art) { - if (/^\s+$/) { - last; # end of headers - } - elsif (/^(\S+):\s*(.*)/) { - $response->push_header($key, $val) if $key; - ($key, $val) = ($1, $2); - } - elsif (/^\s+(.*)/) { - next unless $key; - $val .= $1; - } - else { - unshift(@$art, $_); - last; - } + if (/^\s+$/) { + last; # end of headers + } + elsif (/^(\S+):\s*(.*)/) { + $response->push_header($key, $val) if $key; + ($key, $val) = ($1, $2); + } + elsif (/^\s+(.*)/) { + next unless $key; + $val .= $1; + } + else { + unshift(@$art, $_); + last; + } } $response->push_header($key, $val) if $key; # Ensure that there is a Content-Type header $response->header("Content-Type", "text/plain") - unless $response->header("Content-Type"); + unless $response->header("Content-Type"); # Collect the body - $response = $self->collect_once($arg, $response, join("", @$art)) - if @$art; + $response = $self->collect_once($arg, $response, join("", @$art)) if @$art; # Say goodbye to the server $nntp->quit; diff --git a/Master/tlpkg/tlperl/site/lib/LWP/Protocol/nogo.pm b/Master/tlpkg/tlperl/site/lib/LWP/Protocol/nogo.pm index 68150a722d5..a9b0e411ee7 100644 --- a/Master/tlpkg/tlperl/site/lib/LWP/Protocol/nogo.pm +++ b/Master/tlpkg/tlperl/site/lib/LWP/Protocol/nogo.pm @@ -4,20 +4,19 @@ package LWP::Protocol::nogo; # LWP::Protocol::implementor(that_scheme, 'LWP::Protocol::nogo'); # For then on, attempts to access URLs with that scheme will generate # a 500 error. - +$LWP::Protocol::nogo::VERSION = '6.25'; use strict; -use vars qw(@ISA); + require HTTP::Response; require HTTP::Status; -require LWP::Protocol; -@ISA = qw(LWP::Protocol); +use base qw(LWP::Protocol); sub request { my($self, $request) = @_; my $scheme = $request->uri->scheme; - + return HTTP::Response->new( - &HTTP::Status::RC_INTERNAL_SERVER_ERROR, + HTTP::Status::RC_INTERNAL_SERVER_ERROR, "Access to \'$scheme\' URIs has been disabled" ); } diff --git a/Master/tlpkg/tlperl/site/lib/LWP/RobotUA.pm b/Master/tlpkg/tlperl/site/lib/LWP/RobotUA.pm index 9e0bf5f0dbb..0e96856329a 100644 --- a/Master/tlpkg/tlperl/site/lib/LWP/RobotUA.pm +++ b/Master/tlpkg/tlperl/site/lib/LWP/RobotUA.pm @@ -1,8 +1,8 @@ package LWP::RobotUA; -require LWP::UserAgent; -@ISA = qw(LWP::UserAgent); -$VERSION = "6.15"; +use base qw(LWP::UserAgent); + +our $VERSION = '6.25'; require WWW::RobotRules; require HTTP::Request; @@ -72,7 +72,7 @@ sub agent my $old = $self->SUPER::agent(@_); if (@_) { # Changing our name means to start fresh - $self->{'rules'}->agent($self->{'agent'}); + $self->{'rules'}->agent($self->{'agent'}); } $old; } @@ -123,7 +123,7 @@ sub simple_request $robot_url->query(undef); # make access to robot.txt legal since this will be a recursive call - $self->{'rules'}->parse($robot_url, ""); + $self->{'rules'}->parse($robot_url, ""); my $robot_req = HTTP::Request->new('GET', $robot_url); my $parse_head = $self->parse_head(0); @@ -144,7 +144,7 @@ sub simple_request # Check rules unless ($allowed) { my $res = HTTP::Response->new( - &HTTP::Status::RC_FORBIDDEN, 'Forbidden by robots.txt'); + HTTP::Status::RC_FORBIDDEN, 'Forbidden by robots.txt'); $res->request( $request ); # bind it to that request return $res; } @@ -158,7 +158,7 @@ sub simple_request } else { my $res = HTTP::Response->new( - &HTTP::Status::RC_SERVICE_UNAVAILABLE, 'Please, slow down'); + HTTP::Status::RC_SERVICE_UNAVAILABLE, 'Please, slow down'); $res->header('Retry-After', time2str(time + $wait)); $res->request( $request ); # bind it to that request return $res; @@ -190,6 +190,8 @@ sub as_string __END__ +=pod + =head1 NAME LWP::RobotUA - a class for well-behaved Web robots @@ -213,7 +215,7 @@ should consult the F file to ensure that they are welcomed and they should not make requests too frequently. But before you consider writing a robot, take a look at -. +L. When you use an I object as your user agent, then you do not really have to think about these things yourself; C files @@ -226,16 +228,14 @@ special agent will make sure you are nice. =head1 METHODS -The LWP::RobotUA is a sub-class of LWP::UserAgent and implements the +The LWP::RobotUA is a sub-class of L and implements the same methods. In addition the following methods are provided: -=over 4 - -=item $ua = LWP::RobotUA->new( %options ) +=head2 new -=item $ua = LWP::RobotUA->new( $agent, $from ) - -=item $ua = LWP::RobotUA->new( $agent, $from, $rules ) + my $ua = LWP::RobotUA->new( %options ) + my $ua = LWP::RobotUA->new( $agent, $from ) + my $ua = LWP::RobotUA->new( $agent, $from, $rules ) The LWP::UserAgent options C and C are mandatory. The options C, C and C initialize attributes @@ -246,51 +246,58 @@ F. It is also possible to just pass the value of C, C and optionally C as plain positional arguments. -=item $ua->delay +=head2 delay -=item $ua->delay( $minutes ) + my $delay = $ua->delay; + $ua->delay( $minutes ); Get/set the minimum delay between requests to the same server, in -I. The default is 1 minute. Note that this number doesn't -have to be an integer; for example, this sets the delay to 10 seconds: +I. The default is C<1> minute. Note that this number doesn't +have to be an integer; for example, this sets the delay to C<10> seconds: $ua->delay(10/60); -=item $ua->use_sleep +=head2 use_sleep -=item $ua->use_sleep( $boolean ) + my $bool = $ua->use_sleep; + $ua->use_sleep( $boolean ); -Get/set a value indicating whether the UA should sleep() if requests -arrive too fast, defined as $ua->delay minutes not passed since -last request to the given server. The default is TRUE. If this value is -FALSE then an internal SERVICE_UNAVAILABLE response will be generated. -It will have a Retry-After header that indicates when it is OK to +Get/set a value indicating whether the UA should L if +requests arrive too fast, defined as C<< $ua->delay >> minutes not passed since +last request to the given server. The default is true. If this value is +false then an internal C response will be generated. +It will have a C header that indicates when it is OK to send another request to this server. -=item $ua->rules +=head2 rules -=item $ua->rules( $rules ) + my $rules = $ua->rules; + $ua->rules( $rules ); Set/get which I object to use. -=item $ua->no_visits( $netloc ) +=head2 no_visits + + my $num = $ua->no_visits( $netloc ) Returns the number of documents fetched from this server host. Yeah I -know, this method should probably have been named num_visits() or +know, this method should probably have been named C or something like that. :-( -=item $ua->host_wait( $netloc ) +=head2 host_wait + + my $num = $ua->host_wait( $netloc ) Returns the number of I (from now) you must wait before you can make a new request to this host. -=item $ua->as_string +=head2 as_string + + my $string = $ua->as_string; Returns a string that describes the state of the UA. Mainly useful for debugging. -=back - =head1 SEE ALSO L, L @@ -301,3 +308,5 @@ Copyright 1996-2004 Gisle Aas. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. + +=cut diff --git a/Master/tlpkg/tlperl/site/lib/LWP/Simple.pm b/Master/tlpkg/tlperl/site/lib/LWP/Simple.pm index e522a1d19c2..321f9641c48 100644 --- a/Master/tlpkg/tlperl/site/lib/LWP/Simple.pm +++ b/Master/tlpkg/tlperl/site/lib/LWP/Simple.pm @@ -1,21 +1,20 @@ package LWP::Simple; use strict; -use vars qw($ua %loop_check $FULL_LWP @EXPORT @EXPORT_OK $VERSION); + +our $VERSION = '6.25'; require Exporter; -@EXPORT = qw(get head getprint getstore mirror); -@EXPORT_OK = qw($ua); +our @EXPORT = qw(get head getprint getstore mirror); +our @EXPORT_OK = qw($ua); -# I really hate this. I was a bad idea to do it in the first place. +# I really hate this. It was a bad idea to do it in the first place. # Wonder how to get rid of it??? (It even makes LWP::Simple 7% slower # for trivial tests) use HTTP::Status; push(@EXPORT, @HTTP::Status::EXPORT); -$VERSION = "6.15"; - sub import { my $pkg = shift; @@ -24,13 +23,12 @@ sub import } use LWP::UserAgent (); -use HTTP::Status (); use HTTP::Date (); -$ua = LWP::UserAgent->new; # we create a global UserAgent object + +our $ua = LWP::UserAgent->new; # we create a global UserAgent object $ua->agent("LWP::Simple/$VERSION "); $ua->env_proxy; - sub get ($) { my $response = $ua->get(shift); @@ -97,6 +95,8 @@ sub mirror ($$) __END__ +=pod + =head1 NAME LWP::Simple - simple procedural interface to LWP @@ -123,24 +123,36 @@ This module is meant for people who want a simplified view of the libwww-perl library. It should also be suitable for one-liners. If you need more control or access to the header fields in the requests sent and responses received, then you should use the full object-oriented -interface provided by the C module. +interface provided by the L module. + +The module will also export the L object as C<$ua> if you +ask for it explicitly. + +The user agent created by this module will identify itself as +C +and will initialize its proxy defaults from the environment (by +calling C<< $ua->env_proxy >>). + +=head1 FUNCTIONS The following functions are provided (and exported) by this module: -=over 3 +=head2 get -=item get($url) + my $res = get($url); The get() function will fetch the document identified by the given URL -and return it. It returns C if it fails. The $url argument can -be either a string or a reference to a URI object. +and return it. It returns C if it fails. The C<$url> argument can +be either a string or a reference to a L object. You will not be able to examine the response code or response headers -(like 'Content-Type') when you are accessing the web using this +(like C) when you are accessing the web using this function. If you need that information you should use the full OO interface (see L). -=item head($url) +=head2 head + + my $res = head($url); Get document headers. Returns the following 5 values if successful: ($content_type, $document_length, $modified_time, $expires, $server) @@ -148,7 +160,9 @@ Get document headers. Returns the following 5 values if successful: Returns an empty list if it fails. In scalar context returns TRUE if successful. -=item getprint($url) +=head2 getprint + + my $code = getprint($url); Get and print a document identified by a URL. The document is printed to the selected default filehandle for output (normally STDOUT) as @@ -156,22 +170,26 @@ data is received from the network. If the request fails, then the status code and message are printed on STDERR. The return value is the HTTP response code. -=item getstore($url, $file) +=head2 getstore + + my $code = getstore($url, $file) Gets a document identified by a URL and stores it in the file. The return value is the HTTP response code. -=item mirror($url, $file) +=head2 mirror + + my $code = mirror($url, $file); Get and store a document identified by a URL, using I, and checking the I. Returns the HTTP response code. -=back +=head1 STATUS CONSTANTS -This module also exports the HTTP::Status constants and procedures. -You can use them when you check the response code from getprint(), -getstore() or mirror(). The constants are: +This module also exports the L constants and procedures. +You can use them when you check the response code from L, +L or L. The constants are: RC_CONTINUE RC_SWITCHING_PROTOCOLS @@ -211,34 +229,28 @@ getstore() or mirror(). The constants are: RC_GATEWAY_TIMEOUT RC_HTTP_VERSION_NOT_SUPPORTED -The HTTP::Status classification functions are: +=head1 CLASSIFICATION FUNCTIONS -=over 3 +The L classification functions are: -=item is_success($rc) +=head2 is_success -True if response code indicated a successful request. - -=item is_error($rc) + my $bool = is_success($rc); -True if response code indicated that an error occurred. +True if response code indicated a successful request. -=back +=head2 is_error -The module will also export the LWP::UserAgent object as C<$ua> if you -ask for it explicitly. + my $bool = is_error($rc) -The user agent created by this module will identify itself as -"LWP::Simple/#.##" -and will initialize its proxy defaults from the environment (by -calling $ua->env_proxy). +True if response code indicated that an error occurred. =head1 CAVEAT -Note that if you are using both LWP::Simple and the very popular CGI.pm +Note that if you are using both LWP::Simple and the very popular L module, you may be importing a C function from each module, -producing a warning like "Prototype mismatch: sub main::head ($) vs -none". Get around this problem by just not importing LWP::Simple's +producing a warning like C. +Get around this problem by just not importing LWP::Simple's C function, like so: use LWP::Simple qw(!head); @@ -251,3 +263,5 @@ it as C. L, L, L, L, L, L + +=cut diff --git a/Master/tlpkg/tlperl/site/lib/LWP/UserAgent.pm b/Master/tlpkg/tlperl/site/lib/LWP/UserAgent.pm index b9a32839dd0..07c391605e3 100644 --- a/Master/tlpkg/tlperl/site/lib/LWP/UserAgent.pm +++ b/Master/tlpkg/tlperl/site/lib/LWP/UserAgent.pm @@ -1,12 +1,10 @@ package LWP::UserAgent; use strict; -use vars qw(@ISA $VERSION); -require LWP::MemberMixin; -@ISA = qw(LWP::MemberMixin); -$VERSION = "6.15"; +use base qw(LWP::MemberMixin); +use Carp (); use HTTP::Request (); use HTTP::Response (); use HTTP::Date (); @@ -14,14 +12,16 @@ use HTTP::Date (); use LWP (); use LWP::Protocol (); -use Carp (); +use Scalar::Util qw(blessed); +use Try::Tiny qw(try catch); +our $VERSION = '6.25'; sub new { # Check for common user mistake - Carp::croak("Options to LWP::UserAgent should be key/value pairs, not hash reference") - if ref($_[1]) eq 'HASH'; + Carp::croak("Options to LWP::UserAgent should be key/value pairs, not hash reference") + if ref($_[1]) eq 'HASH'; my($class, %cnf) = @_; @@ -65,17 +65,19 @@ sub new my $max_redirect = delete $cnf{max_redirect}; $max_redirect = 7 unless defined $max_redirect; my $env_proxy = exists $cnf{env_proxy} ? delete $cnf{env_proxy} : $ENV{PERL_LWP_ENV_PROXY}; + my $no_proxy = exists $cnf{no_proxy} ? delete $cnf{no_proxy} : []; + Carp::croak(qq{no_proxy must be an arrayref, not $no_proxy!}) if ref $no_proxy ne 'ARRAY'; my $cookie_jar = delete $cnf{cookie_jar}; my $conn_cache = delete $cnf{conn_cache}; my $keep_alive = delete $cnf{keep_alive}; - + Carp::croak("Can't mix conn_cache and keep_alive") if $conn_cache && $keep_alive; my $protocols_allowed = delete $cnf{protocols_allowed}; my $protocols_forbidden = delete $cnf{protocols_forbidden}; - + my $requests_redirectable = delete $cnf{requests_redirectable}; $requests_redirectable = ['GET', 'HEAD'] unless defined $requests_redirectable; @@ -88,34 +90,40 @@ sub new Carp::croak("requests_redirectable has to be an arrayref or 0, not \"$requests_redirectable\"!") if $requests_redirectable and ref($requests_redirectable) ne 'ARRAY'; - if (%cnf && $^W) { Carp::carp("Unrecognized LWP::UserAgent options: @{[sort keys %cnf]}"); } my $self = bless { - def_headers => $def_headers, - timeout => $timeout, - local_address => $local_address, - ssl_opts => $ssl_opts, - use_eval => $use_eval, - show_progress=> $show_progress, - max_size => $max_size, - max_redirect => $max_redirect, - proxy => {}, - no_proxy => [], - protocols_allowed => $protocols_allowed, - protocols_forbidden => $protocols_forbidden, - requests_redirectable => $requests_redirectable, - }, $class; + def_headers => $def_headers, + timeout => $timeout, + local_address => $local_address, + ssl_opts => $ssl_opts, + use_eval => $use_eval, + show_progress => $show_progress, + max_size => $max_size, + max_redirect => $max_redirect, + # We set proxy later as we do validation on the values + proxy => {}, + no_proxy => [ @{ $no_proxy } ], + protocols_allowed => $protocols_allowed, + protocols_forbidden => $protocols_forbidden, + requests_redirectable => $requests_redirectable, + }, $class; $self->agent(defined($agent) ? $agent : $class->_agent) - if defined($agent) || !$def_headers || !$def_headers->header("User-Agent"); + if defined($agent) || !$def_headers || !$def_headers->header("User-Agent"); $self->from($from) if $from; $self->cookie_jar($cookie_jar) if $cookie_jar; $self->parse_head($parse_head); $self->env_proxy if $env_proxy; + if (exists $cnf{proxy}) { + Carp::croak(qq{proxy must be an arrayref, not $cnf{proxy}!}) + if ref $cnf{proxy} ne 'ARRAY'; + $self->proxy($cnf{proxy}); + } + $self->protocols_allowed( $protocols_allowed ) if $protocols_allowed; $self->protocols_forbidden($protocols_forbidden) if $protocols_forbidden; @@ -171,10 +179,13 @@ sub send_request } unless ($protocol) { - $protocol = eval { LWP::Protocol::create($scheme, $self) }; - if ($@) { - $@ =~ s/ at .* line \d+.*//s; # remove file/line number - $response = _new_response($request, &HTTP::Status::RC_NOT_IMPLEMENTED, $@); + try { + $protocol = LWP::Protocol::create($scheme, $self); + } + catch { + my $error = $_; + $error =~ s/ at .* line \d+.*//s; # remove file/line number + $response = _new_response($request, HTTP::Status::RC_NOT_IMPLEMENTED, $error); if ($scheme eq "https") { $response->message($response->message . " (LWP::Protocol::https not installed)"); $response->content_type("text/plain"); @@ -183,28 +194,28 @@ LWP will support https URLs if the LWP::Protocol::https module is installed. EOT } - } + }; } if (!$response && $self->{use_eval}) { # we eval, and turn dies into responses below - eval { - $response = $protocol->request($request, $proxy, $arg, $size, $self->{timeout}) || - die "No response returned by $protocol"; - }; - if ($@) { - if (UNIVERSAL::isa($@, "HTTP::Response")) { - $response = $@; + try { + $response = $protocol->request($request, $proxy, $arg, $size, $self->{timeout}) || die "No response returned by $protocol"; + } + catch { + my $error = $_; + if (blessed($error) && $error->isa("HTTP::Response")) { + $response = $error; $response->request($request); } else { - my $full = $@; - (my $status = $@) =~ s/\n.*//s; + my $full = $error; + (my $status = $error) =~ s/\n.*//s; $status =~ s/ at .* line \d+.*//s; # remove file/line number - my $code = ($status =~ s/^(\d\d\d)\s+//) ? $1 : &HTTP::Status::RC_INTERNAL_SERVER_ERROR; + my $code = ($status =~ s/^(\d\d\d)\s+//) ? $1 : HTTP::Status::RC_INTERNAL_SERVER_ERROR; $response = _new_response($request, $code, $status, $full); } - } + }; } elsif (!$response) { $response = $protocol->request($request, $proxy, @@ -264,27 +275,32 @@ sub simple_request Carp::croak("No request object passed in"); } - eval { - $request = $self->prepare_request($request); + my $error; + try { + $request = $self->prepare_request($request); + } + catch { + $error = $_; + $error =~ s/ at .* line \d+.*//s; # remove file/line number }; - if ($@) { - $@ =~ s/ at .* line \d+.*//s; # remove file/line number - return _new_response($request, &HTTP::Status::RC_BAD_REQUEST, $@); + + if ($error) { + return _new_response($request, HTTP::Status::RC_BAD_REQUEST, $error); } return $self->send_request($request, $arg, $size); } -sub request -{ - my($self, $request, $arg, $size, $previous) = @_; +sub request { + my ($self, $request, $arg, $size, $previous) = @_; my $response = $self->simple_request($request, $arg, $size); $response->previous($previous) if $previous; if ($response->redirects >= $self->{max_redirect}) { $response->header("Client-Warning" => - "Redirect loop detected (max_redirect = $self->{max_redirect})"); + "Redirect loop detected (max_redirect = $self->{max_redirect})" + ); return $response; } @@ -294,113 +310,121 @@ sub request my $code = $response->code; - if ($code == &HTTP::Status::RC_MOVED_PERMANENTLY or - $code == &HTTP::Status::RC_FOUND or - $code == &HTTP::Status::RC_SEE_OTHER or - $code == &HTTP::Status::RC_TEMPORARY_REDIRECT) + if ( $code == HTTP::Status::RC_MOVED_PERMANENTLY + or $code == HTTP::Status::RC_FOUND + or $code == HTTP::Status::RC_SEE_OTHER + or $code == HTTP::Status::RC_TEMPORARY_REDIRECT) { - my $referral = $request->clone; - - # These headers should never be forwarded - $referral->remove_header('Host', 'Cookie'); - - if ($referral->header('Referer') && - $request->uri->scheme eq 'https' && - $referral->uri->scheme eq 'http') - { - # RFC 2616, section 15.1.3. - # https -> http redirect, suppressing Referer - $referral->remove_header('Referer'); - } + my $referral = $request->clone; - if ($code == &HTTP::Status::RC_SEE_OTHER || - $code == &HTTP::Status::RC_FOUND) + # These headers should never be forwarded + $referral->remove_header('Host', 'Cookie'); + + if ( $referral->header('Referer') + && $request->uri->scheme eq 'https' + && $referral->uri->scheme eq 'http') { - my $method = uc($referral->method); - unless ($method eq "GET" || $method eq "HEAD") { - $referral->method("GET"); - $referral->content(""); - $referral->remove_content_headers; - } - } + # RFC 2616, section 15.1.3. + # https -> http redirect, suppressing Referer + $referral->remove_header('Referer'); + } - # And then we update the URL based on the Location:-header. - my $referral_uri = $response->header('Location'); - { - # Some servers erroneously return a relative URL for redirects, - # so make it absolute if it not already is. - local $URI::ABS_ALLOW_RELATIVE_SCHEME = 1; - my $base = $response->base; - $referral_uri = "" unless defined $referral_uri; - $referral_uri = $HTTP::URI_CLASS->new($referral_uri, $base) - ->abs($base); - } - $referral->uri($referral_uri); + if ( $code == HTTP::Status::RC_SEE_OTHER + || $code == HTTP::Status::RC_FOUND) + { + my $method = uc($referral->method); + unless ($method eq "GET" || $method eq "HEAD") { + $referral->method("GET"); + $referral->content(""); + $referral->remove_content_headers; + } + } - return $response unless $self->redirect_ok($referral, $response); - return $self->request($referral, $arg, $size, $response); + # And then we update the URL based on the Location:-header. + my $referral_uri = $response->header('Location'); + { + # Some servers erroneously return a relative URL for redirects, + # so make it absolute if it not already is. + local $URI::ABS_ALLOW_RELATIVE_SCHEME = 1; + my $base = $response->base; + $referral_uri = "" unless defined $referral_uri; + $referral_uri + = $HTTP::URI_CLASS->new($referral_uri, $base)->abs($base); + } + $referral->uri($referral_uri); + + return $response unless $self->redirect_ok($referral, $response); + return $self->request($referral, $arg, $size, $response); } - elsif ($code == &HTTP::Status::RC_UNAUTHORIZED || - $code == &HTTP::Status::RC_PROXY_AUTHENTICATION_REQUIRED - ) + elsif ($code == HTTP::Status::RC_UNAUTHORIZED + || $code == HTTP::Status::RC_PROXY_AUTHENTICATION_REQUIRED) { - my $proxy = ($code == &HTTP::Status::RC_PROXY_AUTHENTICATION_REQUIRED); - my $ch_header = $proxy || $request->method eq 'CONNECT' - ? "Proxy-Authenticate" : "WWW-Authenticate"; - my @challenge = $response->header($ch_header); - unless (@challenge) { - $response->header("Client-Warning" => - "Missing Authenticate header"); - return $response; - } + my $proxy = ($code == HTTP::Status::RC_PROXY_AUTHENTICATION_REQUIRED); + my $ch_header + = $proxy || $request->method eq 'CONNECT' + ? "Proxy-Authenticate" + : "WWW-Authenticate"; + my @challenges = $response->header($ch_header); + unless (@challenges) { + $response->header( + "Client-Warning" => "Missing Authenticate header"); + return $response; + } - require HTTP::Headers::Util; - CHALLENGE: for my $challenge (@challenge) { - $challenge =~ tr/,/;/; # "," is used to separate auth-params!! - ($challenge) = HTTP::Headers::Util::split_header_words($challenge); - my $scheme = shift(@$challenge); - shift(@$challenge); # no value - $challenge = { @$challenge }; # make rest into a hash - - unless ($scheme =~ /^([a-z]+(?:-[a-z]+)*)$/) { - $response->header("Client-Warning" => - "Bad authentication scheme '$scheme'"); - return $response; - } - $scheme = $1; # untainted now - my $class = "LWP::Authen::\u$scheme"; - $class =~ s/-/_/g; - - no strict 'refs'; - unless (%{"$class\::"}) { - # try to load it - eval "require $class"; - if ($@) { - if ($@ =~ /^Can\'t locate/) { - $response->header("Client-Warning" => - "Unsupported authentication scheme '$scheme'"); - } - else { - $response->header("Client-Warning" => $@); - } - next CHALLENGE; - } - } - unless ($class->can("authenticate")) { - $response->header("Client-Warning" => - "Unsupported authentication scheme '$scheme'"); - next CHALLENGE; - } - return $class->authenticate($self, $proxy, $challenge, $response, - $request, $arg, $size); - } - return $response; + require HTTP::Headers::Util; + CHALLENGE: for my $challenge (@challenges) { + $challenge =~ tr/,/;/; # "," is used to separate auth-params!! + ($challenge) = HTTP::Headers::Util::split_header_words($challenge); + my $scheme = shift(@$challenge); + shift(@$challenge); # no value + $challenge = {@$challenge}; # make rest into a hash + + unless ($scheme =~ /^([a-z]+(?:-[a-z]+)*)$/) { + $response->header( + "Client-Warning" => "Bad authentication scheme '$scheme'"); + return $response; + } + $scheme = $1; # untainted now + my $class = "LWP::Authen::\u$scheme"; + $class =~ s/-/_/g; + + no strict 'refs'; + unless (%{"$class\::"}) { + # try to load it + my $error; + try { + (my $req = $class) =~ s{::}{/}g; + $req .= '.pm' unless $req =~ /\.pm$/; + require $req; + } + catch { + $error = $_; + }; + if ($error) { + if ($error =~ /^Can\'t locate/) { + $response->header("Client-Warning" => + "Unsupported authentication scheme '$scheme'"); + } + else { + $response->header("Client-Warning" => $error); + } + next CHALLENGE; + } + } + unless ($class->can("authenticate")) { + $response->header("Client-Warning" => + "Unsupported authentication scheme '$scheme'"); + next CHALLENGE; + } + return $class->authenticate($self, $proxy, $challenge, $response, + $request, $arg, $size); + } + return $response; } return $response; } - # # Now the shortcuts... # @@ -411,12 +435,47 @@ sub get { return $self->request( HTTP::Request::Common::GET( @parameters ), @suff ); } +sub _has_raw_content { + my $self = shift; + shift; # drop url + + # taken from HTTP::Request::Common::request_type_with_data + my $content; + $content = shift if @_ and ref $_[0]; + my($k, $v); + while (($k,$v) = splice(@_, 0, 2)) { + if (lc($k) eq 'content') { + $content = $v; + } + } + + # We were given Content => 'string' ... + if (defined $content && ! ref ($content)) { + return 1; + } + + return; +} + +sub _maybe_copy_default_content_type { + my ($self, $req, @parameters) = @_; + + # If we have a default Content-Type and someone passes in a POST/PUT + # with Content => 'some-string-value', use that Content-Type instead + # of x-www-form-urlencoded + my $ct = $self->default_header('Content-Type'); + return unless defined $ct && $self->_has_raw_content(@parameters); + + $req->header('Content-Type' => $ct); +} sub post { require HTTP::Request::Common; my($self, @parameters) = @_; my @suff = $self->_process_colonic_headers(\@parameters, (ref($parameters[1]) ? 2 : 1)); - return $self->request( HTTP::Request::Common::POST( @parameters ), @suff ); + my $req = HTTP::Request::Common::POST(@parameters); + $self->_maybe_copy_default_content_type($req, @parameters); + return $self->request($req, @suff); } @@ -432,7 +491,9 @@ sub put { require HTTP::Request::Common; my($self, @parameters) = @_; my @suff = $self->_process_colonic_headers(\@parameters, (ref($parameters[1]) ? 2 : 1)); - return $self->request( HTTP::Request::Common::PUT( @parameters ), @suff ); + my $req = HTTP::Request::Common::PUT(@parameters); + $self->_maybe_copy_default_content_type($req, @parameters); + return $self->request($req, @suff); } @@ -460,7 +521,7 @@ sub _process_colonic_headers { Carp::croak("A :content_cb value can't be undef") unless defined $arg; Carp::croak("A :content_cb value must be a coderef") unless ref $arg and UNIVERSAL::isa($arg, 'CODE'); - + } elsif ($args->[$i] eq ':content_file') { $arg = $args->[$i + 1]; @@ -588,13 +649,13 @@ sub redirect_ok my $method = $response->request->method; return 0 unless grep $_ eq $method, @{ $self->requests_redirectable || [] }; - + if ($new_request->uri->scheme eq 'file') { $response->header("Client-Warning" => "Can't redirect to a file:// URL!"); return 0; } - + # Otherwise it's apparently okay... return 1; } @@ -726,7 +787,7 @@ sub default_header { return $self->default_headers->header(@_); } -sub _agent { "libwww-perl/$LWP::VERSION" } +sub _agent { "libwww-perl/$VERSION" } sub agent { my $self = shift; @@ -917,7 +978,7 @@ sub mirror } # Only fetching a fresh copy of the would be considered success. - # If the file was not modified, "304" would returned, which + # If the file was not modified, "304" would returned, which # is considered by HTTP::Status to be a "redirect", /not/ "success" if ( $response->is_success ) { my @stat = stat($tmpfile) or die "Could not stat tmpfile '$tmpfile': $!"; @@ -932,7 +993,7 @@ sub mirror unlink($tmpfile); die "Content-length mismatch: " . "expected $content_length bytes, got $file_length\n"; } - # The file was the expected length. + # The file was the expected length. else { # Replace the stale file with a fresh copy if ( -e $file ) { @@ -949,7 +1010,7 @@ sub mirror } } } - # The local copy is fresh enough, so just delete the temp file + # The local copy is fresh enough, so just delete the temp file else { unlink($tmpfile); } @@ -974,11 +1035,18 @@ sub _need_proxy { } -sub proxy -{ +sub proxy { my $self = shift; my $key = shift; - return map $self->proxy($_, @_), @$key if ref $key; + if (!@_ && ref $key eq 'ARRAY') { + die 'odd number of items in proxy arrayref!' unless @{$key} % 2 == 0; + + # This map reads the elements of $key 2 at a time + return + map { $self->proxy($key->[2 * $_], $key->[2 * $_ + 1]) } + (0 .. @{$key} / 2 - 1); + } + return map { $self->proxy($_, @_) } @$key if ref $key; Carp::croak("'$key' is not a valid URI scheme") unless $key =~ /^$URI::scheme_re\z/; my $old = $self->{'proxy'}{$key}; @@ -1052,20 +1120,24 @@ sub _new_response { __END__ +=pod + =head1 NAME LWP::UserAgent - Web user agent class =head1 SYNOPSIS - require LWP::UserAgent; - + use strict; + use warnings; + use LWP::UserAgent (); + my $ua = LWP::UserAgent->new; $ua->timeout(10); $ua->env_proxy; - + my $response = $ua->get('http://search.cpan.org/'); - + if ($response->is_success) { print $response->decoded_content; # or whatever } @@ -1075,35 +1147,48 @@ LWP::UserAgent - Web user agent class =head1 DESCRIPTION -The C is a class implementing a web user agent. -C objects can be used to dispatch web requests. +The L is a class implementing a web user agent. +L objects can be used to dispatch web requests. -In normal use the application creates an C object, and +In normal use the application creates an L object, and then configures it with values for timeouts, proxies, name, etc. It -then creates an instance of C for the request that +then creates an instance of L for the request that needs to be performed. This request is then passed to one of the request method the UserAgent, which dispatches it using the relevant -protocol, and returns a C object. There are -convenience methods for sending the most common request types: get(), -head(), post(), put() and delete(). When using these methods then the -creation of the request object is hidden as shown in the synopsis above. - -The basic approach of the library is to use HTTP style communication +protocol, and returns a L object. There are +convenience methods for sending the most common request types: +L, L, L, +L and L. When using these +methods, the creation of the request object is hidden as shown in the +synopsis above. + +The basic approach of the library is to use HTTP-style communication for all protocol schemes. This means that you will construct -C objects and receive C objects even +L objects and receive L objects even for non-HTTP resources like I and I. In order to achieve -even more similarity to HTTP style communications, gopher menus and +even more similarity to HTTP-style communications, I menus and file directories are converted to HTML documents. =head1 CONSTRUCTOR METHODS The following constructor methods are available: -=over 4 +=head2 clone -=item $ua = LWP::UserAgent->new( %options ) + my $ua2 = $ua->clone; -This method constructs a new C object and returns it. +Returns a copy of the L object. + +B: Please be aware that the clone method does not copy or clone your +C attribute. Due to the limited restrictions on what can be used +for your cookie jar, there is no way to clone the attribute. The C +attribute will be C in the new object instance. + +=head2 new + + my $ua = LWP::UserAgent->new( %options ) + +This method constructs a new L object and returns it. Key/value pair arguments may be provided to set up the initial state. The following options correspond to attribute methods described below: @@ -1115,7 +1200,7 @@ The following options correspond to attribute methods described below: cookie_jar undef default_headers HTTP::Headers->new local_address undef - ssl_opts { verify_hostname => 1 } + ssl_opts { verify_hostname => 1 } max_size undef max_redirect 7 parse_head 1 @@ -1123,92 +1208,77 @@ The following options correspond to attribute methods described below: protocols_forbidden undef requests_redirectable ['GET', 'HEAD'] timeout 180 + proxy undef + no_proxy [] The following additional options are also accepted: If the C option -is passed in with a TRUE value, then proxy settings are read from environment -variables (see env_proxy() method below). If C isn't provided the -C environment variable controls if env_proxy() is called -during initialization. If the C option is passed in, then a -C is set up (see conn_cache() method below). The C -value is passed on as the C for the connection cache. - -=item $ua->clone +is passed in with a true value, then proxy settings are read from environment +variables (see L). If C isn't provided, the +C environment variable controls if +L is called during initialization. If the +C option is passed in, then a C is set up (see +L). The C value is passed on as the +C for the connection cache. -Returns a copy of the LWP::UserAgent object. - -=back +C must be set as an arrayref of key/value pairs. C takes an +arrayref of domains. =head1 ATTRIBUTES The settings of the configuration attributes modify the behaviour of the -C when it dispatches requests. Most of these can also +L when it dispatches requests. Most of these can also be initialized by options passed to the constructor method. The following attribute methods are provided. The attribute value is left unchanged if no argument is given. The return value from each method is the old attribute value. -=over - -=item $ua->agent +=head2 agent -=item $ua->agent( $product_id ) + my $agent = $ua->agent; + $ua->agent('Checkbot/0.4 '); # append the defaul to the end + $ua->agent('Mozilla/5.0'); + $ua->agent(""); # don't identify Get/set the product token that is used to identify the user agent on -the network. The agent value is sent as the "User-Agent" header in -the requests. The default is the string returned by the _agent() -method (see below). +the network. The agent value is sent as the C header in +the requests. -If the $product_id ends with space then the _agent() string is -appended to it. +The default is a string of the form C, where C<#.###> is +substituted with the version number of this library. -The user agent string should be one or more simple product identifiers -with an optional version number separated by the "/" character. -Examples are: - - $ua->agent('Checkbot/0.4 ' . $ua->_agent); - $ua->agent('Checkbot/0.4 '); # same as above - $ua->agent('Mozilla/5.0'); - $ua->agent(""); # don't identify - -=item $ua->_agent - -Returns the default agent identifier. This is a string of the form -"libwww-perl/#.###", where "#.###" is substituted with the version number -of this library. - -=item $ua->from +If the provided string ends with space, the default C +string is appended to it. -=item $ua->from( $email_address ) +The user agent string should be one or more simple product identifiers +with an optional version number separated by the C character. -Get/set the e-mail address for the human user who controls -the requesting user agent. The address should be machine-usable, as -defined in RFC 822. The C value is send as the "From" header in -the requests. Example: +=head2 conn_cache - $ua->from('gaas@cpan.org'); + my $cache_obj = $ua->conn_cache; + $ua->conn_cache( $cache_obj ); -The default is to not send a "From" header. See the default_headers() -method for the more general interface that allow any header to be defaulted. +Get/set the L object to use. See L +for details. -=item $ua->cookie_jar +=head2 cookie_jar -=item $ua->cookie_jar( $cookie_jar_obj ) + my $jar = $ua->cookie_jar; + $ua->cookie_jar( $cookie_jar_obj ); Get/set the cookie jar object to use. The only requirement is that -the cookie jar object must implement the extract_cookies($response) and -add_cookie_header($request) methods. These methods will then be +the cookie jar object must implement the C and +C methods. These methods will then be invoked by the user agent as requests are sent and responses are -received. Normally this will be a C object or some +received. Normally this will be a L object or some subclass. -The default is to have no cookie_jar, i.e. never automatically add -"Cookie" headers to the requests. +The default is to have no cookie jar, i.e. never automatically add +C headers to the requests. -Shortcut: If a reference to a plain hash is passed in as the -$cookie_jar_object, then it is replaced with an instance of -C that is initialized based on the hash. This form also -automatically loads the C module. It means that: +Shortcut: If a reference to a plain hash is passed in, it is replaced with an +instance of L that is initialized based on the hash. This form +also automatically loads the L module. It means that: $ua->cookie_jar({ file => "$ENV{HOME}/.cookies.txt" }); @@ -1217,154 +1287,161 @@ is really just a shortcut for: require HTTP::Cookies; $ua->cookie_jar(HTTP::Cookies->new(file => "$ENV{HOME}/.cookies.txt")); -=item $ua->default_headers +=head2 credentials -=item $ua->default_headers( $headers_obj ) + my $creds = $ua->credentials(); + $ua->credentials( $netloc, $realm ); + $ua->credentials( $netloc, $realm, $uname, $pass ); + $ua->credentials("www.example.com:80", "Some Realm", "foo", "secret"); -Get/set the headers object that will provide default header values for -any requests sent. By default this will be an empty C -object. +Get/set the user name and password to be used for a realm. -=item $ua->default_header( $field ) +The C<$netloc> is a string of the form C<< : >>. The username and +password will only be passed to this server. -=item $ua->default_header( $field => $value ) +=head2 default_header -This is just a short-cut for $ua->default_headers->header( $field => -$value ). Example: + $ua->default_header( $field ); + $ua->default_header( $field => $value ); + $ua->default_header('Accept-Encoding' => scalar HTTP::Message::decodable()); + $ua->default_header('Accept-Language' => "no, en"); - $ua->default_header('Accept-Encoding' => scalar HTTP::Message::decodable()); - $ua->default_header('Accept-Language' => "no, en"); +This is just a shortcut for +C<< $ua->default_headers->header( $field => $value ) >>. -=item $ua->conn_cache +=head2 default_headers -=item $ua->conn_cache( $cache_obj ) + my $headers = $ua->default_headers; + $ua->default_headers( $headers_obj ); -Get/set the C object to use. See L -for details. +Get/set the headers object that will provide default header values for +any requests sent. By default this will be an empty L +object. -=item $ua->credentials( $netloc, $realm ) +=head2 from -=item $ua->credentials( $netloc, $realm, $uname, $pass ) + my $from = $ua->from; + $ua->from('foo@bar.com'); -Get/set the user name and password to be used for a realm. +Get/set the email address for the human user who controls +the requesting user agent. The address should be machine-usable, as +defined in L. The C value +is sent as the C header in the requests. -The $netloc is a string of the form ":". The username and -password will only be passed to this server. Example: +The default is to not send a C header. See +L for the more general interface that allow +any header to be defaulted. - $ua->credentials("www.example.com:80", "Some Realm", "foo", "secret"); -=item $ua->local_address +=head2 local_address -=item $ua->local_address( $address ) + my $address = $ua->local_address; + $ua->local_address( $address ); Get/set the local interface to bind to for network connections. The interface can be specified as a hostname or an IP address. This value is passed as the C argument to L. -=item $ua->max_size +=head2 max_redirect + + my $max = $ua->max_redirect; + $ua->max_redirect( $n ); + +This reads or sets the object's limit of how many times it will obey +redirection responses in a given request cycle. + +By default, the value is C<7>. This means that if you call L +and the response is a redirect elsewhere which is in turn a +redirect, and so on seven times, then LWP gives up after that seventh +request. + +=head2 max_size -=item $ua->max_size( $bytes ) + my $size = $ua->max_size; + $ua->max_size( $bytes ); Get/set the size limit for response content. The default is C, which means that there is no limit. If the returned response content is only partial, because the size limit was exceeded, then a -"Client-Aborted" header will be added to the response. The content +C header will be added to the response. The content might end up longer than C as we abort once appending a -chunk of data makes the length exceed the limit. The "Content-Length" +chunk of data makes the length exceed the limit. The C header, if present, will indicate the length of the full content and will normally not be the same as C<< length($res->content) >>. -=item $ua->max_redirect +=head2 parse_head -=item $ua->max_redirect( $n ) - -This reads or sets the object's limit of how many times it will obey -redirection responses in a given request cycle. - -By default, the value is 7. This means that if you call request() -method and the response is a redirect elsewhere which is in turn a -redirect, and so on seven times, then LWP gives up after that seventh -request. - -=item $ua->parse_head - -=item $ua->parse_head( $boolean ) + my $bool = $ua->parse_head; + $ua->parse_head( $boolean ); Get/set a value indicating whether we should initialize response headers from the Ehead> section of HTML documents. The default is -TRUE. Do not turn this off, unless you know what you are doing. +true. I unless you know what you are doing. -=item $ua->protocols_allowed +=head2 protocols_allowed -=item $ua->protocols_allowed( \@protocols ) + my $aref = $ua->protocols_allowed; # get allowed protocols + $ua->protocols_allowed( \@protocols ); # allow ONLY these + $ua->protocols_allowed(undef); # delete the list + $ua->protocols_allowed(['http',]); # ONLY allow http + +By default, an object has neither a C list, nor a +L list. This reads (or sets) this user agent's list of protocols that the request methods will exclusively allow. The protocol names are case insensitive. -For example: C<$ua-Eprotocols_allowed( [ 'http', 'https'] );> +For example: C<< $ua->protocols_allowed( [ 'http', 'https'] ); >> means that this user agent will I those protocols, and attempts to use this user agent to access URLs with any other -schemes (like "ftp://...") will result in a 500 error. - -To delete the list, call: C<$ua-Eprotocols_allowed(undef)> - -By default, an object has neither a C list, nor a -C list. +schemes (like C) will result in a 500 error. Note that having a C list causes any -C list to be ignored. +L list to be ignored. -=item $ua->protocols_forbidden +=head2 protocols_forbidden -=item $ua->protocols_forbidden( \@protocols ) + my $aref = $ua->protocols_forbidden; # get the forbidden list + $ua->protocols_forbidden(\@protocols); # do not allow these + $ua->protocols_forbidden(['http',]); # All http reqs get a 500 + $ua->protocols_forbidden(undef); # delete the list This reads (or sets) this user agent's list of protocols that the request method will I allow. The protocol names are case insensitive. -For example: C<$ua-Eprotocols_forbidden( [ 'file', 'mailto'] );> +For example: C<< $ua->protocols_forbidden( [ 'file', 'mailto'] ); >> means that this user agent will I allow those protocols, and attempts to use this user agent to access URLs with those schemes will result in a 500 error. -To delete the list, call: C<$ua-Eprotocols_forbidden(undef)> - -=item $ua->requests_redirectable +=head2 requests_redirectable -=item $ua->requests_redirectable( \@requests ) + my $aref = $ua->requests_redirectable; + $ua->requests_redirectable( \@requests ); + $ua->requests_redirectable(['GET', 'HEAD',]); # the default This reads or sets the object's list of request names that -C<$ua-Eredirect_ok(...)> will allow redirection for. By -default, this is C<['GET', 'HEAD']>, as per RFC 2616. To -change to include 'POST', consider: +L will allow redirection for. By default, this +is C<['GET', 'HEAD']>, as per L. +To change to include C, consider: push @{ $ua->requests_redirectable }, 'POST'; -=item $ua->show_progress +=head2 show_progress -=item $ua->show_progress( $boolean ) + my $bool = $ua->show_progress; + $ua->show_progress( $boolean ); Get/set a value indicating whether a progress bar should be displayed -on the terminal as requests are processed. The default is FALSE. +on the terminal as requests are processed. The default is false. -=item $ua->timeout +=head2 ssl_opts -=item $ua->timeout( $secs ) - -Get/set the timeout value in seconds. The default timeout() value is -180 seconds, i.e. 3 minutes. - -The requests is aborted if no activity on the connection to the server -is observed for C seconds. This means that the time it takes -for the complete transaction and the request() method to actually -return might be longer. - -=item $ua->ssl_opts - -=item $ua->ssl_opts( $key ) - -=item $ua->ssl_opts( $key => $value ) + my @keys = $ua->ssl_opts; + my $val = $ua->ssl_opts( $key ); + $ua->ssl_opts( $key => $value ); Get/set the options for SSL connections. Without argument return the list of options keys currently set. With a single argument return the current @@ -1408,41 +1485,29 @@ The libwww-perl core no longer bundles protocol plugins for SSL. You will need to install L separately to enable support for processing https-URLs. -=back +=head2 timeout -=head2 Proxy attributes + my $secs = $ua->timeout; + $ua->timeout( $secs ); -The following methods set up when requests should be passed via a -proxy server. - -=over - -=item $ua->proxy(\@schemes, $proxy_url) - -=item $ua->proxy($scheme, $proxy_url) - -Set/retrieve proxy URL for a scheme: - - $ua->proxy(['http', 'ftp'], 'http://proxy.sn.no:8001/'); - $ua->proxy('gopher', 'http://proxy.sn.no:8001/'); - -The first form specifies that the URL is to be used for proxying of -access methods listed in the list in the first method argument, -i.e. 'http' and 'ftp'. +Get/set the timeout value in seconds. The default value is +180 seconds, i.e. 3 minutes. -The second form shows a shorthand form for specifying -proxy URL for a single access scheme. +The requests is aborted if no activity on the connection to the server +is observed for C seconds. This means that the time it takes +for the complete transaction and the L method to +actually return might be longer. -=item $ua->no_proxy( $domain, ... ) +=head1 PROXY ATTRIBUTES -Do not proxy requests to the given domains. Calling no_proxy without -any domains clears the list of domains. Eg: +The following methods set up when requests should be passed via a +proxy server. - $ua->no_proxy('localhost', 'example.com'); +=head2 env_proxy -=item $ua->env_proxy + $ua->env_proxy; -Load proxy settings from *_proxy environment variables. You might +Load proxy settings from C<*_proxy> environment variables. You might specify proxies like this (sh-syntax): gopher_proxy=http://proxy.my.place/ @@ -1455,36 +1520,87 @@ environment variables. On systems with case insensitive environment variables there exists a name clash between the CGI environment variables and the C -environment variable normally picked up by env_proxy(). Because of +environment variable normally picked up by C. Because of this C is not honored for CGI scripts. The C environment variable can be used instead. -=back +=head2 no_proxy + + $ua->no_proxy( @domains ); + $ua->no_proxy('localhost', 'example.com'); + $ua->no_proxy(); # clear the list + +Do not proxy requests to the given domains. Calling C without +any domains clears the list of domains. + +=head2 proxy + + $ua->proxy(\@schemes, $proxy_url) + $ua->proxy(['http', 'ftp'], 'http://proxy.sn.no:8001/'); + + # For a single scheme: + $ua->proxy($scheme, $proxy_url) + $ua->proxy('gopher', 'http://proxy.sn.no:8001/'); + + # To set multiple proxies at once: + $ua->proxy([ + ftp => 'http://ftp.example.com:8001/', + [ 'http', 'https' ] => 'http://http.example.com:8001/', + ]); + +Set/retrieve proxy URL for a scheme. + +The first form specifies that the URL is to be used as a proxy for +access methods listed in the list in the first method argument, +i.e. C and C. + +The second form shows a shorthand form for specifying +proxy URL for a single access scheme. + +The third form demonstrates setting multiple proxies at once. This is also +the only form accepted by the constructor. -=head2 Handlers +=head1 HANDLERS Handlers are code that injected at various phases during the processing of requests. The following methods are provided to manage the active handlers: -=over +=head2 add_handler -=item $ua->add_handler( $phase => \&cb, %matchspec ) + $ua->add_handler( $phase => \&cb, %matchspec ) Add handler to be invoked in the given processing phase. For how to -specify %matchspec see L. +specify C<%matchspec> see L. -The possible values $phase and the corresponding callback signatures are: +The possible values C<$phase> and the corresponding callback signatures are: =over -=item request_preprepare => sub { my($request, $ua, $h) = @_; ... } +=item response_data => sub { my($response, $ua, $h, $data) = @_; ... } -The handler is called before the C and other standard -initialization of the request. This can be used to set up headers -and attributes that the C handler depends on. Proxy -initialization should take place here; but in general don't register -handlers for this phase. +This handler is called for each chunk of data received for the +response. The handler might croak to abort the request. + +This handler needs to return a TRUE value to be called again for +subsequent chunks for the same request. + +=item response_done => sub { my($response, $ua, $h) = @_; ... } + +The handler is called after the response has been fully received, but +before any redirect handling is attempted. The handler can be used to +extract information or modify the response. + +=item response_header => sub { my($response, $ua, $h) = @_; ... } + +This handler is called right after the response headers have been +received, but before any content data. The handler might set up +handlers for data and might croak to abort the request. + +The handler might set the $response->{default_add_content} value to +control if any received data should be added to the response object +directly. This will initially be false if the $ua->request() method +was called with a $content_file or $content_cb argument; otherwise true. =item request_prepare => sub { my($request, $ua, $h) = @_; ... } @@ -1499,6 +1615,14 @@ The return value from the callback is ignored. If an exception is raised it will abort the request and make the request method return a "400 Bad request" response. +=item request_preprepare => sub { my($request, $ua, $h) = @_; ... } + +The handler is called before the C and other standard +initialization of the request. This can be used to set up headers +and attributes that the C handler depends on. Proxy +initialization should take place here; but in general don't register +handlers for this phase. + =item request_send => sub { my($request, $ua, $h) = @_; ... } This handler gets a chance of handling requests before they're sent to the @@ -1508,31 +1632,6 @@ wishes to terminate the processing; otherwise it should return nothing. The C and C handlers will not be invoked for this response, but the C will be. -=item response_header => sub { my($response, $ua, $h) = @_; ... } - -This handler is called right after the response headers have been -received, but before any content data. The handler might set up -handlers for data and might croak to abort the request. - -The handler might set the $response->{default_add_content} value to -control if any received data should be added to the response object -directly. This will initially be false if the $ua->request() method -was called with a $content_file or $content_cb argument; otherwise true. - -=item response_data => sub { my($response, $ua, $h, $data) = @_; ... } - -This handler is called for each chunk of data received for the -response. The handler might croak to abort the request. - -This handler needs to return a TRUE value to be called again for -subsequent chunks for the same request. - -=item response_done => sub { my($response, $ua, $h) = @_; ... } - -The handler is called after the response has been fully received, but -before any redirect handling is attempted. The handler can be used to -extract information or modify the response. - =item response_redirect => sub { my($response, $ua, $h) = @_; ... } The handler is called in $ua->request after C. If the @@ -1541,60 +1640,77 @@ this request instead. =back -=item $ua->remove_handler( undef, %matchspec ) +=head2 get_my_handler -=item $ua->remove_handler( $phase, %matchspec ) + $ua->get_my_handler( $phase, %matchspec ); + $ua->get_my_handler( $phase, %matchspec, $init ); -Remove handlers that match the given %matchspec. If $phase is not -provided remove handlers from all phases. +Will retrieve the matching handler as hash ref. -Be careful as calling this function with %matchspec that is not -specific enough can remove handlers not owned by you. It's probably -better to use the set_my_handler() method instead. +If C<$init> is passed as a true value, create and add the +handler if it's not found. If C<$init> is a subroutine reference, then +it's called with the created handler hash as argument. This sub might +populate the hash with extra fields; especially the callback. If +C<$init> is a hash reference, merge the hashes. -The removed handlers are returned. +=head2 handlers -=item $ua->set_my_handler( $phase, $cb, %matchspec ) + $ua->handlers( $phase, $request ) + $ua->handlers( $phase, $response ) -Set handlers private to the executing subroutine. Works by defaulting -an C field to the %matchspec that holds the name of the called -subroutine. You might pass an explicit C to override this. +Returns the handlers that apply to the given request or response at +the given processing phase. -If $cb is passed as C, remove the handler. +=head2 remove_handler -=item $ua->get_my_handler( $phase, %matchspec ) + $ua->remove_handler( undef, %matchspec ); + $ua->remove_handler( $phase, %matchspec ); + $ua->remove_handlers(); # REMOVE ALL HANDLERS IN ALL PHASES -=item $ua->get_my_handler( $phase, %matchspec, $init ) +Remove handlers that match the given C<%matchspec>. If C<$phase> is not +provided, remove handlers from all phases. -Will retrieve the matching handler as hash ref. +Be careful as calling this function with C<%matchspec> that is not +specific enough can remove handlers not owned by you. It's probably +better to use the L method instead. -If C<$init> is passed as a TRUE value, create and add the -handler if it's not found. If $init is a subroutine reference, then -it's called with the created handler hash as argument. This sub might -populate the hash with extra fields; especially the callback. If -$init is a hash reference, merge the hashes. +The removed handlers are returned. -=item $ua->handlers( $phase, $request ) +=head2 set_my_handler -=item $ua->handlers( $phase, $response ) + $ua->set_my_handler( $phase, $cb, %matchspec ); + $ua->set_my_handler($phase, undef); # remove handler for phase -Returns the handlers that apply to the given request or response at -the given processing phase. +Set handlers private to the executing subroutine. Works by defaulting +an C field to the C<%matchspec> that holds the name of the called +subroutine. You might pass an explicit C to override this. -=back +If $cb is passed as C, remove the handler. =head1 REQUEST METHODS The methods described in this section are used to dispatch requests via the user agent. The following request methods are provided: -=over +=head2 delete -=item $ua->get( $url ) + my $res = $ua->delete( $url ); + my $res = $ua->delete( $url, $field_name => $value, ... ); -=item $ua->get( $url , $field_name => $value, ... ) +This method will dispatch a C request on the given URL. Additional +headers and content options are the same as for the L +method. -This method will dispatch a C request on the given $url. Further +This method will use the DELETE() function from L +to build the request. See L for a details on +how to pass form content and other advanced features. + +=head2 get + + my $res = $ua->get( $url ); + my $res = $ua->get( $url , $field_name => $value, ... ); + +This method will dispatch a C request on the given URL. Further arguments can be given to initialize the headers of the request. These are given as separate name/value pairs. The return value is a response object. See L for a description of the @@ -1627,7 +1743,10 @@ object itself. This might not be suitable for very large response bodies. Only one of C<:content_file> or C<:content_cb> can be specified. The content of unsuccessful responses will always accumulate in the response object itself, regardless of the -C<:content_file> or C<:content_cb> options passed in. +C<:content_file> or C<:content_cb> options passed in. Note that errors +writing to the content file (for example due to permission denied +or the filesystem being full) will be reported via the C +or C response headers, and not the C method. The C<:read_size_hint> option is passed to the protocol module which will try to read data from the server in chunks of this size. A @@ -1640,103 +1759,123 @@ object. The callback can abort the request by invoking die(). The exception message will show up as the "X-Died" header field in the response returned by the get() function. -=item $ua->head( $url ) +=head2 head -=item $ua->head( $url , $field_name => $value, ... ) + my $res = $ua->head( $url ); + my $res = $ua->head( $url , $field_name => $value, ... ); -This method will dispatch a C request on the given $url. -Otherwise it works like the get() method described above. +This method will dispatch a C request on the given URL. +Otherwise it works like the L method described above. -=item $ua->post( $url, \%form ) +=head2 is_protocol_supported -=item $ua->post( $url, \@form ) + my $bool = $ua->is_protocol_supported( $scheme ); -=item $ua->post( $url, \%form, $field_name => $value, ... ) +You can use this method to test whether this user agent object supports the +specified C. (The C might be a string (like C or +C) or it might be an L object reference.) -=item $ua->post( $url, $field_name => $value,... Content => \%form ) +Whether a scheme is supported is determined by the user agent's +C or C lists (if any), and by +the capabilities of LWP. I.e., this will return true only if LWP +supports this protocol I it's permitted for this particular +object. -=item $ua->post( $url, $field_name => $value,... Content => \@form ) +=head2 is_online -=item $ua->post( $url, $field_name => $value,... Content => $content ) + my $bool = $ua->is_online; -This method will dispatch a C request on the given $url, with -%form or @form providing the key/value pairs for the fill-in form -content. Additional headers and content options are the same as for -the get() method. +Tries to determine if you have access to the Internet. Returns C<1> (true) +if the built-in heuristics determine that the user agent is +able to access the Internet (over HTTP) or C<0> (false). -This method will use the POST() function from C -to build the request. See L for a details on -how to pass form content and other advanced features. +See also L. -=item $ua->put( $url, \%form ) +=head2 mirror -=item $ua->put( $url, \@form ) + my $res = $ua->mirror( $url, $filename ); -=item $ua->put( $url, \%form, $field_name => $value, ... ) +This method will get the document identified by URL and store it in +file called C<$filename>. If the file already exists, then the request +will contain an C header matching the modification +time of the file. If the document on the server has not changed since +this time, then nothing happens. If the document has been updated, it +will be downloaded again. The modification time of the file will be +forced to match that of the server. -=item $ua->put( $url, $field_name => $value,... Content => \%form ) +The return value is an L object. -=item $ua->put( $url, $field_name => $value,... Content => \@form ) +=head2 post -=item $ua->put( $url, $field_name => $value,... Content => $content ) + my $res = $ua->post( $url, \%form ); + my $res = $ua->post( $url, \@form ); + my $res = $ua->post( $url, \%form, $field_name => $value, ... ); + my $res = $ua->post( $url, $field_name => $value, Content => \%form ); + my $res = $ua->post( $url, $field_name => $value, Content => \@form ); + my $res = $ua->post( $url, $field_name => $value, Content => $content ); -This method will dispatch a C request on the given $url, with -%form or @form providing the key/value pairs for the fill-in form +This method will dispatch a C request on the given URL, with +C<%form> or C<@form> providing the key/value pairs for the fill-in form content. Additional headers and content options are the same as for -the get() method. +the L method. -This method will use the PUT() function from C +This method will use the C function from L to build the request. See L for a details on how to pass form content and other advanced features. -=item $ua->delete( $url ) +=head2 put -=item $ua->delete( $url, $field_name => $value, ... ) + # Any version of HTTP::Message works with this form: + my $res = $ua->put( $url, $field_name => $value, Content => $content ); -This method will dispatch a C request on the given $url. Additional -headers and content options are the same as for the get() method. + # Using hash or array references requires HTTP::Message >= 6.07 + use HTTP::Request 6.07; + my $res = $ua->put( $url, \%form ); + my $res = $ua->put( $url, \@form ); + my $res = $ua->put( $url, \%form, $field_name => $value, ... ); + my $res = $ua->put( $url, $field_name => $value, Content => \%form ); + my $res = $ua->put( $url, $field_name => $value, Content => \@form ); -This method will use the DELETE() function from C -to build the request. See L for a details on -how to pass form content and other advanced features. - -=item $ua->mirror( $url, $filename ) - -This method will get the document identified by $url and store it in -file called $filename. If the file already exists, then the request -will contain an "If-Modified-Since" header matching the modification -time of the file. If the document on the server has not changed since -this time, then nothing happens. If the document has been updated, it -will be downloaded again. The modification time of the file will be -forced to match that of the server. +This method will dispatch a C request on the given URL, with +C<%form> or C<@form> providing the key/value pairs for the fill-in form +content. Additional headers and content options are the same as for +the L method. -The return value is the response object. +CAVEAT: -=item $ua->request( $request ) +This method can only accept content that is in key-value pairs when using +L prior to version C<6.07>. Any use of hash or array +references will result in an error prior to version C<6.07>. -=item $ua->request( $request, $content_file ) +This method will use the C function from L +to build the request. See L for a details on +how to pass form content and other advanced features. -=item $ua->request( $request, $content_cb ) +=head2 request -=item $ua->request( $request, $content_cb, $read_size_hint ) + my $res = $ua->request( $request ); + my $res = $ua->request( $request, $content_file ); + my $res = $ua->request( $request, $content_cb ); + my $res = $ua->request( $request, $content_cb, $read_size_hint ); -This method will dispatch the given $request object. Normally this -will be an instance of the C class, but any object with -a similar interface will do. The return value is a response object. -See L and L for a description of the -interface provided by these classes. +This method will dispatch the given C<$request> object. Normally this +will be an instance of the L class, but any object with +a similar interface will do. The return value is an L object. -The request() method will process redirects and authentication -responses transparently. This means that it may actually send several -simple requests via the simple_request() method described below. +The C method will process redirects and authentication +responses transparently. This means that it may actually send several +simple requests via the L method described below. -The request methods described above; get(), head(), post() and -mirror(), will all dispatch the request they build via this method. -They are convenience methods that simply hides the creation of the -request object for you. +The request methods described above; L, L, +L and L will all dispatch the request +they build via this method. They are convenience methods that simply hide the +creation of the request object for you. -The $content_file, $content_cb and $read_size_hint all correspond to -options described with the get() method above. +The C<$content_file>, C<$content_cb> and C<$read_size_hint> all correspond to +options described with the L method above. Note that errors +writing to the content file (for example due to permission denied +or the filesystem being full) will be reported via the C +or C response headers, and not the C method. You are allowed to use a CODE reference as C in the request object passed in. The C function should return the content @@ -1744,78 +1883,38 @@ when called. The content can be returned in chunks. The content function will be invoked repeatedly until it return an empty string to signal that there is no more content. -=item $ua->simple_request( $request ) - -=item $ua->simple_request( $request, $content_file ) - -=item $ua->simple_request( $request, $content_cb ) +=head2 simple_request -=item $ua->simple_request( $request, $content_cb, $read_size_hint ) + my $request = HTTP::Request->new( ... ); + my $res = $ua->simple_request( $request ); + my $res = $ua->simple_request( $request, $content_file ); + my $res = $ua->simple_request( $request, $content_cb ); + my $res = $ua->simple_request( $request, $content_cb, $read_size_hint ); This method dispatches a single request and returns the response -received. Arguments are the same as for request() described above. +received. Arguments are the same as for the L described above. -The difference from request() is that simple_request() will not try to -handle redirects or authentication responses. The request() method -will in fact invoke this method for each simple request it sends. +The difference from L is that C will not try to +handle redirects or authentication responses. The L method +will, in fact, invoke this method for each simple request it sends. -=item $ua->is_online - -Tries to determine if you have access to the Internet. Returns -TRUE if the built-in heuristics determine that the user agent is -able to access the Internet (over HTTP). See also L. - -=item $ua->is_protocol_supported( $scheme ) - -You can use this method to test whether this user agent object supports the -specified C. (The C might be a string (like 'http' or -'ftp') or it might be an URI object reference.) - -Whether a scheme is supported, is determined by the user agent's -C or C lists (if any), and by -the capabilities of LWP. I.e., this will return TRUE only if LWP -supports this protocol I it's permitted for this particular -object. - -=back - -=head2 Callback methods +=head1 CALLBACK METHODS The following methods will be invoked as requests are processed. These -methods are documented here because subclasses of C +methods are documented here because subclasses of L might want to override their behaviour. -=over - -=item $ua->prepare_request( $request ) +=head2 get_basic_credentials -This method is invoked by simple_request(). Its task is to modify the -given $request object by setting up various headers based on the -attributes of the user agent. The return value should normally be the -$request object passed in. If a different request object is returned -it will be the one actually processed. + # This checks wantarray and can either return an array: + my ($user, $pass) = $ua->get_basic_credentials( $realm, $uri, $isproxy ); + # or a string that looks like "user:pass" + my $creds = $ua->get_basic_credentials($realm, $uri, $isproxy); -The headers affected by the base implementation are; "User-Agent", -"From", "Range" and "Cookie". - -=item $ua->redirect_ok( $prospective_request, $response ) - -This method is called by request() before it tries to follow a -redirection to the request in $response. This should return a TRUE -value if this redirection is permissible. The $prospective_request -will be the request to be sent if this method returns TRUE. - -The base implementation will return FALSE unless the method -is in the object's C list, -FALSE if the proposed redirection is to a "file://..." -URL, and TRUE otherwise. - -=item $ua->get_basic_credentials( $realm, $uri, $isproxy ) - -This is called by request() to retrieve credentials for documents +This is called by L to retrieve credentials for documents protected by Basic or Digest Authentication. The arguments passed in -is the $realm provided by the server, the $uri requested and a boolean -flag to indicate if this is authentication against a proxy server. +is the C<$realm> provided by the server, the C<$uri> requested and a +C to indicate if this is authentication against a proxy server. The method should return a username and password. It should return an empty list to abort the authentication resolution attempt. Subclasses @@ -1824,21 +1923,48 @@ example of this can be found in C program distributed with this library. The base implementation simply checks a set of pre-stored member -variables, set up with the credentials() method. +variables, set up with the L method. + +=head2 prepare_request + + $request = $ua->prepare_request( $request ); + +This method is invoked by L. Its task is +to modify the given C<$request> object by setting up various headers based +on the attributes of the user agent. The return value should normally be the +C<$request> object passed in. If a different request object is returned +it will be the one actually processed. + +The headers affected by the base implementation are; C, +C, C and C. + +=head2 progress -=item $ua->progress( $status, $request_or_response ) + my $prog = $ua->progress( $status, $request_or_response ); This is called frequently as the response is received regardless of -how the content is processed. The method is called with $status -"begin" at the start of processing the request and with $state "end" -before the request method returns. In between these $status will be +how the content is processed. The method is called with C<$status> +"begin" at the start of processing the request and with C<$state> "end" +before the request method returns. In between these C<$status> will be the fraction of the response currently received or the string "tick" if the fraction can't be calculated. -When $status is "begin" the second argument is the request object, -otherwise it is the response object. +When C<$status> is "begin" the second argument is the L object, +otherwise it is the L object. -=back +=head2 redirect_ok + + my $bool = $ua->redirect_ok( $prospective_request, $response ); + +This method is called by L before it tries to follow a +redirection to the request in C<$response>. This should return a true +value if this redirection is permissible. The C<$prospective_request> +will be the request to be sent if this method returns true. + +The base implementation will return false unless the method +is in the object's C list, +false if the proposed redirection is to a C +URL, and true otherwise. =head1 SEE ALSO @@ -1851,11 +1977,13 @@ message objects dispatched and received. See L and L for other ways to build request objects. See L and L for examples of more -specialized user agents based on C. +specialized user agents based on L. -=head1 COPYRIGHT +=head1 COPYRIGHT AND LICENSE Copyright 1995-2009 Gisle Aas. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. + +=cut diff --git a/Master/tlpkg/tlperl/site/lib/Net/HTTP.pm b/Master/tlpkg/tlperl/site/lib/Net/HTTP.pm index 0c923eddbec..1f2c9fbf2d0 100644 --- a/Master/tlpkg/tlperl/site/lib/Net/HTTP.pm +++ b/Master/tlpkg/tlperl/site/lib/Net/HTTP.pm @@ -1,11 +1,9 @@ package Net::HTTP; - +$Net::HTTP::VERSION = '6.13'; use strict; -use vars qw($VERSION @ISA $SOCKET_CLASS); - -$VERSION = "6.09"; -$VERSION = eval $VERSION; +use warnings; +use vars qw($SOCKET_CLASS); unless ($SOCKET_CLASS) { # Try several, in order of capability and preference if (eval { require IO::Socket::IP }) { @@ -22,7 +20,7 @@ unless ($SOCKET_CLASS) { require Net::HTTP::Methods; require Carp; -@ISA = ($SOCKET_CLASS, 'Net::HTTP::Methods'); +our @ISA = ($SOCKET_CLASS, 'Net::HTTP::Methods'); sub new { my $class = shift; @@ -42,12 +40,18 @@ sub http_connect { 1; -__END__ +=pod + +=encoding UTF-8 =head1 NAME Net::HTTP - Low-level HTTP connection (client) +=head1 VERSION + +version 6.13 + =head1 SYNOPSIS use Net::HTTP; @@ -284,11 +288,20 @@ names prefixed with C and C. L, L, L -=head1 COPYRIGHT +=head1 AUTHOR -Copyright 2001-2003 Gisle Aas. +Gisle Aas -This library is free software; you can redistribute it and/or -modify it under the same terms as Perl itself. +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2001-2017 by Gisle Aas. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. =cut + +__END__ + +# ABSTRACT: Low-level HTTP connection (client) + diff --git a/Master/tlpkg/tlperl/site/lib/Net/HTTP/Methods.pm b/Master/tlpkg/tlperl/site/lib/Net/HTTP/Methods.pm index 3c3c5ca6558..148028444f5 100644 --- a/Master/tlpkg/tlperl/site/lib/Net/HTTP/Methods.pm +++ b/Master/tlpkg/tlperl/site/lib/Net/HTTP/Methods.pm @@ -1,14 +1,9 @@ package Net::HTTP::Methods; - -require 5.005; # 4-arg substr - +$Net::HTTP::Methods::VERSION = '6.13'; use strict; -use vars qw($VERSION); +use warnings; use URI; -$VERSION = "6.09"; -$VERSION = eval $VERSION; - my $CRLF = "\015\012"; # "\r\n" is not portable *_bytes = defined(&utf8::downgrade) ? @@ -279,6 +274,8 @@ sub my_readline { if(defined $bytes_read) { $new_bytes += $bytes_read; last if $bytes_read < 1024; + # We got exactly 1024 bytes, so we need to select() to know if there is more data + last unless $self->can_read(0); } elsif($!{EINTR} || $!{EAGAIN} || $!{EWOULDBLOCK}) { redo READ; @@ -310,6 +307,7 @@ sub can_read { my $self = shift; return 1 unless defined(fileno($self)); return 1 if $self->isa('IO::Socket::SSL') && $self->pending; + return 1 if $self->isa('Net::SSL') && $self->can('pending') && $self->pending; # With no timeout, wait forever. An explicit timeout of 0 can be # used to just check if the socket is readable without waiting. @@ -323,8 +321,8 @@ sub can_read { $before = time if $timeout; my $nfound = select($fbits, undef, undef, $timeout); if ($nfound < 0) { - if ($!{EINTR} || $!{EAGAIN}) { - # don't really think EAGAIN can happen here + if ($!{EINTR} || $!{EAGAIN} || $!{EWOULDBLOCK}) { + # don't really think EAGAIN/EWOULDBLOCK can happen here if ($timeout) { $timeout -= time - $before; $timeout = 0 if $timeout < 0; @@ -646,3 +644,30 @@ sub inflate_ok { } # BEGIN 1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Net::HTTP::Methods + +=head1 VERSION + +version 6.13 + +=head1 AUTHOR + +Gisle Aas + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2001-2017 by Gisle Aas. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/Master/tlpkg/tlperl/site/lib/Net/HTTP/NB.pm b/Master/tlpkg/tlperl/site/lib/Net/HTTP/NB.pm index d908cf8f180..0d5ce9a96c8 100644 --- a/Master/tlpkg/tlperl/site/lib/Net/HTTP/NB.pm +++ b/Master/tlpkg/tlperl/site/lib/Net/HTTP/NB.pm @@ -1,13 +1,9 @@ package Net::HTTP::NB; - +$Net::HTTP::NB::VERSION = '6.13'; use strict; -use vars qw($VERSION @ISA); - -$VERSION = "6.09"; -$VERSION = eval $VERSION; +use warnings; -require Net::HTTP; -@ISA=qw(Net::HTTP); +use base 'Net::HTTP'; sub can_read { return 1; @@ -54,12 +50,18 @@ sub read_entity_body { 1; -__END__ +=pod + +=encoding UTF-8 =head1 NAME Net::HTTP::NB - Non-blocking HTTP client +=head1 VERSION + +version 6.13 + =head1 SYNOPSIS use Net::HTTP::NB; @@ -100,11 +102,20 @@ the value -1 is returned. L -=head1 COPYRIGHT +=head1 AUTHOR -Copyright 2001 Gisle Aas. +Gisle Aas -This library is free software; you can redistribute it and/or -modify it under the same terms as Perl itself. +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2001-2017 by Gisle Aas. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. =cut + +__END__ + +#ABSTRACT: Non-blocking HTTP client + diff --git a/Master/tlpkg/tlperl/site/lib/Net/HTTPS.pm b/Master/tlpkg/tlperl/site/lib/Net/HTTPS.pm index 10c5c8a950a..f8131c1f1c5 100644 --- a/Master/tlpkg/tlperl/site/lib/Net/HTTPS.pm +++ b/Master/tlpkg/tlperl/site/lib/Net/HTTPS.pm @@ -1,12 +1,10 @@ package Net::HTTPS; - +$Net::HTTPS::VERSION = '6.13'; use strict; -use vars qw($VERSION $SSL_SOCKET_CLASS @ISA); - -$VERSION = "6.09"; -$VERSION = eval $VERSION; +use warnings; # Figure out which SSL implementation to use +use vars qw($SSL_SOCKET_CLASS); if ($SSL_SOCKET_CLASS) { # somebody already set it } @@ -43,7 +41,7 @@ else { require Net::HTTP::Methods; -@ISA=($SSL_SOCKET_CLASS, 'Net::HTTP::Methods'); +our @ISA=($SSL_SOCKET_CLASS, 'Net::HTTP::Methods'); sub configure { my($self, $cnf) = @_; @@ -82,16 +80,24 @@ if ($SSL_SOCKET_CLASS eq "Net::SSL") { 1; +=pod + +=encoding UTF-8 + =head1 NAME Net::HTTPS - Low-level HTTP over SSL/TLS connection (client) +=head1 VERSION + +version 6.13 + =head1 DESCRIPTION The C is a low-level HTTP over SSL/TLS client. The interface is the same -as the interface for C, but the constructor method take additional parameters -as accepted by L. The C object isa C -too, which make it inherit additional methods from that base class. +as the interface for C, but the constructor takes additional parameters +as accepted by L. The C object is an C +too, which makes it inherit additional methods from that base class. For historical reasons this module also supports using C (from the Crypt-SSLeay distribution) as its SSL driver and base class. This base is @@ -109,3 +115,21 @@ is C. Currently the only other supported value is C. =head1 SEE ALSO L, L + +=head1 AUTHOR + +Gisle Aas + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2001-2017 by Gisle Aas. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut + +__END__ + +#ABSTRACT: Low-level HTTP over SSL/TLS connection (client) + diff --git a/Master/tlpkg/tlperl/site/lib/Socket.pm b/Master/tlpkg/tlperl/site/lib/Socket.pm index 591791e80ec..64e18ad25e3 100644 --- a/Master/tlpkg/tlperl/site/lib/Socket.pm +++ b/Master/tlpkg/tlperl/site/lib/Socket.pm @@ -3,7 +3,7 @@ package Socket; use strict; { use 5.006001; } -our $VERSION = '2.021'; +our $VERSION = '2.024'; =head1 NAME @@ -108,6 +108,10 @@ C level. Socket option name constants for IPv4 socket options at the C level. +=head2 IP_PMTUDISC_WANT, IP_PMTUDISC_DONT, ... + +Socket option value contants for C socket option. + =head2 IPTOS_LOWDELAY, IPTOS_THROUGHPUT, IPTOS_RELIABILITY, ... Socket option value constants for C socket option. @@ -180,6 +184,9 @@ arguments packed in and C filled in. For Internet domain sockets, this structure is normally what you need for the arguments in bind(), connect(), and send(). +An undefined $port argument is taken as zero; an undefined $ip_address is +considered a fatal error. + =head2 ($port, $ip_address) = unpack_sockaddr_in $sockaddr Takes a C structure (as returned by pack_sockaddr_in(), @@ -209,6 +216,9 @@ inet_pton()), optionally a scope ID number, and optionally a flow label number. Returns the C structure with those arguments packed in and C filled in. IPv6 equivalent of pack_sockaddr_in(). +An undefined $port argument is taken as zero; an undefined $ip6_address is +considered a fatal error. + =head2 ($port, $ip6_address, $scope_id, $flowinfo) = unpack_sockaddr_in6 $sockaddr Takes a C structure. Returns a list of four elements: the port @@ -722,8 +732,8 @@ our @EXPORT = qw( SO_SECURITY_ENCRYPTION_TRANSPORT SO_SNDBUF SO_SNDLOWAT SO_SNDTIMEO SO_STATE SO_TYPE SO_USELOOPBACK SO_XOPEN SO_XSE - IP_OPTIONS IP_HDRINCL IP_TOS IP_TTL IP_RECVOPTS IP_RECVRETOPTS - IP_RETOPTS + IP_HDRINCL IP_OPTIONS IP_RECVOPTS IP_RECVRETOPTS IP_RETOPTS IP_TOS + IP_TTL MSG_BCAST MSG_BTAG MSG_CTLFLAGS MSG_CTLIGNORE MSG_CTRUNC MSG_DONTROUTE MSG_DONTWAIT MSG_EOF MSG_EOR MSG_ERRQUEUE MSG_ETAG MSG_FASTOPEN MSG_FIN @@ -756,14 +766,17 @@ our @EXPORT_OK = qw( SOCK_NONBLOCK SOCK_CLOEXEC - IP_ADD_MEMBERSHIP IP_ADD_SOURCE_MEMBERSHIP IP_DROP_MEMBERSHIP - IP_DROP_SOURCE_MEMBERSHIP IP_MULTICAST_IF IP_MULTICAST_LOOP - IP_MULTICAST_TTL + IP_ADD_MEMBERSHIP IP_ADD_SOURCE_MEMBERSHIP IP_BIND_ADDRESS_NO_PORT + IP_DROP_MEMBERSHIP IP_DROP_SOURCE_MEMBERSHIP IP_FREEBIND + IP_MULTICAST_ALL IP_MULTICAST_IF IP_MULTICAST_LOOP IP_MULTICAST_TTL + IP_MTU IP_MTU_DISCOVER IP_NODEFRAG IP_RECVERR IP_TRANSPARENT IPPROTO_IP IPPROTO_IPV6 IPPROTO_RAW IPPROTO_ICMP IPPROTO_IGMP IPPROTO_TCP IPPROTO_UDP IPPROTO_GRE IPPROTO_ESP IPPROTO_AH IPPROTO_SCTP + IP_PMTUDISC_DO IP_PMTUDISC_DONT IP_PMTUDISC_PROBE IP_PMTUDISC_WANT + IPTOS_LOWDELAY IPTOS_THROUGHPUT IPTOS_RELIABILITY IPTOS_MINCOST TCP_CONGESTION TCP_CONNECTIONTIMEOUT TCP_CORK TCP_DEFER_ACCEPT @@ -774,9 +787,12 @@ our @EXPORT_OK = qw( IN6ADDR_ANY IN6ADDR_LOOPBACK - IPV6_ADD_MEMBERSHIP IPV6_DROP_MEMBERSHIP IPV6_JOIN_GROUP + IPV6_ADDRFROM IPV6_ADD_MEMBERSHIP IPV6_DROP_MEMBERSHIP IPV6_JOIN_GROUP IPV6_LEAVE_GROUP IPV6_MTU IPV6_MTU_DISCOVER IPV6_MULTICAST_HOPS - IPV6_MULTICAST_IF IPV6_MULTICAST_LOOP IPV6_UNICAST_HOPS IPV6_V6ONLY + IPV6_MULTICAST_IF IPV6_MULTICAST_LOOP IPV6_RECVERR IPV6_ROUTER_ALERT + IPV6_UNICAST_HOPS IPV6_V6ONLY + + SO_LOCK_FILTER SO_RCVBUFFORCE SO_SNDBUFFORCE pack_ip_mreq unpack_ip_mreq pack_ip_mreq_source unpack_ip_mreq_source diff --git a/Master/tlpkg/tlperl/site/lib/Test/Fatal.pm b/Master/tlpkg/tlperl/site/lib/Test/Fatal.pm new file mode 100644 index 00000000000..29aa6629fb3 --- /dev/null +++ b/Master/tlpkg/tlperl/site/lib/Test/Fatal.pm @@ -0,0 +1,364 @@ +use strict; +use warnings; +package Test::Fatal; +# ABSTRACT: incredibly simple helpers for testing code with exceptions +$Test::Fatal::VERSION = '0.014'; +#pod =head1 SYNOPSIS +#pod +#pod use Test::More; +#pod use Test::Fatal; +#pod +#pod use System::Under::Test qw(might_die); +#pod +#pod is( +#pod exception { might_die; }, +#pod undef, +#pod "the code lived", +#pod ); +#pod +#pod like( +#pod exception { might_die; }, +#pod qr/turns out it died/, +#pod "the code died as expected", +#pod ); +#pod +#pod isa_ok( +#pod exception { might_die; }, +#pod 'Exception::Whatever', +#pod 'the thrown exception', +#pod ); +#pod +#pod =head1 DESCRIPTION +#pod +#pod Test::Fatal is an alternative to the popular L. It does much +#pod less, but should allow greater flexibility in testing exception-throwing code +#pod with about the same amount of typing. +#pod +#pod It exports one routine by default: C. +#pod +#pod =cut + +use Carp (); +use Try::Tiny 0.07; + +use Exporter 5.57 'import'; + +our @EXPORT = qw(exception); +our @EXPORT_OK = qw(exception success dies_ok lives_ok); + +#pod =func exception +#pod +#pod my $exception = exception { ... }; +#pod +#pod C takes a bare block of code and returns the exception thrown by +#pod that block. If no exception was thrown, it returns undef. +#pod +#pod B If the block results in a I exception, such as 0 or the +#pod empty string, Test::Fatal itself will die. Since either of these cases +#pod indicates a serious problem with the system under testing, this behavior is +#pod considered a I. If you must test for these conditions, you should use +#pod L's try/catch mechanism. (Try::Tiny is the underlying exception +#pod handling system of Test::Fatal.) +#pod +#pod Note that there is no TAP assert being performed. In other words, no "ok" or +#pod "not ok" line is emitted. It's up to you to use the rest of C in an +#pod existing test like C, C, C, et cetera. Or you may wish to use +#pod the C and C wrappers, which do provide TAP output. +#pod +#pod C does I alter the stack presented to the called block, meaning +#pod that if the exception returned has a stack trace, it will include some frames +#pod between the code calling C and the thing throwing the exception. +#pod This is considered a I because it avoids the occasionally twitchy +#pod C mechanism. +#pod +#pod B This is not a great idea: +#pod +#pod sub exception_like(&$;$) { +#pod my ($code, $pattern, $name) = @_; +#pod like( &exception($code), $pattern, $name ); +#pod } +#pod +#pod exception_like(sub { }, qr/foo/, 'foo appears in the exception'); +#pod +#pod If the code in the C<...> is going to throw a stack trace with the arguments to +#pod each subroutine in its call stack (for example via C, +#pod the test name, "foo appears in the exception" will itself be matched by the +#pod regex. Instead, write this: +#pod +#pod like( exception { ... }, qr/foo/, 'foo appears in the exception' ); +#pod +#pod B: One final bad idea: +#pod +#pod isnt( exception { ... }, undef, "my code died!"); +#pod +#pod It's true that this tests that your code died, but you should really test that +#pod it died I. For example, if you make an unrelated mistake +#pod in the block, like using the wrong dereference, your test will pass even though +#pod the code to be tested isn't really run at all. If you're expecting an +#pod inspectable exception with an identifier or class, test that. If you're +#pod expecting a string exception, consider using C. +#pod +#pod =cut + +our ($REAL_TBL, $REAL_CALCULATED_TBL) = (1, 1); + +sub exception (&) { + my $code = shift; + + return try { + my $incremented = $Test::Builder::Level - $REAL_CALCULATED_TBL; + local $Test::Builder::Level = $REAL_CALCULATED_TBL; + if ($incremented) { + # each call to exception adds 5 stack frames + $Test::Builder::Level += 5; + for my $i (1..$incremented) { + # -2 because we want to see it from the perspective of the call to + # is() within the call to $code->() + my $caller = caller($Test::Builder::Level - 2); + if ($caller eq __PACKAGE__) { + # each call to exception adds 5 stack frames + $Test::Builder::Level = $Test::Builder::Level + 5; + } + else { + $Test::Builder::Level = $Test::Builder::Level + 1; + } + } + } + + local $REAL_CALCULATED_TBL = $Test::Builder::Level; + $code->(); + return undef; + } catch { + return $_ if $_; + + my $problem = defined $_ ? 'false' : 'undef'; + Carp::confess("$problem exception caught by Test::Fatal::exception"); + }; +} + +#pod =func success +#pod +#pod try { +#pod should_live; +#pod } catch { +#pod fail("boo, we died"); +#pod } success { +#pod pass("hooray, we lived"); +#pod }; +#pod +#pod C, exported only by request, is a L helper with semantics +#pod identical to L|Try::Tiny/finally>, but the body of the block will +#pod only be run if the C block ran without error. +#pod +#pod Although almost any needed exception tests can be performed with C, +#pod success blocks may sometimes help organize complex testing. +#pod +#pod =cut + +sub success (&;@) { + my $code = shift; + return finally( sub { + return if @_; # <-- only run on success + $code->(); + }, @_ ); +} + +#pod =func dies_ok +#pod +#pod =func lives_ok +#pod +#pod Exported only by request, these two functions run a given block of code, and +#pod provide TAP output indicating if it did, or did not throw an exception. +#pod These provide an easy upgrade path for replacing existing unit tests based on +#pod C. +#pod +#pod RJBS does not suggest using this except as a convenience while porting tests to +#pod use Test::Fatal's C routine. +#pod +#pod use Test::More tests => 2; +#pod use Test::Fatal qw(dies_ok lives_ok); +#pod +#pod dies_ok { die "I failed" } 'code that fails'; +#pod +#pod lives_ok { return "I'm still alive" } 'code that does not fail'; +#pod +#pod =cut + +my $Tester; + +# Signature should match that of Test::Exception +sub dies_ok (&;$) { + my $code = shift; + my $name = shift; + + require Test::Builder; + $Tester ||= Test::Builder->new; + + my $ok = $Tester->ok( exception( \&$code ), $name ); + $ok or $Tester->diag( "expected an exception but none was raised" ); + return $ok; +} + +sub lives_ok (&;$) { + my $code = shift; + my $name = shift; + + require Test::Builder; + $Tester ||= Test::Builder->new; + + my $ok = $Tester->ok( !exception( \&$code ), $name ); + $ok or $Tester->diag( "expected return but an exception was raised" ); + return $ok; +} + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Test::Fatal - incredibly simple helpers for testing code with exceptions + +=head1 VERSION + +version 0.014 + +=head1 SYNOPSIS + + use Test::More; + use Test::Fatal; + + use System::Under::Test qw(might_die); + + is( + exception { might_die; }, + undef, + "the code lived", + ); + + like( + exception { might_die; }, + qr/turns out it died/, + "the code died as expected", + ); + + isa_ok( + exception { might_die; }, + 'Exception::Whatever', + 'the thrown exception', + ); + +=head1 DESCRIPTION + +Test::Fatal is an alternative to the popular L. It does much +less, but should allow greater flexibility in testing exception-throwing code +with about the same amount of typing. + +It exports one routine by default: C. + +=head1 FUNCTIONS + +=head2 exception + + my $exception = exception { ... }; + +C takes a bare block of code and returns the exception thrown by +that block. If no exception was thrown, it returns undef. + +B If the block results in a I exception, such as 0 or the +empty string, Test::Fatal itself will die. Since either of these cases +indicates a serious problem with the system under testing, this behavior is +considered a I. If you must test for these conditions, you should use +L's try/catch mechanism. (Try::Tiny is the underlying exception +handling system of Test::Fatal.) + +Note that there is no TAP assert being performed. In other words, no "ok" or +"not ok" line is emitted. It's up to you to use the rest of C in an +existing test like C, C, C, et cetera. Or you may wish to use +the C and C wrappers, which do provide TAP output. + +C does I alter the stack presented to the called block, meaning +that if the exception returned has a stack trace, it will include some frames +between the code calling C and the thing throwing the exception. +This is considered a I because it avoids the occasionally twitchy +C mechanism. + +B This is not a great idea: + + sub exception_like(&$;$) { + my ($code, $pattern, $name) = @_; + like( &exception($code), $pattern, $name ); + } + + exception_like(sub { }, qr/foo/, 'foo appears in the exception'); + +If the code in the C<...> is going to throw a stack trace with the arguments to +each subroutine in its call stack (for example via C, +the test name, "foo appears in the exception" will itself be matched by the +regex. Instead, write this: + + like( exception { ... }, qr/foo/, 'foo appears in the exception' ); + +B: One final bad idea: + + isnt( exception { ... }, undef, "my code died!"); + +It's true that this tests that your code died, but you should really test that +it died I. For example, if you make an unrelated mistake +in the block, like using the wrong dereference, your test will pass even though +the code to be tested isn't really run at all. If you're expecting an +inspectable exception with an identifier or class, test that. If you're +expecting a string exception, consider using C. + +=head2 success + + try { + should_live; + } catch { + fail("boo, we died"); + } success { + pass("hooray, we lived"); + }; + +C, exported only by request, is a L helper with semantics +identical to L|Try::Tiny/finally>, but the body of the block will +only be run if the C block ran without error. + +Although almost any needed exception tests can be performed with C, +success blocks may sometimes help organize complex testing. + +=head2 dies_ok + +=head2 lives_ok + +Exported only by request, these two functions run a given block of code, and +provide TAP output indicating if it did, or did not throw an exception. +These provide an easy upgrade path for replacing existing unit tests based on +C. + +RJBS does not suggest using this except as a convenience while porting tests to +use Test::Fatal's C routine. + + use Test::More tests => 2; + use Test::Fatal qw(dies_ok lives_ok); + + dies_ok { die "I failed" } 'code that fails'; + + lives_ok { return "I'm still alive" } 'code that does not fail'; + +=head1 AUTHOR + +Ricardo Signes + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2010 by Ricardo Signes. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/Master/tlpkg/tlperl/site/lib/Test/RequiresInternet.pm b/Master/tlpkg/tlperl/site/lib/Test/RequiresInternet.pm new file mode 100644 index 00000000000..e78ca0bc6dc --- /dev/null +++ b/Master/tlpkg/tlperl/site/lib/Test/RequiresInternet.pm @@ -0,0 +1,131 @@ +use strict; +use warnings; +package Test::RequiresInternet; +$Test::RequiresInternet::VERSION = '0.05'; +# ABSTRACT: Easily test network connectivity + + +use Socket; + +sub import { + skip_all("NO_NETWORK_TESTING") if env("NO_NETWORK_TESTING"); + + my $namespace = shift; + + my $argc = scalar @_; + if ( $argc == 0 ) { + push @_, 'www.google.com', 80; + } + elsif ( $argc % 2 != 0 ) { + die "Must supply server and a port pairs. You supplied " . (join ", ", @_) . "\n"; + } + + while ( @_ ) { + my $host = shift; + my $port = shift; + + local $@; + + eval {make_socket($host, $port)}; + + if ( $@ ) { + skip_all("$@"); + } + } +} + +sub make_socket { + my ($host, $port) = @_; + + my $portnum; + if ($port =~ /\D/) { + $portnum = getservbyname($port, "tcp"); + } + else { + $portnum = $port; + } + + die "Could not find a port number for $port\n" if not $portnum; + + my $iaddr = inet_aton($host) or die "no host: $host\n"; + + my $paddr = sockaddr_in($portnum, $iaddr); + my $proto = getprotobyname("tcp"); + + socket(my $sock, PF_INET, SOCK_STREAM, $proto) or die "socket: $!\n"; + connect($sock, $paddr) or die "connect: $!\n"; + close ($sock) or die "close: $!\n"; + + 1; +} + +sub env { + exists $ENV{$_[0]} && $ENV{$_[0]} eq '1' +} + +sub skip_all { + my $reason = shift; + print "1..0 # Skipped: $reason"; + exit 0; +} + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Test::RequiresInternet - Easily test network connectivity + +=head1 VERSION + +version 0.05 + +=head1 SYNOPSIS + + use Test::More; + use Test::RequiresInternet ('www.example.com' => 80, 'foobar.io' => 25); + + # if you reach here, sockets successfully connected to hosts/ports above + plan tests => 1; + + ok(do_that_internet_thing()); + +=head1 OVERVIEW + +This module is intended to easily test network connectivity before functional +tests begin to non-local Internet resources. It does not require any modules +beyond those supplied in core Perl. + +If you do not specify a host/port pair, then the module defaults to using +C on port C<80>. + +You may optionally specify the port by its name, as in C or C. +If you do this, the test module will attempt to look up the port number +using C. + +If you do specify a host and port, they must be specified in B. It is a +fatal error to omit one or the other. + +If the environment variable C is set, then the tests +will be skipped without attempting any socket connections. + +If the sockets cannot connect to the specified hosts and ports, the exception +is caught, reported and the tests skipped. + +=head1 AUTHOR + +Mark Allen + +=head1 COPYRIGHT AND LICENSE + +This software is copyright (c) 2014 by Mark Allen. + +This is free software; you can redistribute it and/or modify it under +the same terms as the Perl 5 programming language system itself. + +=cut diff --git a/Master/tlpkg/tlperl/site/lib/Try/Tiny.pm b/Master/tlpkg/tlperl/site/lib/Try/Tiny.pm new file mode 100644 index 00000000000..476a215fe39 --- /dev/null +++ b/Master/tlpkg/tlperl/site/lib/Try/Tiny.pm @@ -0,0 +1,804 @@ +package Try::Tiny; # git description: v0.27-8-g8dc27c7 +use 5.006; +# ABSTRACT: Minimal try/catch with proper preservation of $@ + +our $VERSION = '0.28'; + +use strict; +use warnings; + +use Exporter 5.57 'import'; +our @EXPORT = our @EXPORT_OK = qw(try catch finally); + +use Carp; +$Carp::Internal{+__PACKAGE__}++; + +BEGIN { + my $su = $INC{'Sub/Util.pm'} && defined &Sub::Util::set_subname; + my $sn = $INC{'Sub/Name.pm'} && eval { Sub::Name->VERSION(0.08) }; + unless ($su || $sn) { + $su = eval { require Sub::Util; } && defined &Sub::Util::set_subname; + unless ($su) { + $sn = eval { require Sub::Name; Sub::Name->VERSION(0.08) }; + } + } + + *_subname = $su ? \&Sub::Util::set_subname + : $sn ? \&Sub::Name::subname + : sub { $_[1] }; + *_HAS_SUBNAME = ($su || $sn) ? sub(){1} : sub(){0}; +} + +my %_finally_guards; + +# Need to prototype as @ not $$ because of the way Perl evaluates the prototype. +# Keeping it at $$ means you only ever get 1 sub because we need to eval in a list +# context & not a scalar one + +sub try (&;@) { + my ( $try, @code_refs ) = @_; + + # we need to save this here, the eval block will be in scalar context due + # to $failed + my $wantarray = wantarray; + + # work around perl bug by explicitly initializing these, due to the likelyhood + # this will be used in global destruction (perl rt#119311) + my ( $catch, @finally ) = (); + + # find labeled blocks in the argument list. + # catch and finally tag the blocks by blessing a scalar reference to them. + foreach my $code_ref (@code_refs) { + + if ( ref($code_ref) eq 'Try::Tiny::Catch' ) { + croak 'A try() may not be followed by multiple catch() blocks' + if $catch; + $catch = ${$code_ref}; + } elsif ( ref($code_ref) eq 'Try::Tiny::Finally' ) { + push @finally, ${$code_ref}; + } else { + croak( + 'try() encountered an unexpected argument (' + . ( defined $code_ref ? $code_ref : 'undef' ) + . ') - perhaps a missing semi-colon before or' + ); + } + } + + # FIXME consider using local $SIG{__DIE__} to accumulate all errors. It's + # not perfect, but we could provide a list of additional errors for + # $catch->(); + + # name the blocks if we have Sub::Name installed + my $caller = caller; + _subname("${caller}::try {...} " => $try) + if _HAS_SUBNAME; + + # set up scope guards to invoke the finally blocks at the end. + # this should really be a function scope lexical variable instead of + # file scope + local but that causes issues with perls < 5.20 due to + # perl rt#119311 + local $_finally_guards{guards} = [ + map { Try::Tiny::ScopeGuard->_new($_) } + @finally + ]; + + # save the value of $@ so we can set $@ back to it in the beginning of the eval + # and restore $@ after the eval finishes + my $prev_error = $@; + + my ( @ret, $error ); + + # failed will be true if the eval dies, because 1 will not be returned + # from the eval body + my $failed = not eval { + $@ = $prev_error; + + # evaluate the try block in the correct context + if ( $wantarray ) { + @ret = $try->(); + } elsif ( defined $wantarray ) { + $ret[0] = $try->(); + } else { + $try->(); + }; + + return 1; # properly set $failed to false + }; + + # preserve the current error and reset the original value of $@ + $error = $@; + $@ = $prev_error; + + # at this point $failed contains a true value if the eval died, even if some + # destructor overwrote $@ as the eval was unwinding. + if ( $failed ) { + # pass $error to the finally blocks + push @$_, $error for @{$_finally_guards{guards}}; + + # if we got an error, invoke the catch block. + if ( $catch ) { + # This works like given($error), but is backwards compatible and + # sets $_ in the dynamic scope for the body of C<$catch> + for ($error) { + return $catch->($error); + } + + # in case when() was used without an explicit return, the C + # loop will be aborted and there's no useful return value + } + + return; + } else { + # no failure, $@ is back to what it was, everything is fine + return $wantarray ? @ret : $ret[0]; + } +} + +sub catch (&;@) { + my ( $block, @rest ) = @_; + + croak 'Useless bare catch()' unless wantarray; + + my $caller = caller; + _subname("${caller}::catch {...} " => $block) + if _HAS_SUBNAME; + return ( + bless(\$block, 'Try::Tiny::Catch'), + @rest, + ); +} + +sub finally (&;@) { + my ( $block, @rest ) = @_; + + croak 'Useless bare finally()' unless wantarray; + + my $caller = caller; + _subname("${caller}::finally {...} " => $block) + if _HAS_SUBNAME; + return ( + bless(\$block, 'Try::Tiny::Finally'), + @rest, + ); +} + +{ + package # hide from PAUSE + Try::Tiny::ScopeGuard; + + use constant UNSTABLE_DOLLARAT => ("$]" < '5.013002') ? 1 : 0; + + sub _new { + shift; + bless [ @_ ]; + } + + sub DESTROY { + my ($code, @args) = @{ $_[0] }; + + local $@ if UNSTABLE_DOLLARAT; + eval { + $code->(@args); + 1; + } or do { + warn + "Execution of finally() block $code resulted in an exception, which " + . '*CAN NOT BE PROPAGATED* due to fundamental limitations of Perl. ' + . 'Your program will continue as if this event never took place. ' + . "Original exception text follows:\n\n" + . (defined $@ ? $@ : '$@ left undefined...') + . "\n" + ; + } + } +} + +__PACKAGE__ + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Try::Tiny - Minimal try/catch with proper preservation of $@ + +=head1 VERSION + +version 0.28 + +=head1 SYNOPSIS + +You can use Try::Tiny's C and C to expect and handle exceptional +conditions, avoiding quirks in Perl and common mistakes: + + # handle errors with a catch handler + try { + die "foo"; + } catch { + warn "caught error: $_"; # not $@ + }; + +You can also use it like a standalone C to catch and ignore any error +conditions. Obviously, this is an extreme measure not to be undertaken +lightly: + + # just silence errors + try { + die "foo"; + }; + +=head1 DESCRIPTION + +This module provides bare bones C/C/C statements that are designed to +minimize common mistakes with eval blocks, and NOTHING else. + +This is unlike L which provides a nice syntax and avoids adding +another call stack layer, and supports calling C from the C block to +return from the parent subroutine. These extra features come at a cost of a few +dependencies, namely L and L which are +occasionally problematic, and the additional catch filtering uses L +type constraints which may not be desirable either. + +The main focus of this module is to provide simple and reliable error handling +for those having a hard time installing L, but who still want to +write correct C blocks without 5 lines of boilerplate each time. + +It's designed to work as correctly as possible in light of the various +pathological edge cases (see L) and to be compatible with any style +of error values (simple strings, references, objects, overloaded objects, etc). + +If the C block dies, it returns the value of the last statement executed in +the C block, if there is one. Otherwise, it returns C in scalar +context or the empty list in list context. The following examples all +assign C<"bar"> to C<$x>: + + my $x = try { die "foo" } catch { "bar" }; + my $x = try { die "foo" } || "bar"; + my $x = (try { die "foo" }) // "bar"; + + my $x = eval { die "foo" } || "bar"; + +You can add C blocks, yielding the following: + + my $x; + try { die 'foo' } finally { $x = 'bar' }; + try { die 'foo' } catch { warn "Got a die: $_" } finally { $x = 'bar' }; + +C blocks are always executed making them suitable for cleanup code +which cannot be handled using local. You can add as many C blocks to a +given C block as you like. + +Note that adding a C block without a preceding C block +suppresses any errors. This behaviour is consistent with using a standalone +C, but it is not consistent with C/C patterns found in +other programming languages, such as Java, Python, Javascript or C#. If you +learnt the C/C pattern from one of these languages, watch out for +this. + +=head1 EXPORTS + +All functions are exported by default using L. + +If you need to rename the C, C or C keyword consider using +L to get L's flexibility. + +=over 4 + +=item try (&;@) + +Takes one mandatory C subroutine, an optional C subroutine and C +subroutine. + +The mandatory subroutine is evaluated in the context of an C block. + +If no error occurred the value from the first block is returned, preserving +list/scalar context. + +If there was an error and the second subroutine was given it will be invoked +with the error in C<$_> (localized) and as that block's first and only +argument. + +C<$@> does B contain the error. Inside the C block it has the same +value it had before the C block was executed. + +Note that the error may be false, but if that happens the C block will +still be invoked. + +Once all execution is finished then the C block, if given, will execute. + +=item catch (&;@) + +Intended to be used in the second argument position of C. + +Returns a reference to the subroutine it was given but blessed as +C which allows try to decode correctly what to do +with this code reference. + + catch { ... } + +Inside the C block the caught error is stored in C<$_>, while previous +value of C<$@> is still available for use. This value may or may not be +meaningful depending on what happened before the C, but it might be a good +idea to preserve it in an error stack. + +For code that captures C<$@> when throwing new errors (i.e. +L), you'll need to do: + + local $@ = $_; + +=item finally (&;@) + + try { ... } + catch { ... } + finally { ... }; + +Or + + try { ... } + finally { ... }; + +Or even + + try { ... } + finally { ... } + catch { ... }; + +Intended to be the second or third element of C. C blocks are always +executed in the event of a successful C or if C is run. This allows +you to locate cleanup code which cannot be done via C e.g. closing a file +handle. + +When invoked, the C block is passed the error that was caught. If no +error was caught, it is passed nothing. (Note that the C block does not +localize C<$_> with the error, since unlike in a C block, there is no way +to know if C<$_ == undef> implies that there were no errors.) In other words, +the following code does just what you would expect: + + try { + die_sometimes(); + } catch { + # ...code run in case of error + } finally { + if (@_) { + print "The try block died with: @_\n"; + } else { + print "The try block ran without error.\n"; + } + }; + +B block>. C will +not do anything about handling possible errors coming from code located in these +blocks. + +Furthermore B blocks are not trappable and are unable +to influence the execution of your program>. This is due to limitation of +C-based scope guards, which C is implemented on top of. This +may change in a future version of Try::Tiny. + +In the same way C blesses the code reference this subroutine does the same +except it bless them as C. + +=back + +=head1 BACKGROUND + +There are a number of issues with C. + +=head2 Clobbering $@ + +When you run an C block and it succeeds, C<$@> will be cleared, potentially +clobbering an error that is currently being caught. + +This causes action at a distance, clearing previous errors your caller may have +not yet handled. + +C<$@> must be properly localized before invoking C in order to avoid this +issue. + +More specifically, C<$@> is clobbered at the beginning of the C, which +also makes it impossible to capture the previous error before you die (for +instance when making exception objects with error stacks). + +For this reason C will actually set C<$@> to its previous value (the one +available before entering the C block) in the beginning of the C +block. + +=head2 Localizing $@ silently masks errors + +Inside an C block, C behaves sort of like: + + sub die { + $@ = $_[0]; + return_undef_from_eval(); + } + +This means that if you were polite and localized C<$@> you can't die in that +scope, or your error will be discarded (printing "Something's wrong" instead). + +The workaround is very ugly: + + my $error = do { + local $@; + eval { ... }; + $@; + }; + + ... + die $error; + +=head2 $@ might not be a true value + +This code is wrong: + + if ( $@ ) { + ... + } + +because due to the previous caveats it may have been unset. + +C<$@> could also be an overloaded error object that evaluates to false, but +that's asking for trouble anyway. + +The classic failure mode is: + + sub Object::DESTROY { + eval { ... } + } + + eval { + my $obj = Object->new; + + die "foo"; + }; + + if ( $@ ) { + + } + +In this case since C is not localizing C<$@> but still uses +C, it will set C<$@> to C<"">. + +The destructor is called when the stack is unwound, after C sets C<$@> to +C<"foo at Foo.pm line 42\n">, so by the time C is evaluated it has +been cleared by C in the destructor. + +The workaround for this is even uglier than the previous ones. Even though we +can't save the value of C<$@> from code that doesn't localize, we can at least +be sure the C was aborted due to an error: + + my $failed = not eval { + ... + + return 1; + }; + +This is because an C that caught a C will always return a false +value. + +=head1 SHINY SYNTAX + +Using Perl 5.10 you can use L. + +=for stopwords topicalizer + +The C block is invoked in a topicalizer context (like a C block), +but note that you can't return a useful value from C using the C +blocks without an explicit C. + +This is somewhat similar to Perl 6's C blocks. You can use it to +concisely match errors: + + try { + require Foo; + } catch { + when (/^Can't locate .*?\.pm in \@INC/) { } # ignore + default { die $_ } + }; + +=head1 CAVEATS + +=over 4 + +=item * + +C<@_> is not available within the C block, so you need to copy your +argument list. In case you want to work with argument values directly via C<@_> +aliasing (i.e. allow C<$_[1] = "foo">), you need to pass C<@_> by reference: + + sub foo { + my ( $self, @args ) = @_; + try { $self->bar(@args) } + } + +or + + sub bar_in_place { + my $self = shift; + my $args = \@_; + try { $_ = $self->bar($_) for @$args } + } + +=item * + +C returns from the C block, not from the parent sub (note that +this is also how C works, but not how L works): + + sub parent_sub { + try { + die; + } + catch { + return; + }; + + say "this text WILL be displayed, even though an exception is thrown"; + } + +Instead, you should capture the return value: + + sub parent_sub { + my $success = try { + die; + 1; + }; + return unless $success; + + say "This text WILL NEVER appear!"; + } + # OR + sub parent_sub_with_catch { + my $success = try { + die; + 1; + } + catch { + # do something with $_ + return undef; #see note + }; + return unless $success; + + say "This text WILL NEVER appear!"; + } + +Note that if you have a C block, it must return C for this to work, +since if a C block exists, its return value is returned in place of C +when an exception is thrown. + +=item * + +C introduces another caller stack frame. L is not used. L +will not report this when using full stack traces, though, because +C<%Carp::Internal> is used. This lack of magic is considered a feature. + +=for stopwords unhygienically + +=item * + +The value of C<$_> in the C block is not guaranteed to be the value of +the exception thrown (C<$@>) in the C block. There is no safe way to +ensure this, since C may be used unhygienically in destructors. The only +guarantee is that the C will be called if an exception is thrown. + +=item * + +The return value of the C block is not ignored, so if testing the result +of the expression for truth on success, be sure to return a false value from +the C block: + + my $obj = try { + MightFail->new; + } catch { + ... + + return; # avoid returning a true value; + }; + + return unless $obj; + +=item * + +C<$SIG{__DIE__}> is still in effect. + +Though it can be argued that C<$SIG{__DIE__}> should be disabled inside of +C blocks, since it isn't people have grown to rely on it. Therefore in +the interests of compatibility, C does not disable C<$SIG{__DIE__}> for +the scope of the error throwing code. + +=item * + +Lexical C<$_> may override the one set by C. + +For example Perl 5.10's C form uses a lexical C<$_>, creating some +confusing behavior: + + given ($foo) { + when (...) { + try { + ... + } catch { + warn $_; # will print $foo, not the error + warn $_[0]; # instead, get the error like this + } + } + } + +Note that this behavior was changed once again in L. +However, since the entirety of lexical C<$_> is now L, it +is unclear whether the new version 18 behavior is final. + +=back + +=head1 SEE ALSO + +=over 4 + +=item L + +Much more feature complete, more convenient semantics, but at the cost of +implementation complexity. + +=item L + +Automatic error throwing for builtin functions and more. Also designed to +work well with C/C. + +=item L + +A lightweight role for rolling your own exception classes. + +=item L + +Exception object implementation with a C statement. Does not localize +C<$@>. + +=item L + +Provides a C statement, but properly calling C is your +responsibility. + +The C keyword pushes C<$@> onto an error stack, avoiding some of the +issues with C<$@>, but you still need to localize to prevent clobbering. + +=back + +=head1 LIGHTNING TALK + +I gave a lightning talk about this module, you can see the slides (Firefox +only): + +L + +Or read the source: + +L + +=head1 SUPPORT + +Bugs may be submitted through L +(or L). + +=head1 AUTHORS + +=over 4 + +=item * + +יובל קוג'מן (Yuval Kogman) + +=item * + +Jesse Luehrs + +=back + +=head1 CONTRIBUTORS + +=for stopwords Karen Etheridge Peter Rabbitson Ricardo Signes Mark Fowler Graham Knop Lukas Mai Dagfinn Ilmari Mannsåker Paul Howarth Rudolf Leermakers anaxagoras awalker chromatic Alex cm-perl Andrew Yates David Lowe Glenn Hans Dieter Pearcey Jonathan Yu Marc Mims Stosberg Pali + +=over 4 + +=item * + +Karen Etheridge + +=item * + +Peter Rabbitson + +=item * + +Ricardo Signes + +=item * + +Mark Fowler + +=item * + +Graham Knop + +=item * + +Lukas Mai + +=item * + +Dagfinn Ilmari Mannsåker + +=item * + +Paul Howarth + +=item * + +Rudolf Leermakers + +=item * + +anaxagoras + +=item * + +awalker + +=item * + +chromatic + +=item * + +Alex + +=item * + +cm-perl + +=item * + +Andrew Yates + +=item * + +David Lowe + +=item * + +Glenn Fowler + +=item * + +Hans Dieter Pearcey + +=item * + +Jonathan Yu + +=item * + +Marc Mims + +=item * + +Mark Stosberg + +=item * + +Pali + +=back + +=head1 COPYRIGHT AND LICENCE + +This software is Copyright (c) 2009 by יובל קוג'מן (Yuval Kogman). + +This is free software, licensed under: + + The MIT (X11) License + +=cut diff --git a/Master/tlpkg/tlperl/site/lib/auto/Digest/SHA1/SHA1.dll b/Master/tlpkg/tlperl/site/lib/auto/Digest/SHA1/SHA1.dll index e184096ca87..86090539524 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Digest/SHA1/SHA1.dll and b/Master/tlpkg/tlperl/site/lib/auto/Digest/SHA1/SHA1.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/HTML/Parser/Parser.dll b/Master/tlpkg/tlperl/site/lib/auto/HTML/Parser/Parser.dll index 5e04188df29..4cc97f0777f 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/HTML/Parser/Parser.dll and b/Master/tlpkg/tlperl/site/lib/auto/HTML/Parser/Parser.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/LWP/.packlist b/Master/tlpkg/tlperl/site/lib/auto/LWP/.packlist deleted file mode 100644 index 5e930937248..00000000000 --- a/Master/tlpkg/tlperl/site/lib/auto/LWP/.packlist +++ /dev/null @@ -1,33 +0,0 @@ -C:\tlperl\bin\lwp-download -C:\tlperl\bin\lwp-download.bat -C:\tlperl\bin\lwp-dump -C:\tlperl\bin\lwp-dump.bat -C:\tlperl\bin\lwp-mirror -C:\tlperl\bin\lwp-mirror.bat -C:\tlperl\bin\lwp-request -C:\tlperl\bin\lwp-request.bat -C:\tlperl\site\lib\LWP.pm -C:\tlperl\site\lib\LWP\Authen\Basic.pm -C:\tlperl\site\lib\LWP\Authen\Digest.pm -C:\tlperl\site\lib\LWP\Authen\Ntlm.pm -C:\tlperl\site\lib\LWP\ConnCache.pm -C:\tlperl\site\lib\LWP\Debug.pm -C:\tlperl\site\lib\LWP\DebugFile.pm -C:\tlperl\site\lib\LWP\MemberMixin.pm -C:\tlperl\site\lib\LWP\Protocol.pm -C:\tlperl\site\lib\LWP\Protocol\GHTTP.pm -C:\tlperl\site\lib\LWP\Protocol\cpan.pm -C:\tlperl\site\lib\LWP\Protocol\data.pm -C:\tlperl\site\lib\LWP\Protocol\file.pm -C:\tlperl\site\lib\LWP\Protocol\ftp.pm -C:\tlperl\site\lib\LWP\Protocol\gopher.pm -C:\tlperl\site\lib\LWP\Protocol\http.pm -C:\tlperl\site\lib\LWP\Protocol\loopback.pm -C:\tlperl\site\lib\LWP\Protocol\mailto.pm -C:\tlperl\site\lib\LWP\Protocol\nntp.pm -C:\tlperl\site\lib\LWP\Protocol\nogo.pm -C:\tlperl\site\lib\LWP\RobotUA.pm -C:\tlperl\site\lib\LWP\Simple.pm -C:\tlperl\site\lib\LWP\UserAgent.pm -C:\tlperl\site\lib\lwpcook.pod -C:\tlperl\site\lib\lwptut.pod diff --git a/Master/tlpkg/tlperl/site/lib/auto/Math/Int64/Int64.dll b/Master/tlpkg/tlperl/site/lib/auto/Math/Int64/Int64.dll index 48cb12c173a..ac97081b198 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Math/Int64/Int64.dll and b/Master/tlpkg/tlperl/site/lib/auto/Math/Int64/Int64.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Socket/Socket.dll b/Master/tlpkg/tlperl/site/lib/auto/Socket/Socket.dll index 1a1a11cbb69..960de7a1969 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Socket/Socket.dll and b/Master/tlpkg/tlperl/site/lib/auto/Socket/Socket.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Test/Fatal/.packlist b/Master/tlpkg/tlperl/site/lib/auto/Test/Fatal/.packlist new file mode 100644 index 00000000000..f8b34dfe0f7 --- /dev/null +++ b/Master/tlpkg/tlperl/site/lib/auto/Test/Fatal/.packlist @@ -0,0 +1 @@ +C:\tlperl\site\lib\Test\Fatal.pm diff --git a/Master/tlpkg/tlperl/site/lib/auto/Test/RequiresInternet/.packlist b/Master/tlpkg/tlperl/site/lib/auto/Test/RequiresInternet/.packlist new file mode 100644 index 00000000000..2236c52f855 --- /dev/null +++ b/Master/tlpkg/tlperl/site/lib/auto/Test/RequiresInternet/.packlist @@ -0,0 +1 @@ +C:\tlperl\site\lib\Test\RequiresInternet.pm diff --git a/Master/tlpkg/tlperl/site/lib/auto/Tk/Canvas/Canvas.dll b/Master/tlpkg/tlperl/site/lib/auto/Tk/Canvas/Canvas.dll index 6446afced36..aaea038696e 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Tk/Canvas/Canvas.dll and b/Master/tlpkg/tlperl/site/lib/auto/Tk/Canvas/Canvas.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Tk/Compound/Compound.dll b/Master/tlpkg/tlperl/site/lib/auto/Tk/Compound/Compound.dll index c64b368860a..a6999af8459 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Tk/Compound/Compound.dll and b/Master/tlpkg/tlperl/site/lib/auto/Tk/Compound/Compound.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Tk/DragDrop/Win32Site/Win32Site.dll b/Master/tlpkg/tlperl/site/lib/auto/Tk/DragDrop/Win32Site/Win32Site.dll index 31ee1df07e6..525b9ca16ad 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Tk/DragDrop/Win32Site/Win32Site.dll and b/Master/tlpkg/tlperl/site/lib/auto/Tk/DragDrop/Win32Site/Win32Site.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Tk/Entry/Entry.dll b/Master/tlpkg/tlperl/site/lib/auto/Tk/Entry/Entry.dll index 9b7b7f412b7..a0a92119300 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Tk/Entry/Entry.dll and b/Master/tlpkg/tlperl/site/lib/auto/Tk/Entry/Entry.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Tk/Event/Event.dll b/Master/tlpkg/tlperl/site/lib/auto/Tk/Event/Event.dll index 7d0927e62e5..61b4c43543d 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Tk/Event/Event.dll and b/Master/tlpkg/tlperl/site/lib/auto/Tk/Event/Event.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Tk/HList/HList.dll b/Master/tlpkg/tlperl/site/lib/auto/Tk/HList/HList.dll index 6bd49586ac3..3887b0688f7 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Tk/HList/HList.dll and b/Master/tlpkg/tlperl/site/lib/auto/Tk/HList/HList.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Tk/IO/IO.dll b/Master/tlpkg/tlperl/site/lib/auto/Tk/IO/IO.dll index b0e171a0ceb..c99e35fa409 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Tk/IO/IO.dll and b/Master/tlpkg/tlperl/site/lib/auto/Tk/IO/IO.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Tk/JPEG/JPEG.dll b/Master/tlpkg/tlperl/site/lib/auto/Tk/JPEG/JPEG.dll index f6e70059bc5..47462a79290 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Tk/JPEG/JPEG.dll and b/Master/tlpkg/tlperl/site/lib/auto/Tk/JPEG/JPEG.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Tk/Listbox/Listbox.dll b/Master/tlpkg/tlperl/site/lib/auto/Tk/Listbox/Listbox.dll index 00235e724d0..a8650b82e74 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Tk/Listbox/Listbox.dll and b/Master/tlpkg/tlperl/site/lib/auto/Tk/Listbox/Listbox.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Tk/Menubutton/Menubutton.dll b/Master/tlpkg/tlperl/site/lib/auto/Tk/Menubutton/Menubutton.dll index 04febc64ef0..859bcf7837d 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Tk/Menubutton/Menubutton.dll and b/Master/tlpkg/tlperl/site/lib/auto/Tk/Menubutton/Menubutton.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Tk/NBFrame/NBFrame.dll b/Master/tlpkg/tlperl/site/lib/auto/Tk/NBFrame/NBFrame.dll index 2e1270e7126..826dc1c5ee9 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Tk/NBFrame/NBFrame.dll and b/Master/tlpkg/tlperl/site/lib/auto/Tk/NBFrame/NBFrame.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Tk/PNG/PNG.dll b/Master/tlpkg/tlperl/site/lib/auto/Tk/PNG/PNG.dll index 9c9d0d4cfc1..d3e627056bc 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Tk/PNG/PNG.dll and b/Master/tlpkg/tlperl/site/lib/auto/Tk/PNG/PNG.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Tk/Pixmap/Pixmap.dll b/Master/tlpkg/tlperl/site/lib/auto/Tk/Pixmap/Pixmap.dll index 89f6d56a0b1..ca6e720a39b 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Tk/Pixmap/Pixmap.dll and b/Master/tlpkg/tlperl/site/lib/auto/Tk/Pixmap/Pixmap.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Tk/Scale/Scale.dll b/Master/tlpkg/tlperl/site/lib/auto/Tk/Scale/Scale.dll index 06d39386842..dceb08656e9 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Tk/Scale/Scale.dll and b/Master/tlpkg/tlperl/site/lib/auto/Tk/Scale/Scale.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Tk/Scrollbar/Scrollbar.dll b/Master/tlpkg/tlperl/site/lib/auto/Tk/Scrollbar/Scrollbar.dll index ace8473c081..6581166a0d2 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Tk/Scrollbar/Scrollbar.dll and b/Master/tlpkg/tlperl/site/lib/auto/Tk/Scrollbar/Scrollbar.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Tk/TList/TList.dll b/Master/tlpkg/tlperl/site/lib/auto/Tk/TList/TList.dll index c53136072bf..74a7db0aec0 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Tk/TList/TList.dll and b/Master/tlpkg/tlperl/site/lib/auto/Tk/TList/TList.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Tk/Text/Text.dll b/Master/tlpkg/tlperl/site/lib/auto/Tk/Text/Text.dll index 272aa40da1e..db74843f80d 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Tk/Text/Text.dll and b/Master/tlpkg/tlperl/site/lib/auto/Tk/Text/Text.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Tk/TixGrid/TixGrid.dll b/Master/tlpkg/tlperl/site/lib/auto/Tk/TixGrid/TixGrid.dll index 16f6b45250d..68783a2bc86 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Tk/TixGrid/TixGrid.dll and b/Master/tlpkg/tlperl/site/lib/auto/Tk/TixGrid/TixGrid.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Tk/Tk.dll b/Master/tlpkg/tlperl/site/lib/auto/Tk/Tk.dll index 9471c2cb7fa..c1fc88120c5 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Tk/Tk.dll and b/Master/tlpkg/tlperl/site/lib/auto/Tk/Tk.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Tk/X/X.dll b/Master/tlpkg/tlperl/site/lib/auto/Tk/X/X.dll index cb3865194c8..5efc1ed7168 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Tk/X/X.dll and b/Master/tlpkg/tlperl/site/lib/auto/Tk/X/X.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Tk/Xlib/Xlib.dll b/Master/tlpkg/tlperl/site/lib/auto/Tk/Xlib/Xlib.dll index 5326436a0ea..f6753ab9b41 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Tk/Xlib/Xlib.dll and b/Master/tlpkg/tlperl/site/lib/auto/Tk/Xlib/Xlib.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Try/Tiny/.packlist b/Master/tlpkg/tlperl/site/lib/auto/Try/Tiny/.packlist new file mode 100644 index 00000000000..44c33603fa6 --- /dev/null +++ b/Master/tlpkg/tlperl/site/lib/auto/Try/Tiny/.packlist @@ -0,0 +1 @@ +C:\tlperl\site\lib\Try\Tiny.pm diff --git a/Master/tlpkg/tlperl/site/lib/auto/Win32/API/API.dll b/Master/tlpkg/tlperl/site/lib/auto/Win32/API/API.dll index d1033369f81..1da8a27ac20 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Win32/API/API.dll and b/Master/tlpkg/tlperl/site/lib/auto/Win32/API/API.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Win32/API/Callback/Callback.dll b/Master/tlpkg/tlperl/site/lib/auto/Win32/API/Callback/Callback.dll index 404cd0308eb..2d50bfa9573 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Win32/API/Callback/Callback.dll and b/Master/tlpkg/tlperl/site/lib/auto/Win32/API/Callback/Callback.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Win32/Console/Console.dll b/Master/tlpkg/tlperl/site/lib/auto/Win32/Console/Console.dll index 1493cffda23..1eb79855d63 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Win32/Console/Console.dll and b/Master/tlpkg/tlperl/site/lib/auto/Win32/Console/Console.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Win32/OLE/OLE.dll b/Master/tlpkg/tlperl/site/lib/auto/Win32/OLE/OLE.dll index ee0afd77bed..9f4ee98c466 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Win32/OLE/OLE.dll and b/Master/tlpkg/tlperl/site/lib/auto/Win32/OLE/OLE.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Win32/Process/Process.dll b/Master/tlpkg/tlperl/site/lib/auto/Win32/Process/Process.dll index 68dfd660838..7c4e92a6725 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Win32/Process/Process.dll and b/Master/tlpkg/tlperl/site/lib/auto/Win32/Process/Process.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Win32/Shortcut/Shortcut.dll b/Master/tlpkg/tlperl/site/lib/auto/Win32/Shortcut/Shortcut.dll index 817aea2599a..5bb6d509e87 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Win32/Shortcut/Shortcut.dll and b/Master/tlpkg/tlperl/site/lib/auto/Win32/Shortcut/Shortcut.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/Win32API/Registry/Registry.dll b/Master/tlpkg/tlperl/site/lib/auto/Win32API/Registry/Registry.dll index a5de61dcfae..a460a26c22f 100755 Binary files a/Master/tlpkg/tlperl/site/lib/auto/Win32API/Registry/Registry.dll and b/Master/tlpkg/tlperl/site/lib/auto/Win32API/Registry/Registry.dll differ diff --git a/Master/tlpkg/tlperl/site/lib/auto/libwww/perl/.packlist b/Master/tlpkg/tlperl/site/lib/auto/libwww/perl/.packlist new file mode 100644 index 00000000000..156f09f720f --- /dev/null +++ b/Master/tlpkg/tlperl/site/lib/auto/libwww/perl/.packlist @@ -0,0 +1,33 @@ +C:\tlperl\bin\lwp-download +C:\tlperl\bin\lwp-download.bat +C:\tlperl\bin\lwp-dump +C:\tlperl\bin\lwp-dump.bat +C:\tlperl\bin\lwp-mirror +C:\tlperl\bin\lwp-mirror.bat +C:\tlperl\bin\lwp-request +C:\tlperl\bin\lwp-request.bat +C:\tlperl\site\lib\LWP.pm +C:\tlperl\site\lib\LWP\Authen\Basic.pm +C:\tlperl\site\lib\LWP\Authen\Digest.pm +C:\tlperl\site\lib\LWP\Authen\Ntlm.pm +C:\tlperl\site\lib\LWP\ConnCache.pm +C:\tlperl\site\lib\LWP\Debug.pm +C:\tlperl\site\lib\LWP\DebugFile.pm +C:\tlperl\site\lib\LWP\Debug\TraceHTTP.pm +C:\tlperl\site\lib\LWP\MemberMixin.pm +C:\tlperl\site\lib\LWP\Protocol.pm +C:\tlperl\site\lib\LWP\Protocol\cpan.pm +C:\tlperl\site\lib\LWP\Protocol\data.pm +C:\tlperl\site\lib\LWP\Protocol\file.pm +C:\tlperl\site\lib\LWP\Protocol\ftp.pm +C:\tlperl\site\lib\LWP\Protocol\gopher.pm +C:\tlperl\site\lib\LWP\Protocol\http.pm +C:\tlperl\site\lib\LWP\Protocol\loopback.pm +C:\tlperl\site\lib\LWP\Protocol\mailto.pm +C:\tlperl\site\lib\LWP\Protocol\nntp.pm +C:\tlperl\site\lib\LWP\Protocol\nogo.pm +C:\tlperl\site\lib\LWP\RobotUA.pm +C:\tlperl\site\lib\LWP\Simple.pm +C:\tlperl\site\lib\LWP\UserAgent.pm +C:\tlperl\site\lib\libwww\lwpcook.pod +C:\tlperl\site\lib\libwww\lwptut.pod diff --git a/Master/tlpkg/tlperl/site/lib/libwww/lwpcook.pod b/Master/tlpkg/tlperl/site/lib/libwww/lwpcook.pod new file mode 100644 index 00000000000..43af716db06 --- /dev/null +++ b/Master/tlpkg/tlperl/site/lib/libwww/lwpcook.pod @@ -0,0 +1,308 @@ +=head1 NAME + +lwpcook - The libwww-perl cookbook + +=head1 DESCRIPTION + +This document contain some examples that show typical usage of the +libwww-perl library. You should consult the documentation for the +individual modules for more detail. + +All examples should be runnable programs. You can, in most cases, test +the code sections by piping the program text directly to perl. + + + +=head1 GET + +It is very easy to use this library to just fetch documents from the +net. The LWP::Simple module provides the get() function that return +the document specified by its URL argument: + + use LWP::Simple; + $doc = get 'http://search.cpan.org/dist/libwww-perl/'; + +or, as a perl one-liner using the getprint() function: + + perl -MLWP::Simple -e 'getprint "http://search.cpan.org/dist/libwww-perl/"' + +or, how about fetching the latest perl by running this command: + + perl -MLWP::Simple -e ' + getstore "ftp://ftp.sunet.se/pub/lang/perl/CPAN/src/latest.tar.gz", + "perl.tar.gz"' + +You will probably first want to find a CPAN site closer to you by +running something like the following command: + + perl -MLWP::Simple -e 'getprint "http://www.cpan.org/SITES.html"' + +Enough of this simple stuff! The LWP object oriented interface gives +you more control over the request sent to the server. Using this +interface you have full control over headers sent and how you want to +handle the response returned. + + use LWP::UserAgent; + $ua = LWP::UserAgent->new; + $ua->agent("$0/0.1 " . $ua->agent); + # $ua->agent("Mozilla/8.0") # pretend we are very capable browser + + $req = HTTP::Request->new( + GET => 'http://search.cpan.org/dist/libwww-perl/'); + $req->header('Accept' => 'text/html'); + + # send request + $res = $ua->request($req); + + # check the outcome + if ($res->is_success) { + print $res->decoded_content; + } + else { + print "Error: " . $res->status_line . "\n"; + } + +The lwp-request program (alias GET) that is distributed with the +library can also be used to fetch documents from WWW servers. + + + +=head1 HEAD + +If you just want to check if a document is present (i.e. the URL is +valid) try to run code that looks like this: + + use LWP::Simple; + + if (head($url)) { + # ok document exists + } + +The head() function really returns a list of meta-information about +the document. The first three values of the list returned are the +document type, the size of the document, and the age of the document. + +More control over the request or access to all header values returned +require that you use the object oriented interface described for GET +above. Just s/GET/HEAD/g. + + +=head1 POST + +There is no simple procedural interface for posting data to a WWW server. You +must use the object oriented interface for this. The most common POST +operation is to access a WWW form application: + + use LWP::UserAgent; + $ua = LWP::UserAgent->new; + + my $req = HTTP::Request->new( + POST => 'http://rt.cpan.org/Public/Dist/Display.html'); + $req->content_type('application/x-www-form-urlencoded'); + $req->content('Status=Active&Name=libwww-perl'); + + my $res = $ua->request($req); + print $res->as_string; + +Lazy people use the HTTP::Request::Common module to set up a suitable +POST request message (it handles all the escaping issues) and has a +suitable default for the content_type: + + use HTTP::Request::Common qw(POST); + use LWP::UserAgent; + $ua = LWP::UserAgent->new; + + my $req = POST 'http://rt.cpan.org/Public/Dist/Display.html', + [ Status => 'Active', Name => 'libwww-perl' ]; + + print $ua->request($req)->as_string; + +The lwp-request program (alias POST) that is distributed with the +library can also be used for posting data. + + + +=head1 PROXIES + +Some sites use proxies to go through fire wall machines, or just as +cache in order to improve performance. Proxies can also be used for +accessing resources through protocols not supported directly (or +supported badly :-) by the libwww-perl library. + +You should initialize your proxy setting before you start sending +requests: + + use LWP::UserAgent; + $ua = LWP::UserAgent->new; + $ua->env_proxy; # initialize from environment variables + # or + $ua->proxy(ftp => 'http://proxy.myorg.com'); + $ua->proxy(wais => 'http://proxy.myorg.com'); + $ua->no_proxy(qw(no se fi)); + + my $req = HTTP::Request->new(GET => 'wais://xxx.com/'); + print $ua->request($req)->as_string; + +The LWP::Simple interface will call env_proxy() for you automatically. +Applications that use the $ua->env_proxy() method will normally not +use the $ua->proxy() and $ua->no_proxy() methods. + +Some proxies also require that you send it a username/password in +order to let requests through. You should be able to add the +required header, with something like this: + + use LWP::UserAgent; + + $ua = LWP::UserAgent->new; + $ua->proxy(['http', 'ftp'] => 'http://username:password@proxy.myorg.com'); + + $req = HTTP::Request->new('GET',"http://www.perl.com"); + + $res = $ua->request($req); + print $res->decoded_content if $res->is_success; + +Replace C, C and +C with something suitable for your site. + + +=head1 ACCESS TO PROTECTED DOCUMENTS + +Documents protected by basic authorization can easily be accessed +like this: + + use LWP::UserAgent; + $ua = LWP::UserAgent->new; + $req = HTTP::Request->new(GET => 'http://www.linpro.no/secret/'); + $req->authorization_basic('aas', 'mypassword'); + print $ua->request($req)->as_string; + +The other alternative is to provide a subclass of I that +overrides the get_basic_credentials() method. Study the I +program for an example of this. + + +=head1 COOKIES + +Some sites like to play games with cookies. By default LWP ignores +cookies provided by the servers it visits. LWP will collect cookies +and respond to cookie requests if you set up a cookie jar. + + use LWP::UserAgent; + use HTTP::CookieJar::LWP; + + $ua = LWP::UserAgent->new( + cookie_jar => HTTP::CookieJar::LWP->new, + ); + + # and then send requests just as you used to do + $res = $ua->request(HTTP::Request->new(GET => "http://no.yahoo.com/")); + print $res->status_line, "\n"; + +=head1 HTTPS + +URLs with https scheme are accessed in exactly the same way as with +http scheme, provided that an SSL interface module for LWP has been +properly installed (see the F file found in the +libwww-perl distribution for more details). If no SSL interface is +installed for LWP to use, then you will get "501 Protocol scheme +'https' is not supported" errors when accessing such URLs. + +Here's an example of fetching and printing a WWW page using SSL: + + use LWP::UserAgent; + + my $ua = LWP::UserAgent->new; + my $req = HTTP::Request->new(GET => 'https://www.helsinki.fi/'); + my $res = $ua->request($req); + if ($res->is_success) { + print $res->as_string; + } + else { + print "Failed: ", $res->status_line, "\n"; + } + +=head1 MIRRORING + +If you want to mirror documents from a WWW server, then try to run +code similar to this at regular intervals: + + use LWP::Simple; + + %mirrors = ( + 'http://www.sn.no/' => 'sn.html', + 'http://www.perl.com/' => 'perl.html', + 'http://search.cpan.org/distlibwww-perl/' => 'lwp.html', + 'gopher://gopher.sn.no/' => 'gopher.html', + ); + + while (($url, $localfile) = each(%mirrors)) { + mirror($url, $localfile); + } + +Or, as a perl one-liner: + + perl -MLWP::Simple -e 'mirror("http://www.perl.com/", "perl.html")'; + +The document will not be transferred unless it has been updated. + + + +=head1 LARGE DOCUMENTS + +If the document you want to fetch is too large to be kept in memory, +then you have two alternatives. You can instruct the library to write +the document content to a file (second $ua->request() argument is a file +name): + + use LWP::UserAgent; + $ua = LWP::UserAgent->new; + + my $req = HTTP::Request->new(GET => + 'http://www.cpan.org/authors/Gisle_Aas/libwww-perl-6.02.tar.gz'); + $res = $ua->request($req, "libwww-perl.tar.gz"); + if ($res->is_success) { + print "ok\n"; + } + else { + print $res->status_line, "\n"; + } + + +Or you can process the document as it arrives (second $ua->request() +argument is a code reference): + + use LWP::UserAgent; + $ua = LWP::UserAgent->new; + $URL = 'ftp://ftp.unit.no/pub/rfc/rfc-index.txt'; + + my $expected_length; + my $bytes_received = 0; + my $res = + $ua->request(HTTP::Request->new(GET => $URL), + sub { + my($chunk, $res) = @_; + $bytes_received += length($chunk); + unless (defined $expected_length) { + $expected_length = $res->content_length || 0; + } + if ($expected_length) { + printf STDERR "%d%% - ", + 100 * $bytes_received / $expected_length; + } + print STDERR "$bytes_received bytes received\n"; + + # XXX Should really do something with the chunk itself + # print $chunk; + }); + print $res->status_line, "\n"; + + + +=head1 COPYRIGHT + +Copyright 1996-2001, Gisle Aas + +This library is free software; you can redistribute it and/or +modify it under the same terms as Perl itself. + + diff --git a/Master/tlpkg/tlperl/site/lib/libwww/lwptut.pod b/Master/tlpkg/tlperl/site/lib/libwww/lwptut.pod new file mode 100644 index 00000000000..f9f98a0f159 --- /dev/null +++ b/Master/tlpkg/tlperl/site/lib/libwww/lwptut.pod @@ -0,0 +1,820 @@ +=head1 NAME + +lwptut -- An LWP Tutorial + +=head1 DESCRIPTION + +LWP (short for "Library for WWW in Perl") is a very popular group of +Perl modules for accessing data on the Web. Like most Perl +module-distributions, each of LWP's component modules comes with +documentation that is a complete reference to its interface. However, +there are so many modules in LWP that it's hard to know where to start +looking for information on how to do even the simplest most common +things. + +Really introducing you to using LWP would require a whole book -- a book +that just happens to exist, called I. But this article +should give you a taste of how you can go about some common tasks with +LWP. + + +=head2 Getting documents with LWP::Simple + +If you just want to get what's at a particular URL, the simplest way +to do it is LWP::Simple's functions. + +In a Perl program, you can call its C function. It will try +getting that URL's content. If it works, then it'll return the +content; but if there's some error, it'll return undef. + + my $url = 'http://www.npr.org/programs/fa/?todayDate=current'; + # Just an example: the URL for the most recent /Fresh Air/ show + + use LWP::Simple; + my $content = get $url; + die "Couldn't get $url" unless defined $content; + + # Then go do things with $content, like this: + + if($content =~ m/jazz/i) { + print "They're talking about jazz today on Fresh Air!\n"; + } + else { + print "Fresh Air is apparently jazzless today.\n"; + } + +The handiest variant on C is C, which is useful in Perl +one-liners. If it can get the page whose URL you provide, it sends it +to STDOUT; otherwise it complains to STDERR. + + % perl -MLWP::Simple -e "getprint 'http://www.cpan.org/RECENT'" + +That is the URL of a plain text file that lists new files in CPAN in +the past two weeks. You can easily make it part of a tidy little +shell command, like this one that mails you the list of new +C modules: + + % perl -MLWP::Simple -e "getprint 'http://www.cpan.org/RECENT'" \ + | grep "/by-module/Acme" | mail -s "New Acme modules! Joy!" $USER + +There are other useful functions in LWP::Simple, including one function +for running a HEAD request on a URL (useful for checking links, or +getting the last-revised time of a URL), and two functions for +saving/mirroring a URL to a local file. See L for the full details, or chapter 2 of I for more examples. + + + +=for comment + ########################################################################## + + + +=head2 The Basics of the LWP Class Model + +LWP::Simple's functions are handy for simple cases, but its functions +don't support cookies or authorization, don't support setting header +lines in the HTTP request, generally don't support reading header lines +in the HTTP response (notably the full HTTP error message, in case of an +error). To get at all those features, you'll have to use the full LWP +class model. + +While LWP consists of dozens of classes, the main two that you have to +understand are L and L. LWP::UserAgent +is a class for "virtual browsers" which you use for performing requests, +and L is a class for the responses (or error messages) +that you get back from those requests. + +The basic idiom is C<< $response = $browser->get($url) >>, or more fully +illustrated: + + # Early in your program: + + use LWP 5.64; # Loads all important LWP classes, and makes + # sure your version is reasonably recent. + + my $browser = LWP::UserAgent->new; + + ... + + # Then later, whenever you need to make a get request: + my $url = 'http://www.npr.org/programs/fa/?todayDate=current'; + + my $response = $browser->get( $url ); + die "Can't get $url -- ", $response->status_line + unless $response->is_success; + + die "Hey, I was expecting HTML, not ", $response->content_type + unless $response->content_type eq 'text/html'; + # or whatever content-type you're equipped to deal with + + # Otherwise, process the content somehow: + + if($response->decoded_content =~ m/jazz/i) { + print "They're talking about jazz today on Fresh Air!\n"; + } + else { + print "Fresh Air is apparently jazzless today.\n"; + } + +There are two objects involved: C<$browser>, which holds an object of +class LWP::UserAgent, and then the C<$response> object, which is of +class HTTP::Response. You really need only one browser object per +program; but every time you make a request, you get back a new +HTTP::Response object, which will have some interesting attributes: + +=over + +=item * + +A status code indicating +success or failure +(which you can test with C<< $response->is_success >>). + +=item * + +An HTTP status +line that is hopefully informative if there's failure (which you can +see with C<< $response->status_line >>, +returning something like "404 Not Found"). + +=item * + +A MIME content-type like "text/html", "image/gif", +"application/xml", etc., which you can see with +C<< $response->content_type >> + +=item * + +The actual content of the response, in C<< $response->decoded_content >>. +If the response is HTML, that's where the HTML source will be; if +it's a GIF, then C<< $response->decoded_content >> will be the binary +GIF data. + +=item * + +And dozens of other convenient and more specific methods that are +documented in the docs for L, and its superclasses +L and L. + +=back + + + +=for comment + ########################################################################## + + + +=head2 Adding Other HTTP Request Headers + +The most commonly used syntax for requests is C<< $response = +$browser->get($url) >>, but in truth, you can add extra HTTP header +lines to the request by adding a list of key-value pairs after the URL, +like so: + + $response = $browser->get( $url, $key1, $value1, $key2, $value2, ... ); + +For example, here's how to send some commonly used headers, in case +you're dealing with a site that would otherwise reject your request: + + + my @ns_headers = ( + 'User-Agent' => 'Mozilla/4.76 [en] (Win98; U)', + 'Accept' => 'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */*', + 'Accept-Charset' => 'iso-8859-1,*,utf-8', + 'Accept-Language' => 'en-US', + ); + + ... + + $response = $browser->get($url, @ns_headers); + +If you weren't reusing that array, you could just go ahead and do this: + + $response = $browser->get($url, + 'User-Agent' => 'Mozilla/4.76 [en] (Win98; U)', + 'Accept' => 'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */*', + 'Accept-Charset' => 'iso-8859-1,*,utf-8', + 'Accept-Language' => 'en-US', + ); + +If you were only ever changing the 'User-Agent' line, you could just change +the C<$browser> object's default line from "libwww-perl/5.65" (or the like) +to whatever you like, using the LWP::UserAgent C method: + + $browser->agent('Mozilla/4.76 [en] (Win98; U)'); + + + +=for comment + ########################################################################## + + + +=head2 Enabling Cookies + +A default LWP::UserAgent object acts like a browser with its cookies +support turned off. There are various ways of turning it on, by setting +its C attribute. A "cookie jar" is an object representing +a little database of all +the HTTP cookies that a browser knows about. It can correspond to a +file on disk or +an in-memory object that starts out empty, and whose collection of +cookies will disappear once the program is finished running. + +To give a browser an in-memory empty cookie jar, you set its C +attribute like so: + + use HTTP::CookieJar::LWP; + $browser->cookie_jar( HTTP::CookieJar::LWP->new ); + +To save a cookie jar to disk, see L<< HTTP::CookieJar/dump_cookies >>. +To load cookies from disk into a jar, see L<< +HTTP::CookieJar/load_cookies >>. + +=for comment + ########################################################################## + + + +=head2 Posting Form Data + +Many HTML forms send data to their server using an HTTP POST request, which +you can send with this syntax: + + $response = $browser->post( $url, + [ + formkey1 => value1, + formkey2 => value2, + ... + ], + ); + +Or if you need to send HTTP headers: + + $response = $browser->post( $url, + [ + formkey1 => value1, + formkey2 => value2, + ... + ], + headerkey1 => value1, + headerkey2 => value2, + ); + +For example, the following program makes a search request to AltaVista +(by sending some form data via an HTTP POST request), and extracts from +the HTML the report of the number of matches: + + use strict; + use warnings; + use LWP 5.64; + my $browser = LWP::UserAgent->new; + + my $word = 'tarragon'; + + my $url = 'http://search.yahoo.com/yhs/search'; + my $response = $browser->post( $url, + [ 'q' => $word, # the Altavista query string + 'fr' => 'altavista', 'pg' => 'q', 'avkw' => 'tgz', 'kl' => 'XX', + ] + ); + die "$url error: ", $response->status_line + unless $response->is_success; + die "Weird content type at $url -- ", $response->content_type + unless $response->content_is_html; + + if( $response->decoded_content =~ m{([0-9,]+)(?:<.*?>)? results for} ) { + # The substring will be like "996,000 results for" + print "$word: $1\n"; + } + else { + print "Couldn't find the match-string in the response\n"; + } + + + +=for comment + ########################################################################## + + + +=head2 Sending GET Form Data + +Some HTML forms convey their form data not by sending the data +in an HTTP POST request, but by making a normal GET request with +the data stuck on the end of the URL. For example, if you went to +C and ran a search on "Blade Runner", the URL you'd see +in your browser window would be: + + http://www.imdb.com/find?s=all&q=Blade+Runner + +To run the same search with LWP, you'd use this idiom, which involves +the URI class: + + use URI; + my $url = URI->new( 'http://www.imdb.com/find' ); + # makes an object representing the URL + + $url->query_form( # And here the form data pairs: + 'q' => 'Blade Runner', + 's' => 'all', + ); + + my $response = $browser->get($url); + +See chapter 5 of I for a longer discussion of HTML forms +and of form data, and chapters 6 through 9 for a longer discussion of +extracting data from HTML. + + + +=head2 Absolutizing URLs + +The URI class that we just mentioned above provides all sorts of methods +for accessing and modifying parts of URLs (such as asking sort of URL it +is with C<< $url->scheme >>, and asking what host it refers to with C<< +$url->host >>, and so on, as described in L. However, the methods of most immediate interest +are the C method seen above, and now the C method +for taking a probably-relative URL string (like "../foo.html") and getting +back an absolute URL (like "http://www.perl.com/stuff/foo.html"), as +shown here: + + use URI; + $abs = URI->new_abs($maybe_relative, $base); + +For example, consider this program that matches URLs in the HTML +list of new modules in CPAN: + + use strict; + use warnings; + use LWP; + my $browser = LWP::UserAgent->new; + + my $url = 'http://www.cpan.org/RECENT.html'; + my $response = $browser->get($url); + die "Can't get $url -- ", $response->status_line + unless $response->is_success; + + my $html = $response->decoded_content; + while( $html =~ m/ method, by changing the C +loop to this: + + while( $html =~ m/new_abs( $1, $response->base ) ,"\n"; + } + +(The C<< $response->base >> method from L +is for returning what URL +should be used for resolving relative URLs -- it's usually just +the same as the URL that you requested.) + +That program then emits nicely absolute URLs: + + http://www.cpan.org/MIRRORING.FROM + http://www.cpan.org/RECENT + http://www.cpan.org/RECENT.html + http://www.cpan.org/authors/00whois.html + http://www.cpan.org/authors/01mailrc.txt.gz + http://www.cpan.org/authors/id/A/AA/AASSAD/CHECKSUMS + ... + +See chapter 4 of I for a longer discussion of URI objects. + +Of course, using a regexp to match hrefs is a bit simplistic, and for +more robust programs, you'll probably want to use an HTML-parsing module +like L or L or even maybe +L. + + + + +=for comment + ########################################################################## + +=head2 Other Browser Attributes + +LWP::UserAgent objects have many attributes for controlling how they +work. Here are a few notable ones: + +=over + +=item * + +C<< $browser->timeout(15); >> + +This sets this browser object to give up on requests that don't answer +within 15 seconds. + + +=item * + +C<< $browser->protocols_allowed( [ 'http', 'gopher'] ); >> + +This sets this browser object to not speak any protocols other than HTTP +and gopher. If it tries accessing any other kind of URL (like an "ftp:" +or "mailto:" or "news:" URL), then it won't actually try connecting, but +instead will immediately return an error code 500, with a message like +"Access to 'ftp' URIs has been disabled". + + +=item * + +C<< use LWP::ConnCache; $browser->conn_cache(LWP::ConnCache->new()); >> + +This tells the browser object to try using the HTTP/1.1 "Keep-Alive" +feature, which speeds up requests by reusing the same socket connection +for multiple requests to the same server. + + +=item * + +C<< $browser->agent( 'SomeName/1.23 (more info here maybe)' ) >> + +This changes how the browser object will identify itself in +the default "User-Agent" line is its HTTP requests. By default, +it'll send "libwww-perl/I", like +"libwww-perl/5.65". You can change that to something more descriptive +like this: + + $browser->agent( 'SomeName/3.14 (contact@robotplexus.int)' ); + +Or if need be, you can go in disguise, like this: + + $browser->agent( 'Mozilla/4.0 (compatible; MSIE 5.12; Mac_PowerPC)' ); + + +=item * + +C<< push @{ $ua->requests_redirectable }, 'POST'; >> + +This tells this browser to obey redirection responses to POST requests +(like most modern interactive browsers), even though the HTTP RFC says +that should not normally be done. + + +=back + + +For more options and information, see L. + + + +=for comment + ########################################################################## + + + +=head2 Writing Polite Robots + +If you want to make sure that your LWP-based program respects F +files and doesn't make too many requests too fast, you can use the LWP::RobotUA +class instead of the LWP::UserAgent class. + +LWP::RobotUA class is just like LWP::UserAgent, and you can use it like so: + + use LWP::RobotUA; + my $browser = LWP::RobotUA->new('YourSuperBot/1.34', 'you@yoursite.com'); + # Your bot's name and your email address + + my $response = $browser->get($url); + +But HTTP::RobotUA adds these features: + + +=over + +=item * + +If the F on C<$url>'s server forbids you from accessing +C<$url>, then the C<$browser> object (assuming it's of class LWP::RobotUA) +won't actually request it, but instead will give you back (in C<$response>) a 403 error +with a message "Forbidden by robots.txt". That is, if you have this line: + + die "$url -- ", $response->status_line, "\nAborted" + unless $response->is_success; + +then the program would die with an error message like this: + + http://whatever.site.int/pith/x.html -- 403 Forbidden by robots.txt + Aborted at whateverprogram.pl line 1234 + +=item * + +If this C<$browser> object sees that the last time it talked to +C<$url>'s server was too recently, then it will pause (via C) to +avoid making too many requests too often. How long it will pause for, is +by default one minute -- but you can control it with the C<< +$browser->delay( I ) >> attribute. + +For example, this code: + + $browser->delay( 7/60 ); + +...means that this browser will pause when it needs to avoid talking to +any given server more than once every 7 seconds. + +=back + +For more options and information, see L. + + + + + +=for comment + ########################################################################## + +=head2 Using Proxies + +In some cases, you will want to (or will have to) use proxies for +accessing certain sites and/or using certain protocols. This is most +commonly the case when your LWP program is running (or could be running) +on a machine that is behind a firewall. + +To make a browser object use proxies that are defined in the usual +environment variables (C, etc.), just call the C +on a user-agent object before you go making any requests on it. +Specifically: + + use LWP::UserAgent; + my $browser = LWP::UserAgent->new; + + # And before you go making any requests: + $browser->env_proxy; + +For more information on proxy parameters, see L, specifically the C, C, +and C methods. + + + +=for comment + ########################################################################## + +=head2 HTTP Authentication + +Many web sites restrict access to documents by using "HTTP +Authentication". This isn't just any form of "enter your password" +restriction, but is a specific mechanism where the HTTP server sends the +browser an HTTP code that says "That document is part of a protected +'realm', and you can access it only if you re-request it and add some +special authorization headers to your request". + +For example, the Unicode.org admins stop email-harvesting bots from +harvesting the contents of their mailing list archives, by protecting +them with HTTP Authentication, and then publicly stating the username +and password (at C) -- namely +username "unicode-ml" and password "unicode". + +For example, consider this URL, which is part of the protected +area of the web site: + + http://www.unicode.org/mail-arch/unicode-ml/y2002-m08/0067.html + +If you access that with a browser, you'll get a prompt +like +"Enter username and password for 'Unicode-MailList-Archives' at server +'www.unicode.org'". + +In LWP, if you just request that URL, like this: + + use LWP; + my $browser = LWP::UserAgent->new; + + my $url = + 'http://www.unicode.org/mail-arch/unicode-ml/y2002-m08/0067.html'; + my $response = $browser->get($url); + + die "Error: ", $response->header('WWW-Authenticate') || 'Error accessing', + # ('WWW-Authenticate' is the realm-name) + "\n ", $response->status_line, "\n at $url\n Aborting" + unless $response->is_success; + +Then you'll get this error: + + Error: Basic realm="Unicode-MailList-Archives" + 401 Authorization Required + at http://www.unicode.org/mail-arch/unicode-ml/y2002-m08/0067.html + Aborting at auth1.pl line 9. [or wherever] + +...because the C<$browser> doesn't know any the username and password +for that realm ("Unicode-MailList-Archives") at that host +("www.unicode.org"). The simplest way to let the browser know about this +is to use the C method to let it know about a username and +password that it can try using for that realm at that host. The syntax is: + + $browser->credentials( + 'servername:portnumber', + 'realm-name', + 'username' => 'password' + ); + +In most cases, the port number is 80, the default TCP/IP port for HTTP; and +you usually call the C method before you make any requests. +For example: + + $browser->credentials( + 'reports.mybazouki.com:80', + 'web_server_usage_reports', + 'plinky' => 'banjo123' + ); + +So if we add the following to the program above, right after the C<< +$browser = LWP::UserAgent->new; >> line... + + $browser->credentials( # add this to our $browser 's "key ring" + 'www.unicode.org:80', + 'Unicode-MailList-Archives', + 'unicode-ml' => 'unicode' + ); + +...then when we run it, the request succeeds, instead of causing the +C to be called. + + + +=for comment + ########################################################################## + +=head2 Accessing HTTPS URLs + +When you access an HTTPS URL, it'll work for you just like an HTTP URL +would -- if your LWP installation has HTTPS support (via an appropriate +Secure Sockets Layer library). For example: + + use LWP; + my $url = 'https://www.paypal.com/'; # Yes, HTTPS! + my $browser = LWP::UserAgent->new; + my $response = $browser->get($url); + die "Error at $url\n ", $response->status_line, "\n Aborting" + unless $response->is_success; + print "Whee, it worked! I got that ", + $response->content_type, " document!\n"; + +If your LWP installation doesn't have HTTPS support set up, then the +response will be unsuccessful, and you'll get this error message: + + Error at https://www.paypal.com/ + 501 Protocol scheme 'https' is not supported + Aborting at paypal.pl line 7. [or whatever program and line] + +If your LWP installation I have HTTPS support installed, then the +response should be successful, and you should be able to consult +C<$response> just like with any normal HTTP response. + +For information about installing HTTPS support for your LWP +installation, see the helpful F file that comes in the +libwww-perl distribution. + + +=for comment + ########################################################################## + + + +=head2 Getting Large Documents + +When you're requesting a large (or at least potentially large) document, +a problem with the normal way of using the request methods (like C<< +$response = $browser->get($url) >>) is that the response object in +memory will have to hold the whole document -- I. If the +response is a thirty megabyte file, this is likely to be quite an +imposition on this process's memory usage. + +A notable alternative is to have LWP save the content to a file on disk, +instead of saving it up in memory. This is the syntax to use: + + $response = $ua->get($url, + ':content_file' => $filespec, + ); + +For example, + + $response = $ua->get('http://search.cpan.org/', + ':content_file' => '/tmp/sco.html' + ); + +When you use this C<:content_file> option, the C<$response> will have +all the normal header lines, but C<< $response->content >> will be +empty. Errors writing to the content file (for example due to +permission denied or the filesystem being full) will be reported via +the C or C response headers, and not the +C method: + + if ($response->header('Client-Aborted') eq 'die') { + # handle error ... + +Note that this ":content_file" option isn't supported under older +versions of LWP, so you should consider adding C to check +the LWP version, if you think your program might run on systems with +older versions. + +If you need to be compatible with older LWP versions, then use +this syntax, which does the same thing: + + use HTTP::Request::Common; + $response = $ua->request( GET($url), $filespec ); + + +=for comment + ########################################################################## + + +=head1 SEE ALSO + +Remember, this article is just the most rudimentary introduction to +LWP -- to learn more about LWP and LWP-related tasks, you really +must read from the following: + +=over + +=item * + +L -- simple functions for getting/heading/mirroring URLs + +=item * + +L -- overview of the libwww-perl modules + +=item * + +L -- the class for objects that represent "virtual browsers" + +=item * + +L -- the class for objects that represent the response to +a LWP response, as in C<< $response = $browser->get(...) >> + +=item * + +L and L -- classes that provide more methods +to HTTP::Response. + +=item * + +L -- class for objects that represent absolute or relative URLs + +=item * + +L -- functions for URL-escaping and URL-unescaping strings +(like turning "this & that" to and from "this%20%26%20that"). + +=item * + +L -- functions for HTML-escaping and HTML-unescaping strings +(like turning "C. & E. BrontE" to and from "C. & E. Brontë") + +=item * + +L and L -- classes for parsing HTML + +=item * + +L -- class for finding links in HTML documents + +=item * + +The book I by Sean M. Burke. O'Reilly & Associates, +2002. ISBN: 0-596-00178-9, L. The +whole book is also available free online: +L. + +=back + + +=head1 COPYRIGHT + +Copyright 2002, Sean M. Burke. You can redistribute this document and/or +modify it, but only under the same terms as Perl itself. + +=head1 AUTHOR + +Sean M. Burke C + +=for comment + ########################################################################## + +=cut + +# End of Pod diff --git a/Master/tlpkg/tlperl/site/lib/lwpcook.pod b/Master/tlpkg/tlperl/site/lib/lwpcook.pod deleted file mode 100644 index 2002b79925e..00000000000 --- a/Master/tlpkg/tlperl/site/lib/lwpcook.pod +++ /dev/null @@ -1,311 +0,0 @@ -=head1 NAME - -lwpcook - The libwww-perl cookbook - -=head1 DESCRIPTION - -This document contain some examples that show typical usage of the -libwww-perl library. You should consult the documentation for the -individual modules for more detail. - -All examples should be runnable programs. You can, in most cases, test -the code sections by piping the program text directly to perl. - - - -=head1 GET - -It is very easy to use this library to just fetch documents from the -net. The LWP::Simple module provides the get() function that return -the document specified by its URL argument: - - use LWP::Simple; - $doc = get 'http://search.cpan.org/dist/libwww-perl/'; - -or, as a perl one-liner using the getprint() function: - - perl -MLWP::Simple -e 'getprint "http://search.cpan.org/dist/libwww-perl/"' - -or, how about fetching the latest perl by running this command: - - perl -MLWP::Simple -e ' - getstore "ftp://ftp.sunet.se/pub/lang/perl/CPAN/src/latest.tar.gz", - "perl.tar.gz"' - -You will probably first want to find a CPAN site closer to you by -running something like the following command: - - perl -MLWP::Simple -e 'getprint "http://www.cpan.org/SITES.html"' - -Enough of this simple stuff! The LWP object oriented interface gives -you more control over the request sent to the server. Using this -interface you have full control over headers sent and how you want to -handle the response returned. - - use LWP::UserAgent; - $ua = LWP::UserAgent->new; - $ua->agent("$0/0.1 " . $ua->agent); - # $ua->agent("Mozilla/8.0") # pretend we are very capable browser - - $req = HTTP::Request->new( - GET => 'http://search.cpan.org/dist/libwww-perl/'); - $req->header('Accept' => 'text/html'); - - # send request - $res = $ua->request($req); - - # check the outcome - if ($res->is_success) { - print $res->decoded_content; - } - else { - print "Error: " . $res->status_line . "\n"; - } - -The lwp-request program (alias GET) that is distributed with the -library can also be used to fetch documents from WWW servers. - - - -=head1 HEAD - -If you just want to check if a document is present (i.e. the URL is -valid) try to run code that looks like this: - - use LWP::Simple; - - if (head($url)) { - # ok document exists - } - -The head() function really returns a list of meta-information about -the document. The first three values of the list returned are the -document type, the size of the document, and the age of the document. - -More control over the request or access to all header values returned -require that you use the object oriented interface described for GET -above. Just s/GET/HEAD/g. - - -=head1 POST - -There is no simple procedural interface for posting data to a WWW server. You -must use the object oriented interface for this. The most common POST -operation is to access a WWW form application: - - use LWP::UserAgent; - $ua = LWP::UserAgent->new; - - my $req = HTTP::Request->new( - POST => 'http://rt.cpan.org/Public/Dist/Display.html'); - $req->content_type('application/x-www-form-urlencoded'); - $req->content('Status=Active&Name=libwww-perl'); - - my $res = $ua->request($req); - print $res->as_string; - -Lazy people use the HTTP::Request::Common module to set up a suitable -POST request message (it handles all the escaping issues) and has a -suitable default for the content_type: - - use HTTP::Request::Common qw(POST); - use LWP::UserAgent; - $ua = LWP::UserAgent->new; - - my $req = POST 'http://rt.cpan.org/Public/Dist/Display.html', - [ Status => 'Active', Name => 'libwww-perl' ]; - - print $ua->request($req)->as_string; - -The lwp-request program (alias POST) that is distributed with the -library can also be used for posting data. - - - -=head1 PROXIES - -Some sites use proxies to go through fire wall machines, or just as -cache in order to improve performance. Proxies can also be used for -accessing resources through protocols not supported directly (or -supported badly :-) by the libwww-perl library. - -You should initialize your proxy setting before you start sending -requests: - - use LWP::UserAgent; - $ua = LWP::UserAgent->new; - $ua->env_proxy; # initialize from environment variables - # or - $ua->proxy(ftp => 'http://proxy.myorg.com'); - $ua->proxy(wais => 'http://proxy.myorg.com'); - $ua->no_proxy(qw(no se fi)); - - my $req = HTTP::Request->new(GET => 'wais://xxx.com/'); - print $ua->request($req)->as_string; - -The LWP::Simple interface will call env_proxy() for you automatically. -Applications that use the $ua->env_proxy() method will normally not -use the $ua->proxy() and $ua->no_proxy() methods. - -Some proxies also require that you send it a username/password in -order to let requests through. You should be able to add the -required header, with something like this: - - use LWP::UserAgent; - - $ua = LWP::UserAgent->new; - $ua->proxy(['http', 'ftp'] => 'http://username:password@proxy.myorg.com'); - - $req = HTTP::Request->new('GET',"http://www.perl.com"); - - $res = $ua->request($req); - print $res->decoded_content if $res->is_success; - -Replace C, C and -C with something suitable for your site. - - -=head1 ACCESS TO PROTECTED DOCUMENTS - -Documents protected by basic authorization can easily be accessed -like this: - - use LWP::UserAgent; - $ua = LWP::UserAgent->new; - $req = HTTP::Request->new(GET => 'http://www.linpro.no/secret/'); - $req->authorization_basic('aas', 'mypassword'); - print $ua->request($req)->as_string; - -The other alternative is to provide a subclass of I that -overrides the get_basic_credentials() method. Study the I -program for an example of this. - - -=head1 COOKIES - -Some sites like to play games with cookies. By default LWP ignores -cookies provided by the servers it visits. LWP will collect cookies -and respond to cookie requests if you set up a cookie jar. - - use LWP::UserAgent; - use HTTP::Cookies; - - $ua = LWP::UserAgent->new; - $ua->cookie_jar(HTTP::Cookies->new(file => "lwpcookies.txt", - autosave => 1)); - - # and then send requests just as you used to do - $res = $ua->request(HTTP::Request->new(GET => "http://no.yahoo.com/")); - print $res->status_line, "\n"; - -As you visit sites that send you cookies to keep, then the file -F will grow. - -=head1 HTTPS - -URLs with https scheme are accessed in exactly the same way as with -http scheme, provided that an SSL interface module for LWP has been -properly installed (see the F file found in the -libwww-perl distribution for more details). If no SSL interface is -installed for LWP to use, then you will get "501 Protocol scheme -'https' is not supported" errors when accessing such URLs. - -Here's an example of fetching and printing a WWW page using SSL: - - use LWP::UserAgent; - - my $ua = LWP::UserAgent->new; - my $req = HTTP::Request->new(GET => 'https://www.helsinki.fi/'); - my $res = $ua->request($req); - if ($res->is_success) { - print $res->as_string; - } - else { - print "Failed: ", $res->status_line, "\n"; - } - -=head1 MIRRORING - -If you want to mirror documents from a WWW server, then try to run -code similar to this at regular intervals: - - use LWP::Simple; - - %mirrors = ( - 'http://www.sn.no/' => 'sn.html', - 'http://www.perl.com/' => 'perl.html', - 'http://search.cpan.org/distlibwww-perl/' => 'lwp.html', - 'gopher://gopher.sn.no/' => 'gopher.html', - ); - - while (($url, $localfile) = each(%mirrors)) { - mirror($url, $localfile); - } - -Or, as a perl one-liner: - - perl -MLWP::Simple -e 'mirror("http://www.perl.com/", "perl.html")'; - -The document will not be transferred unless it has been updated. - - - -=head1 LARGE DOCUMENTS - -If the document you want to fetch is too large to be kept in memory, -then you have two alternatives. You can instruct the library to write -the document content to a file (second $ua->request() argument is a file -name): - - use LWP::UserAgent; - $ua = LWP::UserAgent->new; - - my $req = HTTP::Request->new(GET => - 'http://www.cpan.org/authors/Gisle_Aas/libwww-perl-6.02.tar.gz'); - $res = $ua->request($req, "libwww-perl.tar.gz"); - if ($res->is_success) { - print "ok\n"; - } - else { - print $res->status_line, "\n"; - } - - -Or you can process the document as it arrives (second $ua->request() -argument is a code reference): - - use LWP::UserAgent; - $ua = LWP::UserAgent->new; - $URL = 'ftp://ftp.unit.no/pub/rfc/rfc-index.txt'; - - my $expected_length; - my $bytes_received = 0; - my $res = - $ua->request(HTTP::Request->new(GET => $URL), - sub { - my($chunk, $res) = @_; - $bytes_received += length($chunk); - unless (defined $expected_length) { - $expected_length = $res->content_length || 0; - } - if ($expected_length) { - printf STDERR "%d%% - ", - 100 * $bytes_received / $expected_length; - } - print STDERR "$bytes_received bytes received\n"; - - # XXX Should really do something with the chunk itself - # print $chunk; - }); - print $res->status_line, "\n"; - - - -=head1 COPYRIGHT - -Copyright 1996-2001, Gisle Aas - -This library is free software; you can redistribute it and/or -modify it under the same terms as Perl itself. - - diff --git a/Master/tlpkg/tlperl/site/lib/lwptut.pod b/Master/tlpkg/tlperl/site/lib/lwptut.pod deleted file mode 100644 index 3ab5e61eae4..00000000000 --- a/Master/tlpkg/tlperl/site/lib/lwptut.pod +++ /dev/null @@ -1,839 +0,0 @@ -=head1 NAME - -lwptut -- An LWP Tutorial - -=head1 DESCRIPTION - -LWP (short for "Library for WWW in Perl") is a very popular group of -Perl modules for accessing data on the Web. Like most Perl -module-distributions, each of LWP's component modules comes with -documentation that is a complete reference to its interface. However, -there are so many modules in LWP that it's hard to know where to start -looking for information on how to do even the simplest most common -things. - -Really introducing you to using LWP would require a whole book -- a book -that just happens to exist, called I. But this article -should give you a taste of how you can go about some common tasks with -LWP. - - -=head2 Getting documents with LWP::Simple - -If you just want to get what's at a particular URL, the simplest way -to do it is LWP::Simple's functions. - -In a Perl program, you can call its C function. It will try -getting that URL's content. If it works, then it'll return the -content; but if there's some error, it'll return undef. - - my $url = 'http://www.npr.org/programs/fa/?todayDate=current'; - # Just an example: the URL for the most recent /Fresh Air/ show - - use LWP::Simple; - my $content = get $url; - die "Couldn't get $url" unless defined $content; - - # Then go do things with $content, like this: - - if($content =~ m/jazz/i) { - print "They're talking about jazz today on Fresh Air!\n"; - } - else { - print "Fresh Air is apparently jazzless today.\n"; - } - -The handiest variant on C is C, which is useful in Perl -one-liners. If it can get the page whose URL you provide, it sends it -to STDOUT; otherwise it complains to STDERR. - - % perl -MLWP::Simple -e "getprint 'http://www.cpan.org/RECENT'" - -That is the URL of a plain text file that lists new files in CPAN in -the past two weeks. You can easily make it part of a tidy little -shell command, like this one that mails you the list of new -C modules: - - % perl -MLWP::Simple -e "getprint 'http://www.cpan.org/RECENT'" \ - | grep "/by-module/Acme" | mail -s "New Acme modules! Joy!" $USER - -There are other useful functions in LWP::Simple, including one function -for running a HEAD request on a URL (useful for checking links, or -getting the last-revised time of a URL), and two functions for -saving/mirroring a URL to a local file. See L for the full details, or chapter 2 of I for more examples. - - - -=for comment - ########################################################################## - - - -=head2 The Basics of the LWP Class Model - -LWP::Simple's functions are handy for simple cases, but its functions -don't support cookies or authorization, don't support setting header -lines in the HTTP request, generally don't support reading header lines -in the HTTP response (notably the full HTTP error message, in case of an -error). To get at all those features, you'll have to use the full LWP -class model. - -While LWP consists of dozens of classes, the main two that you have to -understand are L and L. LWP::UserAgent -is a class for "virtual browsers" which you use for performing requests, -and L is a class for the responses (or error messages) -that you get back from those requests. - -The basic idiom is C<< $response = $browser->get($url) >>, or more fully -illustrated: - - # Early in your program: - - use LWP 5.64; # Loads all important LWP classes, and makes - # sure your version is reasonably recent. - - my $browser = LWP::UserAgent->new; - - ... - - # Then later, whenever you need to make a get request: - my $url = 'http://www.npr.org/programs/fa/?todayDate=current'; - - my $response = $browser->get( $url ); - die "Can't get $url -- ", $response->status_line - unless $response->is_success; - - die "Hey, I was expecting HTML, not ", $response->content_type - unless $response->content_type eq 'text/html'; - # or whatever content-type you're equipped to deal with - - # Otherwise, process the content somehow: - - if($response->decoded_content =~ m/jazz/i) { - print "They're talking about jazz today on Fresh Air!\n"; - } - else { - print "Fresh Air is apparently jazzless today.\n"; - } - -There are two objects involved: C<$browser>, which holds an object of -class LWP::UserAgent, and then the C<$response> object, which is of -class HTTP::Response. You really need only one browser object per -program; but every time you make a request, you get back a new -HTTP::Response object, which will have some interesting attributes: - -=over - -=item * - -A status code indicating -success or failure -(which you can test with C<< $response->is_success >>). - -=item * - -An HTTP status -line that is hopefully informative if there's failure (which you can -see with C<< $response->status_line >>, -returning something like "404 Not Found"). - -=item * - -A MIME content-type like "text/html", "image/gif", -"application/xml", etc., which you can see with -C<< $response->content_type >> - -=item * - -The actual content of the response, in C<< $response->decoded_content >>. -If the response is HTML, that's where the HTML source will be; if -it's a GIF, then C<< $response->decoded_content >> will be the binary -GIF data. - -=item * - -And dozens of other convenient and more specific methods that are -documented in the docs for L, and its superclasses -L and L. - -=back - - - -=for comment - ########################################################################## - - - -=head2 Adding Other HTTP Request Headers - -The most commonly used syntax for requests is C<< $response = -$browser->get($url) >>, but in truth, you can add extra HTTP header -lines to the request by adding a list of key-value pairs after the URL, -like so: - - $response = $browser->get( $url, $key1, $value1, $key2, $value2, ... ); - -For example, here's how to send some more Netscape-like headers, in case -you're dealing with a site that would otherwise reject your request: - - - my @ns_headers = ( - 'User-Agent' => 'Mozilla/4.76 [en] (Win98; U)', - 'Accept' => 'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */*', - 'Accept-Charset' => 'iso-8859-1,*,utf-8', - 'Accept-Language' => 'en-US', - ); - - ... - - $response = $browser->get($url, @ns_headers); - -If you weren't reusing that array, you could just go ahead and do this: - - $response = $browser->get($url, - 'User-Agent' => 'Mozilla/4.76 [en] (Win98; U)', - 'Accept' => 'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */*', - 'Accept-Charset' => 'iso-8859-1,*,utf-8', - 'Accept-Language' => 'en-US', - ); - -If you were only ever changing the 'User-Agent' line, you could just change -the C<$browser> object's default line from "libwww-perl/5.65" (or the like) -to whatever you like, using the LWP::UserAgent C method: - - $browser->agent('Mozilla/4.76 [en] (Win98; U)'); - - - -=for comment - ########################################################################## - - - -=head2 Enabling Cookies - -A default LWP::UserAgent object acts like a browser with its cookies -support turned off. There are various ways of turning it on, by setting -its C attribute. A "cookie jar" is an object representing -a little database of all -the HTTP cookies that a browser can know about. It can correspond to a -file on disk (the way Netscape uses its F file), or it can -be just an in-memory object that starts out empty, and whose collection of -cookies will disappear once the program is finished running. - -To give a browser an in-memory empty cookie jar, you set its C -attribute like so: - - $browser->cookie_jar({}); - -To give it a copy that will be read from a file on disk, and will be saved -to it when the program is finished running, set the C attribute -like this: - - use HTTP::Cookies; - $browser->cookie_jar( HTTP::Cookies->new( - 'file' => '/some/where/cookies.lwp', - # where to read/write cookies - 'autosave' => 1, - # save it to disk when done - )); - -That file will be in LWP-specific format. If you want to access the -cookies in your Netscape cookies file, you can use the -HTTP::Cookies::Netscape class: - - use HTTP::Cookies; - # yes, loads HTTP::Cookies::Netscape too - - $browser->cookie_jar( HTTP::Cookies::Netscape->new( - 'file' => 'c:/Program Files/Netscape/Users/DIR-NAME-HERE/cookies.txt', - # where to read cookies - )); - -You could add an C<< 'autosave' => 1 >> line as further above, but at -time of writing, it's uncertain whether Netscape might discard some of -the cookies you could be writing back to disk. - - - -=for comment - ########################################################################## - - - -=head2 Posting Form Data - -Many HTML forms send data to their server using an HTTP POST request, which -you can send with this syntax: - - $response = $browser->post( $url, - [ - formkey1 => value1, - formkey2 => value2, - ... - ], - ); - -Or if you need to send HTTP headers: - - $response = $browser->post( $url, - [ - formkey1 => value1, - formkey2 => value2, - ... - ], - headerkey1 => value1, - headerkey2 => value2, - ); - -For example, the following program makes a search request to AltaVista -(by sending some form data via an HTTP POST request), and extracts from -the HTML the report of the number of matches: - - use strict; - use warnings; - use LWP 5.64; - my $browser = LWP::UserAgent->new; - - my $word = 'tarragon'; - - my $url = 'http://search.yahoo.com/yhs/search'; - my $response = $browser->post( $url, - [ 'q' => $word, # the Altavista query string - 'fr' => 'altavista', 'pg' => 'q', 'avkw' => 'tgz', 'kl' => 'XX', - ] - ); - die "$url error: ", $response->status_line - unless $response->is_success; - die "Weird content type at $url -- ", $response->content_type - unless $response->content_is_html; - - if( $response->decoded_content =~ m{([0-9,]+)(?:<.*?>)? results for} ) { - # The substring will be like "996,000 results for" - print "$word: $1\n"; - } - else { - print "Couldn't find the match-string in the response\n"; - } - - - -=for comment - ########################################################################## - - - -=head2 Sending GET Form Data - -Some HTML forms convey their form data not by sending the data -in an HTTP POST request, but by making a normal GET request with -the data stuck on the end of the URL. For example, if you went to -C and ran a search on "Blade Runner", the URL you'd see -in your browser window would be: - - http://www.imdb.com/find?s=all&q=Blade+Runner - -To run the same search with LWP, you'd use this idiom, which involves -the URI class: - - use URI; - my $url = URI->new( 'http://www.imdb.com/find' ); - # makes an object representing the URL - - $url->query_form( # And here the form data pairs: - 'q' => 'Blade Runner', - 's' => 'all', - ); - - my $response = $browser->get($url); - -See chapter 5 of I for a longer discussion of HTML forms -and of form data, and chapters 6 through 9 for a longer discussion of -extracting data from HTML. - - - -=head2 Absolutizing URLs - -The URI class that we just mentioned above provides all sorts of methods -for accessing and modifying parts of URLs (such as asking sort of URL it -is with C<< $url->scheme >>, and asking what host it refers to with C<< -$url->host >>, and so on, as described in L. However, the methods of most immediate interest -are the C method seen above, and now the C method -for taking a probably-relative URL string (like "../foo.html") and getting -back an absolute URL (like "http://www.perl.com/stuff/foo.html"), as -shown here: - - use URI; - $abs = URI->new_abs($maybe_relative, $base); - -For example, consider this program that matches URLs in the HTML -list of new modules in CPAN: - - use strict; - use warnings; - use LWP; - my $browser = LWP::UserAgent->new; - - my $url = 'http://www.cpan.org/RECENT.html'; - my $response = $browser->get($url); - die "Can't get $url -- ", $response->status_line - unless $response->is_success; - - my $html = $response->decoded_content; - while( $html =~ m/ method, by changing the C -loop to this: - - while( $html =~ m/new_abs( $1, $response->base ) ,"\n"; - } - -(The C<< $response->base >> method from L -is for returning what URL -should be used for resolving relative URLs -- it's usually just -the same as the URL that you requested.) - -That program then emits nicely absolute URLs: - - http://www.cpan.org/MIRRORING.FROM - http://www.cpan.org/RECENT - http://www.cpan.org/RECENT.html - http://www.cpan.org/authors/00whois.html - http://www.cpan.org/authors/01mailrc.txt.gz - http://www.cpan.org/authors/id/A/AA/AASSAD/CHECKSUMS - ... - -See chapter 4 of I for a longer discussion of URI objects. - -Of course, using a regexp to match hrefs is a bit simplistic, and for -more robust programs, you'll probably want to use an HTML-parsing module -like L or L or even maybe -L. - - - - -=for comment - ########################################################################## - -=head2 Other Browser Attributes - -LWP::UserAgent objects have many attributes for controlling how they -work. Here are a few notable ones: - -=over - -=item * - -C<< $browser->timeout(15); >> - -This sets this browser object to give up on requests that don't answer -within 15 seconds. - - -=item * - -C<< $browser->protocols_allowed( [ 'http', 'gopher'] ); >> - -This sets this browser object to not speak any protocols other than HTTP -and gopher. If it tries accessing any other kind of URL (like an "ftp:" -or "mailto:" or "news:" URL), then it won't actually try connecting, but -instead will immediately return an error code 500, with a message like -"Access to 'ftp' URIs has been disabled". - - -=item * - -C<< use LWP::ConnCache; $browser->conn_cache(LWP::ConnCache->new()); >> - -This tells the browser object to try using the HTTP/1.1 "Keep-Alive" -feature, which speeds up requests by reusing the same socket connection -for multiple requests to the same server. - - -=item * - -C<< $browser->agent( 'SomeName/1.23 (more info here maybe)' ) >> - -This changes how the browser object will identify itself in -the default "User-Agent" line is its HTTP requests. By default, -it'll send "libwww-perl/I", like -"libwww-perl/5.65". You can change that to something more descriptive -like this: - - $browser->agent( 'SomeName/3.14 (contact@robotplexus.int)' ); - -Or if need be, you can go in disguise, like this: - - $browser->agent( 'Mozilla/4.0 (compatible; MSIE 5.12; Mac_PowerPC)' ); - - -=item * - -C<< push @{ $ua->requests_redirectable }, 'POST'; >> - -This tells this browser to obey redirection responses to POST requests -(like most modern interactive browsers), even though the HTTP RFC says -that should not normally be done. - - -=back - - -For more options and information, see L. - - - -=for comment - ########################################################################## - - - -=head2 Writing Polite Robots - -If you want to make sure that your LWP-based program respects F -files and doesn't make too many requests too fast, you can use the LWP::RobotUA -class instead of the LWP::UserAgent class. - -LWP::RobotUA class is just like LWP::UserAgent, and you can use it like so: - - use LWP::RobotUA; - my $browser = LWP::RobotUA->new('YourSuperBot/1.34', 'you@yoursite.com'); - # Your bot's name and your email address - - my $response = $browser->get($url); - -But HTTP::RobotUA adds these features: - - -=over - -=item * - -If the F on C<$url>'s server forbids you from accessing -C<$url>, then the C<$browser> object (assuming it's of class LWP::RobotUA) -won't actually request it, but instead will give you back (in C<$response>) a 403 error -with a message "Forbidden by robots.txt". That is, if you have this line: - - die "$url -- ", $response->status_line, "\nAborted" - unless $response->is_success; - -then the program would die with an error message like this: - - http://whatever.site.int/pith/x.html -- 403 Forbidden by robots.txt - Aborted at whateverprogram.pl line 1234 - -=item * - -If this C<$browser> object sees that the last time it talked to -C<$url>'s server was too recently, then it will pause (via C) to -avoid making too many requests too often. How long it will pause for, is -by default one minute -- but you can control it with the C<< -$browser->delay( I ) >> attribute. - -For example, this code: - - $browser->delay( 7/60 ); - -...means that this browser will pause when it needs to avoid talking to -any given server more than once every 7 seconds. - -=back - -For more options and information, see L. - - - - - -=for comment - ########################################################################## - -=head2 Using Proxies - -In some cases, you will want to (or will have to) use proxies for -accessing certain sites and/or using certain protocols. This is most -commonly the case when your LWP program is running (or could be running) -on a machine that is behind a firewall. - -To make a browser object use proxies that are defined in the usual -environment variables (C, etc.), just call the C -on a user-agent object before you go making any requests on it. -Specifically: - - use LWP::UserAgent; - my $browser = LWP::UserAgent->new; - - # And before you go making any requests: - $browser->env_proxy; - -For more information on proxy parameters, see L, specifically the C, C, -and C methods. - - - -=for comment - ########################################################################## - -=head2 HTTP Authentication - -Many web sites restrict access to documents by using "HTTP -Authentication". This isn't just any form of "enter your password" -restriction, but is a specific mechanism where the HTTP server sends the -browser an HTTP code that says "That document is part of a protected -'realm', and you can access it only if you re-request it and add some -special authorization headers to your request". - -For example, the Unicode.org admins stop email-harvesting bots from -harvesting the contents of their mailing list archives, by protecting -them with HTTP Authentication, and then publicly stating the username -and password (at C) -- namely -username "unicode-ml" and password "unicode". - -For example, consider this URL, which is part of the protected -area of the web site: - - http://www.unicode.org/mail-arch/unicode-ml/y2002-m08/0067.html - -If you access that with a browser, you'll get a prompt -like -"Enter username and password for 'Unicode-MailList-Archives' at server -'www.unicode.org'". - -In LWP, if you just request that URL, like this: - - use LWP; - my $browser = LWP::UserAgent->new; - - my $url = - 'http://www.unicode.org/mail-arch/unicode-ml/y2002-m08/0067.html'; - my $response = $browser->get($url); - - die "Error: ", $response->header('WWW-Authenticate') || 'Error accessing', - # ('WWW-Authenticate' is the realm-name) - "\n ", $response->status_line, "\n at $url\n Aborting" - unless $response->is_success; - -Then you'll get this error: - - Error: Basic realm="Unicode-MailList-Archives" - 401 Authorization Required - at http://www.unicode.org/mail-arch/unicode-ml/y2002-m08/0067.html - Aborting at auth1.pl line 9. [or wherever] - -...because the C<$browser> doesn't know any the username and password -for that realm ("Unicode-MailList-Archives") at that host -("www.unicode.org"). The simplest way to let the browser know about this -is to use the C method to let it know about a username and -password that it can try using for that realm at that host. The syntax is: - - $browser->credentials( - 'servername:portnumber', - 'realm-name', - 'username' => 'password' - ); - -In most cases, the port number is 80, the default TCP/IP port for HTTP; and -you usually call the C method before you make any requests. -For example: - - $browser->credentials( - 'reports.mybazouki.com:80', - 'web_server_usage_reports', - 'plinky' => 'banjo123' - ); - -So if we add the following to the program above, right after the C<< -$browser = LWP::UserAgent->new; >> line... - - $browser->credentials( # add this to our $browser 's "key ring" - 'www.unicode.org:80', - 'Unicode-MailList-Archives', - 'unicode-ml' => 'unicode' - ); - -...then when we run it, the request succeeds, instead of causing the -C to be called. - - - -=for comment - ########################################################################## - -=head2 Accessing HTTPS URLs - -When you access an HTTPS URL, it'll work for you just like an HTTP URL -would -- if your LWP installation has HTTPS support (via an appropriate -Secure Sockets Layer library). For example: - - use LWP; - my $url = 'https://www.paypal.com/'; # Yes, HTTPS! - my $browser = LWP::UserAgent->new; - my $response = $browser->get($url); - die "Error at $url\n ", $response->status_line, "\n Aborting" - unless $response->is_success; - print "Whee, it worked! I got that ", - $response->content_type, " document!\n"; - -If your LWP installation doesn't have HTTPS support set up, then the -response will be unsuccessful, and you'll get this error message: - - Error at https://www.paypal.com/ - 501 Protocol scheme 'https' is not supported - Aborting at paypal.pl line 7. [or whatever program and line] - -If your LWP installation I have HTTPS support installed, then the -response should be successful, and you should be able to consult -C<$response> just like with any normal HTTP response. - -For information about installing HTTPS support for your LWP -installation, see the helpful F file that comes in the -libwww-perl distribution. - - -=for comment - ########################################################################## - - - -=head2 Getting Large Documents - -When you're requesting a large (or at least potentially large) document, -a problem with the normal way of using the request methods (like C<< -$response = $browser->get($url) >>) is that the response object in -memory will have to hold the whole document -- I. If the -response is a thirty megabyte file, this is likely to be quite an -imposition on this process's memory usage. - -A notable alternative is to have LWP save the content to a file on disk, -instead of saving it up in memory. This is the syntax to use: - - $response = $ua->get($url, - ':content_file' => $filespec, - ); - -For example, - - $response = $ua->get('http://search.cpan.org/', - ':content_file' => '/tmp/sco.html' - ); - -When you use this C<:content_file> option, the C<$response> will have -all the normal header lines, but C<< $response->content >> will be -empty. - -Note that this ":content_file" option isn't supported under older -versions of LWP, so you should consider adding C to check -the LWP version, if you think your program might run on systems with -older versions. - -If you need to be compatible with older LWP versions, then use -this syntax, which does the same thing: - - use HTTP::Request::Common; - $response = $ua->request( GET($url), $filespec ); - - -=for comment - ########################################################################## - - -=head1 SEE ALSO - -Remember, this article is just the most rudimentary introduction to -LWP -- to learn more about LWP and LWP-related tasks, you really -must read from the following: - -=over - -=item * - -L -- simple functions for getting/heading/mirroring URLs - -=item * - -L -- overview of the libwww-perl modules - -=item * - -L -- the class for objects that represent "virtual browsers" - -=item * - -L -- the class for objects that represent the response to -a LWP response, as in C<< $response = $browser->get(...) >> - -=item * - -L and L -- classes that provide more methods -to HTTP::Response. - -=item * - -L -- class for objects that represent absolute or relative URLs - -=item * - -L -- functions for URL-escaping and URL-unescaping strings -(like turning "this & that" to and from "this%20%26%20that"). - -=item * - -L -- functions for HTML-escaping and HTML-unescaping strings -(like turning "C. & E. BrontE" to and from "C. & E. Brontë") - -=item * - -L and L -- classes for parsing HTML - -=item * - -L -- class for finding links in HTML documents - -=item * - -The book I by Sean M. Burke. O'Reilly & Associates, -2002. ISBN: 0-596-00178-9, L. The -whole book is also available free online: -L. - -=back - - -=head1 COPYRIGHT - -Copyright 2002, Sean M. Burke. You can redistribute this document and/or -modify it, but only under the same terms as Perl itself. - -=head1 AUTHOR - -Sean M. Burke C - -=for comment - ########################################################################## - -=cut - -# End of Pod -- cgit v1.2.3