Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

722 lines
21 KiB

  1. # $Id: UserAgent.pm,v 1.77 2001/03/14 20:48:19 gisle Exp $
  2. package LWP::UserAgent;
  3. use strict;
  4. =head1 NAME
  5. LWP::UserAgent - A WWW UserAgent class
  6. =head1 SYNOPSIS
  7. require LWP::UserAgent;
  8. $ua = LWP::UserAgent->new;
  9. $request = HTTP::Request->new('GET', 'file://localhost/etc/motd');
  10. $response = $ua->request($request); # or
  11. $response = $ua->request($request, '/tmp/sss'); # or
  12. $response = $ua->request($request, \&callback, 4096);
  13. sub callback { my($data, $response, $protocol) = @_; .... }
  14. =head1 DESCRIPTION
  15. The C<LWP::UserAgent> is a class implementing a simple World-Wide Web
  16. user agent in Perl. It brings together the HTTP::Request,
  17. HTTP::Response and the LWP::Protocol classes that form the rest of the
  18. core of libwww-perl library. For simple uses this class can be used
  19. directly to dispatch WWW requests, alternatively it can be subclassed
  20. for application-specific behaviour.
  21. In normal use the application creates a UserAgent object, and then
  22. configures it with values for timeouts, proxies, name, etc. It next
  23. creates an instance of C<HTTP::Request> for the request that
  24. needs to be performed. This request is then passed to the UserAgent
  25. request() method, which dispatches it using the relevant protocol,
  26. and returns a C<HTTP::Response> object.
  27. The basic approach of the library is to use HTTP style communication
  28. for all protocol schemes, i.e. you also receive an C<HTTP::Response>
  29. object for gopher or ftp requests. In order to achieve even more
  30. similarity to HTTP style communications, gopher menus and file
  31. directories are converted to HTML documents.
  32. The request() method can process the content of the response in one of
  33. three ways: in core, into a file, or into repeated calls to a
  34. subroutine. You choose which one by the kind of value passed as the
  35. second argument to request().
  36. The in core variant simply stores the content in a scalar 'content' attribute
  37. of the response object and is suitable for small
  38. HTML replies that might need further parsing. This variant is used if
  39. the second argument is missing (or is undef).
  40. The filename variant requires a scalar containing a filename as the
  41. second argument to request() and is suitable for large WWW objects
  42. which need to be written directly to the file without requiring large
  43. amounts of memory. In this case the response object returned from
  44. request() will have an empty content attribute. If the request fails, then the
  45. content might not be empty, and the file will be untouched.
  46. The subroutine variant requires a reference to callback routine as the
  47. second argument to request() and it can also take an optional chuck
  48. size as the third argument. This variant can be used to construct
  49. "pipe-lined" processing, where processing of received chuncks can
  50. begin before the complete data has arrived. The callback function is
  51. called with 3 arguments: the data received this time, a reference to
  52. the response object and a reference to the protocol object. The
  53. response object returned from request() will have empty content. If
  54. the request fails, then the the callback routine is not
  55. called, and the response->content might not be empty.
  56. The request can be aborted by calling die() in the callback
  57. routine. The die message will be available as the "X-Died" special
  58. response header field.
  59. The library also allows you to use a subroutine reference as
  60. content in the request object. This subroutine should return the
  61. content (possibly in pieces) when called. It should return an empty
  62. string when there is no more content.
  63. =head1 METHODS
  64. The following methods are available:
  65. =over 4
  66. =cut
  67. use vars qw(@ISA $VERSION);
  68. require LWP::MemberMixin;
  69. @ISA = qw(LWP::MemberMixin);
  70. $VERSION = sprintf("%d.%02d", q$Revision: 1.77 $ =~ /(\d+)\.(\d+)/);
  71. use HTTP::Request ();
  72. use HTTP::Response ();
  73. use HTTP::Date ();
  74. use LWP ();
  75. use LWP::Debug ();
  76. use LWP::Protocol ();
  77. use Carp ();
  78. =item $ua = LWP::UserAgent->new;
  79. Constructor for the UserAgent. Returns a reference to a
  80. LWP::UserAgent object.
  81. =cut
  82. sub new
  83. {
  84. my($class, $init) = @_;
  85. LWP::Debug::trace('()');
  86. my $self;
  87. if (ref $init) {
  88. $self = $init->clone;
  89. } else {
  90. $self = bless {
  91. 'agent' => "libwww-perl/$LWP::VERSION",
  92. 'from' => undef,
  93. 'timeout' => 3*60,
  94. 'proxy' => undef,
  95. 'cookie_jar' => undef,
  96. 'use_eval' => 1,
  97. 'parse_head' => 1,
  98. 'max_size' => undef,
  99. 'no_proxy' => [],
  100. }, $class;
  101. }
  102. }
  103. =item $ua->simple_request($request, [$arg [, $size]])
  104. This method dispatches a single WWW request on behalf of a user, and
  105. returns the response received. The C<$request> should be a reference
  106. to a C<HTTP::Request> object with values defined for at least the
  107. method() and uri() attributes.
  108. If C<$arg> is a scalar it is taken as a filename where the content of
  109. the response is stored.
  110. If C<$arg> is a reference to a subroutine, then this routine is called
  111. as chunks of the content is received. An optional C<$size> argument
  112. is taken as a hint for an appropriate chunk size.
  113. If C<$arg> is omitted, then the content is stored in the response
  114. object itself.
  115. =cut
  116. sub simple_request
  117. {
  118. my($self, $request, $arg, $size) = @_;
  119. local($SIG{__DIE__}); # protect agains user defined die handlers
  120. my($method, $url) = ($request->method, $request->url);
  121. # Check that we have a METHOD and a URL first
  122. return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST, "Method missing")
  123. unless $method;
  124. return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST, "URL missing")
  125. unless $url;
  126. return HTTP::Response->new(&HTTP::Status::RC_BAD_REQUEST, "URL must be absolute")
  127. unless $url->scheme;
  128. LWP::Debug::trace("$method $url");
  129. # Locate protocol to use
  130. my $scheme = '';
  131. my $proxy = $self->_need_proxy($url);
  132. if (defined $proxy) {
  133. $scheme = $proxy->scheme;
  134. } else {
  135. $scheme = $url->scheme;
  136. }
  137. my $protocol;
  138. eval {
  139. $protocol = LWP::Protocol::create($scheme);
  140. };
  141. if ($@) {
  142. $@ =~ s/\s+at\s+\S+\s+line\s+\d+.*//; # remove file/line number
  143. return HTTP::Response->new(&HTTP::Status::RC_NOT_IMPLEMENTED, $@)
  144. }
  145. # Extract fields that will be used below
  146. my ($agent, $from, $timeout, $cookie_jar,
  147. $use_eval, $parse_head, $max_size) =
  148. @{$self}{qw(agent from timeout cookie_jar
  149. use_eval parse_head max_size)};
  150. # Set User-Agent and From headers if they are defined
  151. $request->header('User-Agent' => $agent) if $agent;
  152. $request->header('From' => $from) if $from;
  153. $request->header('Range' => "bytes=0-$max_size") if $max_size;
  154. $cookie_jar->add_cookie_header($request) if $cookie_jar;
  155. # Transfer some attributes to the protocol object
  156. $protocol->parse_head($parse_head);
  157. $protocol->max_size($max_size);
  158. my $response;
  159. if ($use_eval) {
  160. # we eval, and turn dies into responses below
  161. eval {
  162. $response = $protocol->request($request, $proxy,
  163. $arg, $size, $timeout);
  164. };
  165. if ($@) {
  166. $@ =~ s/\s+at\s+\S+\s+line\s+\d+.*//;
  167. $response =
  168. HTTP::Response->new(&HTTP::Status::RC_INTERNAL_SERVER_ERROR,
  169. $@);
  170. }
  171. } else {
  172. $response = $protocol->request($request, $proxy,
  173. $arg, $size, $timeout);
  174. # XXX: Should we die unless $response->is_success ???
  175. }
  176. $response->request($request); # record request for reference
  177. $cookie_jar->extract_cookies($response) if $cookie_jar;
  178. $response->header("Client-Date" => HTTP::Date::time2str(time));
  179. return $response;
  180. }
  181. =item $ua->request($request, $arg [, $size])
  182. Process a request, including redirects and security. This method may
  183. actually send several different simple requests.
  184. The arguments are the same as for C<simple_request()>.
  185. =cut
  186. sub request
  187. {
  188. my($self, $request, $arg, $size, $previous) = @_;
  189. LWP::Debug::trace('()');
  190. my $response = $self->simple_request($request, $arg, $size);
  191. my $code = $response->code;
  192. $response->previous($previous) if defined $previous;
  193. LWP::Debug::debug('Simple response: ' .
  194. (HTTP::Status::status_message($code) ||
  195. "Unknown code $code"));
  196. if ($code == &HTTP::Status::RC_MOVED_PERMANENTLY or
  197. $code == &HTTP::Status::RC_MOVED_TEMPORARILY) {
  198. # Make a copy of the request and initialize it with the new URI
  199. my $referral = $request->clone;
  200. # And then we update the URL based on the Location:-header.
  201. my $referral_uri = $response->header('Location');
  202. {
  203. # Some servers erroneously return a relative URL for redirects,
  204. # so make it absolute if it not already is.
  205. local $URI::ABS_ALLOW_RELATIVE_SCHEME = 1;
  206. my $base = $response->base;
  207. $referral_uri = $HTTP::URI_CLASS->new($referral_uri, $base)
  208. ->abs($base);
  209. }
  210. $referral->url($referral_uri);
  211. return $response unless $self->redirect_ok($referral);
  212. # Check for loop in the redirects
  213. my $count = 0;
  214. my $r = $response;
  215. while ($r) {
  216. if (++$count > 13 ||
  217. $r->request->url->as_string eq $referral_uri->as_string) {
  218. $response->header("Client-Warning" =>
  219. "Redirect loop detected");
  220. return $response;
  221. }
  222. $r = $r->previous;
  223. }
  224. return $self->request($referral, $arg, $size, $response);
  225. } elsif ($code == &HTTP::Status::RC_UNAUTHORIZED ||
  226. $code == &HTTP::Status::RC_PROXY_AUTHENTICATION_REQUIRED
  227. )
  228. {
  229. my $proxy = ($code == &HTTP::Status::RC_PROXY_AUTHENTICATION_REQUIRED);
  230. my $ch_header = $proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  231. my @challenge = $response->header($ch_header);
  232. unless (@challenge) {
  233. $response->header("Client-Warning" =>
  234. "Missing Authenticate header");
  235. return $response;
  236. }
  237. require HTTP::Headers::Util;
  238. CHALLENGE: for my $challenge (@challenge) {
  239. $challenge =~ tr/,/;/; # "," is used to separate auth-params!!
  240. ($challenge) = HTTP::Headers::Util::split_header_words($challenge);
  241. my $scheme = lc(shift(@$challenge));
  242. shift(@$challenge); # no value
  243. $challenge = { @$challenge }; # make rest into a hash
  244. for (keys %$challenge) { # make sure all keys are lower case
  245. $challenge->{lc $_} = delete $challenge->{$_};
  246. }
  247. unless ($scheme =~ /^([a-z]+(?:-[a-z]+)*)$/) {
  248. $response->header("Client-Warning" =>
  249. "Bad authentication scheme '$scheme'");
  250. return $response;
  251. }
  252. $scheme = $1; # untainted now
  253. my $class = "LWP::Authen::\u$scheme";
  254. $class =~ s/-/_/g;
  255. no strict 'refs';
  256. unless (%{"$class\::"}) {
  257. # try to load it
  258. eval "require $class";
  259. if ($@) {
  260. if ($@ =~ /^Can\'t locate/) {
  261. $response->header("Client-Warning" =>
  262. "Unsupported authentication scheme '$scheme'");
  263. } else {
  264. $response->header("Client-Warning" => $@);
  265. }
  266. next CHALLENGE;
  267. }
  268. }
  269. return $class->authenticate($self, $proxy, $challenge, $response,
  270. $request, $arg, $size);
  271. }
  272. return $response;
  273. }
  274. return $response;
  275. }
  276. =item $ua->redirect_ok
  277. This method is called by request() before it tries to do any
  278. redirects. It should return a true value if a redirect is allowed
  279. to be performed. Subclasses might want to override this.
  280. The default implementation will return FALSE for POST request and TRUE
  281. for all others.
  282. =cut
  283. sub redirect_ok
  284. {
  285. # draft-ietf-http-v10-spec-02.ps from www.ics.uci.edu, specify:
  286. #
  287. # If the 30[12] status code is received in response to a request using
  288. # the POST method, the user agent must not automatically redirect the
  289. # request unless it can be confirmed by the user, since this might change
  290. # the conditions under which the request was issued.
  291. my($self, $request) = @_;
  292. return 0 if $request->method eq "POST";
  293. 1;
  294. }
  295. =item $ua->credentials($netloc, $realm, $uname, $pass)
  296. Set the user name and password to be used for a realm. It is often more
  297. useful to specialize the get_basic_credentials() method instead.
  298. =cut
  299. sub credentials
  300. {
  301. my($self, $netloc, $realm, $uid, $pass) = @_;
  302. @{ $self->{'basic_authentication'}{$netloc}{$realm} } = ($uid, $pass);
  303. }
  304. =item $ua->get_basic_credentials($realm, $uri, [$proxy])
  305. This is called by request() to retrieve credentials for a Realm
  306. protected by Basic Authentication or Digest Authentication.
  307. Should return username and password in a list. Return undef to abort
  308. the authentication resolution atempts.
  309. This implementation simply checks a set of pre-stored member
  310. variables. Subclasses can override this method to e.g. ask the user
  311. for a username/password. An example of this can be found in
  312. C<lwp-request> program distributed with this library.
  313. =cut
  314. sub get_basic_credentials
  315. {
  316. my($self, $realm, $uri, $proxy) = @_;
  317. return if $proxy;
  318. my $host_port = $uri->host_port;
  319. if (exists $self->{'basic_authentication'}{$host_port}{$realm}) {
  320. return @{ $self->{'basic_authentication'}{$host_port}{$realm} };
  321. }
  322. return (undef, undef);
  323. }
  324. =item $ua->agent([$product_id])
  325. Get/set the product token that is used to identify the user agent on
  326. the network. The agent value is sent as the "User-Agent" header in
  327. the requests. The default agent name is "libwww-perl/#.##", where
  328. "#.##" is substitued with the version numer of this library.
  329. The user agent string should be one or more simple product identifiers
  330. with an optional version number separated by the "/" character.
  331. Examples are:
  332. $ua->agent('Checkbot/0.4 ' . $ua->agent);
  333. $ua->agent('Mozilla/5.0');
  334. =item $ua->from([$email_address])
  335. Get/set the Internet e-mail address for the human user who controls
  336. the requesting user agent. The address should be machine-usable, as
  337. defined in RFC 822. The from value is send as the "From" header in
  338. the requests. There is no default. Example:
  339. $ua->from('[email protected]');
  340. =item $ua->timeout([$secs])
  341. Get/set the timeout value in seconds. The default timeout() value is
  342. 180 seconds, i.e. 3 minutes.
  343. =item $ua->cookie_jar([$cookies])
  344. Get/set the I<HTTP::Cookies> object to use. The default is to have no
  345. cookie_jar, i.e. never automatically add "Cookie" headers to the
  346. requests.
  347. =item $ua->parse_head([$boolean])
  348. Get/set a value indicating wether we should initialize response
  349. headers from the E<lt>head> section of HTML documents. The default is
  350. TRUE. Do not turn this off, unless you know what you are doing.
  351. =item $ua->max_size([$bytes])
  352. Get/set the size limit for response content. The default is undef,
  353. which means that there is no limit. If the returned response content
  354. is only partial, because the size limit was exceeded, then a
  355. "X-Content-Range" header will be added to the response.
  356. =cut
  357. sub timeout { shift->_elem('timeout', @_); }
  358. sub agent { shift->_elem('agent', @_); }
  359. sub from { shift->_elem('from', @_); }
  360. sub cookie_jar { shift->_elem('cookie_jar',@_); }
  361. sub parse_head { shift->_elem('parse_head',@_); }
  362. sub max_size { shift->_elem('max_size', @_); }
  363. # depreciated
  364. sub use_eval { shift->_elem('use_eval', @_); }
  365. sub use_alarm
  366. {
  367. Carp::carp("LWP::UserAgent->use_alarm(BOOL) is a no-op")
  368. if @_ > 1 && $^W;
  369. "";
  370. }
  371. =item $ua->clone;
  372. Returns a copy of the LWP::UserAgent object
  373. =cut
  374. sub clone
  375. {
  376. my $self = shift;
  377. my $copy = bless { %$self }, ref $self; # copy most fields
  378. # elements that are references must be handled in a special way
  379. $copy->{'no_proxy'} = [ @{$self->{'no_proxy'}} ]; # copy array
  380. $copy;
  381. }
  382. =item $ua->is_protocol_supported($scheme)
  383. You can use this method to query if the library currently support the
  384. specified C<scheme>. The C<scheme> might be a string (like 'http' or
  385. 'ftp') or it might be an URI object reference.
  386. =cut
  387. sub is_protocol_supported
  388. {
  389. my($self, $scheme) = @_;
  390. if (ref $scheme) {
  391. # assume we got a reference to an URI object
  392. $scheme = $scheme->scheme;
  393. } else {
  394. Carp::croak("Illegal scheme '$scheme' passed to is_protocol_supported")
  395. if $scheme =~ /\W/;
  396. $scheme = lc $scheme;
  397. }
  398. local($SIG{__DIE__}); # protect agains user defined die handlers
  399. return LWP::Protocol::implementor($scheme);
  400. }
  401. =item $ua->mirror($url, $file)
  402. Get and store a document identified by a URL, using If-Modified-Since,
  403. and checking of the Content-Length. Returns a reference to the
  404. response object.
  405. =cut
  406. sub mirror
  407. {
  408. my($self, $url, $file) = @_;
  409. LWP::Debug::trace('()');
  410. my $request = HTTP::Request->new('GET', $url);
  411. if (-e $file) {
  412. my($mtime) = (stat($file))[9];
  413. if($mtime) {
  414. $request->header('If-Modified-Since' =>
  415. HTTP::Date::time2str($mtime));
  416. }
  417. }
  418. my $tmpfile = "$file-$$";
  419. my $response = $self->request($request, $tmpfile);
  420. if ($response->is_success) {
  421. my $file_length = (stat($tmpfile))[7];
  422. my($content_length) = $response->header('Content-length');
  423. if (defined $content_length and $file_length < $content_length) {
  424. unlink($tmpfile);
  425. die "Transfer truncated: " .
  426. "only $file_length out of $content_length bytes received\n";
  427. } elsif (defined $content_length and $file_length > $content_length) {
  428. unlink($tmpfile);
  429. die "Content-length mismatch: " .
  430. "expected $content_length bytes, got $file_length\n";
  431. } else {
  432. # OK
  433. if (-e $file) {
  434. # Some dosish systems fail to rename if the target exists
  435. chmod 0777, $file;
  436. unlink $file;
  437. }
  438. rename($tmpfile, $file) or
  439. die "Cannot rename '$tmpfile' to '$file': $!\n";
  440. if (my $lm = $response->last_modified) {
  441. # make sure the file has the same last modification time
  442. utime $lm, $lm, $file;
  443. }
  444. }
  445. } else {
  446. unlink($tmpfile);
  447. }
  448. return $response;
  449. }
  450. =item $ua->proxy(...)
  451. Set/retrieve proxy URL for a scheme:
  452. $ua->proxy(['http', 'ftp'], 'http://proxy.sn.no:8001/');
  453. $ua->proxy('gopher', 'http://proxy.sn.no:8001/');
  454. The first form specifies that the URL is to be used for proxying of
  455. access methods listed in the list in the first method argument,
  456. i.e. 'http' and 'ftp'.
  457. The second form shows a shorthand form for specifying
  458. proxy URL for a single access scheme.
  459. =cut
  460. sub proxy
  461. {
  462. my $self = shift;
  463. my $key = shift;
  464. LWP::Debug::trace("$key @_");
  465. return map $self->proxy($_, @_), @$key if ref $key;
  466. my $old = $self->{'proxy'}{$key};
  467. $self->{'proxy'}{$key} = shift if @_;
  468. return $old;
  469. }
  470. =item $ua->env_proxy()
  471. Load proxy settings from *_proxy environment variables. You might
  472. specify proxies like this (sh-syntax):
  473. gopher_proxy=http://proxy.my.place/
  474. wais_proxy=http://proxy.my.place/
  475. no_proxy="localhost,my.domain"
  476. export gopher_proxy wais_proxy no_proxy
  477. Csh or tcsh users should use the C<setenv> command to define these
  478. environment variables.
  479. On systems with case-insensitive environment variables there exists a
  480. name clash between the CGI environment variables and the C<HTTP_PROXY>
  481. environment variable normally picked up by env_proxy(). Because of
  482. this C<HTTP_PROXY> is not honored for CGI scripts. The
  483. C<CGI_HTTP_PROXY> environment variable can be used instead.
  484. =cut
  485. sub env_proxy {
  486. my ($self) = @_;
  487. my($k,$v);
  488. while(($k, $v) = each %ENV) {
  489. if ($ENV{REQUEST_METHOD}) {
  490. # Need to be careful when called in the CGI environment, as
  491. # the HTTP_PROXY variable is under control of that other guy.
  492. next if $k =~ /^HTTP_/;
  493. $k = "HTTP_PROXY" if $k eq "CGI_HTTP_PROXY";
  494. }
  495. $k = lc($k);
  496. next unless $k =~ /^(.*)_proxy$/;
  497. $k = $1;
  498. if ($k eq 'no') {
  499. $self->no_proxy(split(/\s*,\s*/, $v));
  500. }
  501. else {
  502. $self->proxy($k, $v);
  503. }
  504. }
  505. }
  506. =item $ua->no_proxy($domain,...)
  507. Do not proxy requests to the given domains. Calling no_proxy without
  508. any domains clears the list of domains. Eg:
  509. $ua->no_proxy('localhost', 'no', ...);
  510. =cut
  511. sub no_proxy {
  512. my($self, @no) = @_;
  513. if (@no) {
  514. push(@{ $self->{'no_proxy'} }, @no);
  515. }
  516. else {
  517. $self->{'no_proxy'} = [];
  518. }
  519. }
  520. # Private method which returns the URL of the Proxy configured for this
  521. # URL, or undefined if none is configured.
  522. sub _need_proxy
  523. {
  524. my($self, $url) = @_;
  525. $url = $HTTP::URI_CLASS->new($url) unless ref $url;
  526. my $scheme = $url->scheme || return;
  527. if (my $proxy = $self->{'proxy'}{$scheme}) {
  528. if (@{ $self->{'no_proxy'} }) {
  529. if (my $host = eval { $url->host }) {
  530. for my $domain (@{ $self->{'no_proxy'} }) {
  531. if ($host =~ /\Q$domain\E$/) {
  532. LWP::Debug::trace("no_proxy configured");
  533. return;
  534. }
  535. }
  536. }
  537. }
  538. LWP::Debug::debug("Proxied to $proxy");
  539. return $HTTP::URI_CLASS->new($proxy);
  540. }
  541. LWP::Debug::debug('Not proxied');
  542. undef;
  543. }
  544. 1;
  545. =back
  546. =head1 SEE ALSO
  547. See L<LWP> for a complete overview of libwww-perl5. See F<lwp-request> and
  548. F<lwp-mirror> for examples of usage.
  549. =head1 COPYRIGHT
  550. Copyright 1995-2000 Gisle Aas.
  551. This library is free software; you can redistribute it and/or
  552. modify it under the same terms as Perl itself.
  553. =cut