home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / share / perl5 / HTTP / Response.pm < prev    next >
Encoding:
Perl POD Document  |  2010-05-13  |  16.1 KB  |  642 lines

  1. package HTTP::Response;
  2.  
  3. require HTTP::Message;
  4. @ISA = qw(HTTP::Message);
  5. $VERSION = "5.836";
  6.  
  7. use strict;
  8. use HTTP::Status ();
  9.  
  10.  
  11.  
  12. sub new
  13. {
  14.     my($class, $rc, $msg, $header, $content) = @_;
  15.     my $self = $class->SUPER::new($header, $content);
  16.     $self->code($rc);
  17.     $self->message($msg);
  18.     $self;
  19. }
  20.  
  21.  
  22. sub parse
  23. {
  24.     my($class, $str) = @_;
  25.     my $status_line;
  26.     if ($str =~ s/^(.*)\n//) {
  27.     $status_line = $1;
  28.     }
  29.     else {
  30.     $status_line = $str;
  31.     $str = "";
  32.     }
  33.  
  34.     my $self = $class->SUPER::parse($str);
  35.     my($protocol, $code, $message);
  36.     if ($status_line =~ /^\d{3} /) {
  37.        # Looks like a response created by HTTP::Response->new
  38.        ($code, $message) = split(' ', $status_line, 2);
  39.     } else {
  40.        ($protocol, $code, $message) = split(' ', $status_line, 3);
  41.     }
  42.     $self->protocol($protocol) if $protocol;
  43.     $self->code($code) if defined($code);
  44.     $self->message($message) if defined($message);
  45.     $self;
  46. }
  47.  
  48.  
  49. sub clone
  50. {
  51.     my $self = shift;
  52.     my $clone = bless $self->SUPER::clone, ref($self);
  53.     $clone->code($self->code);
  54.     $clone->message($self->message);
  55.     $clone->request($self->request->clone) if $self->request;
  56.     # we don't clone previous
  57.     $clone;
  58. }
  59.  
  60.  
  61. sub code      { shift->_elem('_rc',      @_); }
  62. sub message   { shift->_elem('_msg',     @_); }
  63. sub previous  { shift->_elem('_previous',@_); }
  64. sub request   { shift->_elem('_request', @_); }
  65.  
  66.  
  67. sub status_line
  68. {
  69.     my $self = shift;
  70.     my $code = $self->{'_rc'}  || "000";
  71.     my $mess = $self->{'_msg'} || HTTP::Status::status_message($code) || "Unknown code";
  72.     return "$code $mess";
  73. }
  74.  
  75.  
  76. sub base
  77. {
  78.     my $self = shift;
  79.     my $base = (
  80.     $self->header('Content-Base'),        # used to be HTTP/1.1
  81.     $self->header('Content-Location'),    # HTTP/1.1
  82.     $self->header('Base'),                # HTTP/1.0
  83.     )[0];
  84.     if ($base && $base =~ /^$URI::scheme_re:/o) {
  85.     # already absolute
  86.     return $HTTP::URI_CLASS->new($base);
  87.     }
  88.  
  89.     my $req = $self->request;
  90.     if ($req) {
  91.         # if $base is undef here, the return value is effectively
  92.         # just a copy of $self->request->uri.
  93.         return $HTTP::URI_CLASS->new_abs($base, $req->uri);
  94.     }
  95.  
  96.     # can't find an absolute base
  97.     return undef;
  98. }
  99.  
  100.  
  101. sub redirects {
  102.     my $self = shift;
  103.     my @r;
  104.     my $r = $self;
  105.     while (my $p = $r->previous) {
  106.         push(@r, $p);
  107.         $r = $p;
  108.     }
  109.     return @r unless wantarray;
  110.     return reverse @r;
  111. }
  112.  
  113.  
  114. sub filename
  115. {
  116.     my $self = shift;
  117.     my $file;
  118.  
  119.     my $cd = $self->header('Content-Disposition');
  120.     if ($cd) {
  121.     require HTTP::Headers::Util;
  122.     if (my @cd = HTTP::Headers::Util::split_header_words($cd)) {
  123.         my ($disposition, undef, %cd_param) = @{$cd[-1]};
  124.         $file = $cd_param{filename};
  125.  
  126.         # RFC 2047 encoded?
  127.         if ($file && $file =~ /^=\?(.+?)\?(.+?)\?(.+)\?=$/) {
  128.         my $charset = $1;
  129.         my $encoding = uc($2);
  130.         my $encfile = $3;
  131.  
  132.         if ($encoding eq 'Q' || $encoding eq 'B') {
  133.             local($SIG{__DIE__});
  134.             eval {
  135.             if ($encoding eq 'Q') {
  136.                 $encfile =~ s/_/ /g;
  137.                 require MIME::QuotedPrint;
  138.                 $encfile = MIME::QuotedPrint::decode($encfile);
  139.             }
  140.             else { # $encoding eq 'B'
  141.                 require MIME::Base64;
  142.                 $encfile = MIME::Base64::decode($encfile);
  143.             }
  144.  
  145.             require Encode;
  146.             require encoding;
  147.             # This is ugly use of non-public API, but is there
  148.             # a better way to accomplish what we want (locally
  149.             # as-is usable filename string)?
  150.             my $locale_charset = encoding::_get_locale_encoding();
  151.             Encode::from_to($encfile, $charset, $locale_charset);
  152.             };
  153.  
  154.             $file = $encfile unless $@;
  155.         }
  156.         }
  157.     }
  158.     }
  159.  
  160.     unless (defined($file) && length($file)) {
  161.     my $uri;
  162.     if (my $cl = $self->header('Content-Location')) {
  163.         $uri = URI->new($cl);
  164.     }
  165.     elsif (my $request = $self->request) {
  166.         $uri = $request->uri;
  167.     }
  168.  
  169.     if ($uri) {
  170.         $file = ($uri->path_segments)[-1];
  171.     }
  172.     }
  173.  
  174.     if ($file) {
  175.     $file =~ s,.*[\\/],,;  # basename
  176.     }
  177.  
  178.     if ($file && !length($file)) {
  179.     $file = undef;
  180.     }
  181.  
  182.     $file;
  183. }
  184.  
  185.  
  186. sub as_string
  187. {
  188.     require HTTP::Status;
  189.     my $self = shift;
  190.     my($eol) = @_;
  191.     $eol = "\n" unless defined $eol;
  192.  
  193.     my $status_line = $self->status_line;
  194.     my $proto = $self->protocol;
  195.     $status_line = "$proto $status_line" if $proto;
  196.  
  197.     return join($eol, $status_line, $self->SUPER::as_string(@_));
  198. }
  199.  
  200.  
  201. sub dump
  202. {
  203.     my $self = shift;
  204.  
  205.     my $status_line = $self->status_line;
  206.     my $proto = $self->protocol;
  207.     $status_line = "$proto $status_line" if $proto;
  208.  
  209.     return $self->SUPER::dump(
  210.     preheader => $status_line,
  211.         @_,
  212.     );
  213. }
  214.  
  215.  
  216. sub is_info     { HTTP::Status::is_info     (shift->{'_rc'}); }
  217. sub is_success  { HTTP::Status::is_success  (shift->{'_rc'}); }
  218. sub is_redirect { HTTP::Status::is_redirect (shift->{'_rc'}); }
  219. sub is_error    { HTTP::Status::is_error    (shift->{'_rc'}); }
  220.  
  221.  
  222. sub error_as_HTML
  223. {
  224.     require HTML::Entities;
  225.     my $self = shift;
  226.     my $title = 'An Error Occurred';
  227.     my $body  = HTML::Entities::encode($self->status_line);
  228.     return <<EOM;
  229. <html>
  230. <head><title>$title</title></head>
  231. <body>
  232. <h1>$title</h1>
  233. <p>$body</p>
  234. </body>
  235. </html>
  236. EOM
  237. }
  238.  
  239.  
  240. sub current_age
  241. {
  242.     my $self = shift;
  243.     my $time = shift;
  244.  
  245.     # Implementation of RFC 2616 section 13.2.3
  246.     # (age calculations)
  247.     my $response_time = $self->client_date;
  248.     my $date = $self->date;
  249.  
  250.     my $age = 0;
  251.     if ($response_time && $date) {
  252.     $age = $response_time - $date;  # apparent_age
  253.     $age = 0 if $age < 0;
  254.     }
  255.  
  256.     my $age_v = $self->header('Age');
  257.     if ($age_v && $age_v > $age) {
  258.     $age = $age_v;   # corrected_received_age
  259.     }
  260.  
  261.     if ($response_time) {
  262.     my $request = $self->request;
  263.     if ($request) {
  264.         my $request_time = $request->date;
  265.         if ($request_time && $request_time < $response_time) {
  266.         # Add response_delay to age to get 'corrected_initial_age'
  267.         $age += $response_time - $request_time;
  268.         }
  269.     }
  270.     $age += ($time || time) - $response_time;
  271.     }
  272.     return $age;
  273. }
  274.  
  275.  
  276. sub freshness_lifetime
  277. {
  278.     my($self, %opt) = @_;
  279.  
  280.     # First look for the Cache-Control: max-age=n header
  281.     for my $cc ($self->header('Cache-Control')) {
  282.     for my $cc_dir (split(/\s*,\s*/, $cc)) {
  283.         return $1 if $cc_dir =~ /^max-age\s*=\s*(\d+)/i;
  284.     }
  285.     }
  286.  
  287.     # Next possibility is to look at the "Expires" header
  288.     my $date = $self->date || $self->client_date || $opt{time} || time;
  289.     if (my $expires = $self->expires) {
  290.     return $expires - $date;
  291.     }
  292.  
  293.     # Must apply heuristic expiration
  294.     return undef if exists $opt{heuristic_expiry} && !$opt{heuristic_expiry};
  295.  
  296.     # Default heuristic expiration parameters
  297.     $opt{h_min} ||= 60;
  298.     $opt{h_max} ||= 24 * 3600;
  299.     $opt{h_lastmod_fraction} ||= 0.10; # 10% since last-mod suggested by RFC2616
  300.     $opt{h_default} ||= 3600;
  301.  
  302.     # Should give a warning if more than 24 hours according to
  303.     # RFC 2616 section 13.2.4.  Here we just make this the default
  304.     # maximum value.
  305.  
  306.     if (my $last_modified = $self->last_modified) {
  307.     my $h_exp = ($date - $last_modified) * $opt{h_lastmod_fraction};
  308.     return $opt{h_min} if $h_exp < $opt{h_min};
  309.     return $opt{h_max} if $h_exp > $opt{h_max};
  310.     return $h_exp;
  311.     }
  312.  
  313.     # default when all else fails
  314.     return $opt{h_min} if $opt{h_min} > $opt{h_default};
  315.     return $opt{h_default};
  316. }
  317.  
  318.  
  319. sub is_fresh
  320. {
  321.     my($self, %opt) = @_;
  322.     $opt{time} ||= time;
  323.     my $f = $self->freshness_lifetime(%opt);
  324.     return undef unless defined($f);
  325.     return $f > $self->current_age($opt{time});
  326. }
  327.  
  328.  
  329. sub fresh_until
  330. {
  331.     my($self, %opt) = @_;
  332.     $opt{time} ||= time;
  333.     my $f = $self->freshness_lifetime(%opt);
  334.     return undef unless defined($f);
  335.     return $f - $self->current_age($opt{time}) + $opt{time};
  336. }
  337.  
  338. 1;
  339.  
  340.  
  341. __END__
  342.  
  343. =head1 NAME
  344.  
  345. HTTP::Response - HTTP style response message
  346.  
  347. =head1 SYNOPSIS
  348.  
  349. Response objects are returned by the request() method of the C<LWP::UserAgent>:
  350.  
  351.     # ...
  352.     $response = $ua->request($request)
  353.     if ($response->is_success) {
  354.         print $response->decoded_content;
  355.     }
  356.     else {
  357.         print STDERR $response->status_line, "\n";
  358.     }
  359.  
  360. =head1 DESCRIPTION
  361.  
  362. The C<HTTP::Response> class encapsulates HTTP style responses.  A
  363. response consists of a response line, some headers, and a content
  364. body. Note that the LWP library uses HTTP style responses even for
  365. non-HTTP protocol schemes.  Instances of this class are usually
  366. created and returned by the request() method of an C<LWP::UserAgent>
  367. object.
  368.  
  369. C<HTTP::Response> is a subclass of C<HTTP::Message> and therefore
  370. inherits its methods.  The following additional methods are available:
  371.  
  372. =over 4
  373.  
  374. =item $r = HTTP::Response->new( $code )
  375.  
  376. =item $r = HTTP::Response->new( $code, $msg )
  377.  
  378. =item $r = HTTP::Response->new( $code, $msg, $header )
  379.  
  380. =item $r = HTTP::Response->new( $code, $msg, $header, $content )
  381.  
  382. Constructs a new C<HTTP::Response> object describing a response with
  383. response code $code and optional message $msg.  The optional $header
  384. argument should be a reference to an C<HTTP::Headers> object or a
  385. plain array reference of key/value pairs.  The optional $content
  386. argument should be a string of bytes.  The meaning these arguments are
  387. described below.
  388.  
  389. =item $r = HTTP::Response->parse( $str )
  390.  
  391. This constructs a new response object by parsing the given string.
  392.  
  393. =item $r->code
  394.  
  395. =item $r->code( $code )
  396.  
  397. This is used to get/set the code attribute.  The code is a 3 digit
  398. number that encode the overall outcome of a HTTP response.  The
  399. C<HTTP::Status> module provide constants that provide mnemonic names
  400. for the code attribute.
  401.  
  402. =item $r->message
  403.  
  404. =item $r->message( $message )
  405.  
  406. This is used to get/set the message attribute.  The message is a short
  407. human readable single line string that explains the response code.
  408.  
  409. =item $r->header( $field )
  410.  
  411. =item $r->header( $field => $value )
  412.  
  413. This is used to get/set header values and it is inherited from
  414. C<HTTP::Headers> via C<HTTP::Message>.  See L<HTTP::Headers> for
  415. details and other similar methods that can be used to access the
  416. headers.
  417.  
  418. =item $r->content
  419.  
  420. =item $r->content( $bytes )
  421.  
  422. This is used to get/set the raw content and it is inherited from the
  423. C<HTTP::Message> base class.  See L<HTTP::Message> for details and
  424. other methods that can be used to access the content.
  425.  
  426. =item $r->decoded_content( %options )
  427.  
  428. This will return the content after any C<Content-Encoding> and
  429. charsets have been decoded.  See L<HTTP::Message> for details.
  430.  
  431. =item $r->request
  432.  
  433. =item $r->request( $request )
  434.  
  435. This is used to get/set the request attribute.  The request attribute
  436. is a reference to the the request that caused this response.  It does
  437. not have to be the same request passed to the $ua->request() method,
  438. because there might have been redirects and authorization retries in
  439. between.
  440.  
  441. =item $r->previous
  442.  
  443. =item $r->previous( $response )
  444.  
  445. This is used to get/set the previous attribute.  The previous
  446. attribute is used to link together chains of responses.  You get
  447. chains of responses if the first response is redirect or unauthorized.
  448. The value is C<undef> if this is the first response in a chain.
  449.  
  450. Note that the method $r->redirects is provided as a more convenient
  451. way to access the response chain.
  452.  
  453. =item $r->status_line
  454.  
  455. Returns the string "E<lt>code> E<lt>message>".  If the message attribute
  456. is not set then the official name of E<lt>code> (see L<HTTP::Status>)
  457. is substituted.
  458.  
  459. =item $r->base
  460.  
  461. Returns the base URI for this response.  The return value will be a
  462. reference to a URI object.
  463.  
  464. The base URI is obtained from one the following sources (in priority
  465. order):
  466.  
  467. =over 4
  468.  
  469. =item 1.
  470.  
  471. Embedded in the document content, for instance <BASE HREF="...">
  472. in HTML documents.
  473.  
  474. =item 2.
  475.  
  476. A "Content-Base:" or a "Content-Location:" header in the response.
  477.  
  478. For backwards compatibility with older HTTP implementations we will
  479. also look for the "Base:" header.
  480.  
  481. =item 3.
  482.  
  483. The URI used to request this response. This might not be the original
  484. URI that was passed to $ua->request() method, because we might have
  485. received some redirect responses first.
  486.  
  487. =back
  488.  
  489. If none of these sources provide an absolute URI, undef is returned.
  490.  
  491. When the LWP protocol modules produce the HTTP::Response object, then
  492. any base URI embedded in the document (step 1) will already have
  493. initialized the "Content-Base:" header. This means that this method
  494. only performs the last 2 steps (the content is not always available
  495. either).
  496.  
  497. =item $r->filename
  498.  
  499. Returns a filename for this response.  Note that doing sanity checks
  500. on the returned filename (eg. removing characters that cannot be used
  501. on the target filesystem where the filename would be used, and
  502. laundering it for security purposes) are the caller's responsibility;
  503. the only related thing done by this method is that it makes a simple
  504. attempt to return a plain filename with no preceding path segments.
  505.  
  506. The filename is obtained from one the following sources (in priority
  507. order):
  508.  
  509. =over 4
  510.  
  511. =item 1.
  512.  
  513. A "Content-Disposition:" header in the response.  Proper decoding of
  514. RFC 2047 encoded filenames requires the C<MIME::QuotedPrint> (for "Q"
  515. encoding), C<MIME::Base64> (for "B" encoding), and C<Encode> modules.
  516.  
  517. =item 2.
  518.  
  519. A "Content-Location:" header in the response.
  520.  
  521. =item 3.
  522.  
  523. The URI used to request this response. This might not be the original
  524. URI that was passed to $ua->request() method, because we might have
  525. received some redirect responses first.
  526.  
  527. =back
  528.  
  529. If a filename cannot be derived from any of these sources, undef is
  530. returned.
  531.  
  532. =item $r->as_string
  533.  
  534. =item $r->as_string( $eol )
  535.  
  536. Returns a textual representation of the response.
  537.  
  538. =item $r->is_info
  539.  
  540. =item $r->is_success
  541.  
  542. =item $r->is_redirect
  543.  
  544. =item $r->is_error
  545.  
  546. These methods indicate if the response was informational, successful, a
  547. redirection, or an error.  See L<HTTP::Status> for the meaning of these.
  548.  
  549. =item $r->error_as_HTML
  550.  
  551. Returns a string containing a complete HTML document indicating what
  552. error occurred.  This method should only be called when $r->is_error
  553. is TRUE.
  554.  
  555. =item $r->redirects
  556.  
  557. Returns the list of redirect responses that lead up to this response
  558. by following the $r->previous chain.  The list order is oldest first.
  559.  
  560. In scalar context return the number of redirect responses leading up
  561. to this one.
  562.  
  563. =item $r->current_age
  564.  
  565. Calculates the "current age" of the response as specified by RFC 2616
  566. section 13.2.3.  The age of a response is the time since it was sent
  567. by the origin server.  The returned value is a number representing the
  568. age in seconds.
  569.  
  570. =item $r->freshness_lifetime( %opt )
  571.  
  572. Calculates the "freshness lifetime" of the response as specified by
  573. RFC 2616 section 13.2.4.  The "freshness lifetime" is the length of
  574. time between the generation of a response and its expiration time.
  575. The returned value is the number of seconds until expiry.
  576.  
  577. If the response does not contain an "Expires" or a "Cache-Control"
  578. header, then this function will apply some simple heuristic based on
  579. the "Last-Modified" header to determine a suitable lifetime.  The
  580. following options might be passed to control the heuristics:
  581.  
  582. =over
  583.  
  584. =item heuristic_expiry => $bool
  585.  
  586. If passed as a FALSE value, don't apply heuristics and just return
  587. C<undef> when "Expires" or "Cache-Control" is lacking.
  588.  
  589. =item h_lastmod_fraction => $num
  590.  
  591. This number represent the fraction of the difference since the
  592. "Last-Modified" timestamp to make the expiry time.  The default is
  593. C<0.10>, the suggested typical setting of 10% in RFC 2616.
  594.  
  595. =item h_min => $sec
  596.  
  597. This is the lower limit of the heuristic expiry age to use.  The
  598. default is C<60> (1 minute).
  599.  
  600. =item h_max => $sec
  601.  
  602. This is the upper limit of the heuristic expiry age to use.  The
  603. default is C<86400> (24 hours).
  604.  
  605. =item h_default => $sec
  606.  
  607. This is the expiry age to use when nothing else applies.  The default
  608. is C<3600> (1 hour) or "h_min" if greater.
  609.  
  610. =back
  611.  
  612. =item $r->is_fresh( %opt )
  613.  
  614. Returns TRUE if the response is fresh, based on the values of
  615. freshness_lifetime() and current_age().  If the response is no longer
  616. fresh, then it has to be re-fetched or re-validated by the origin
  617. server.
  618.  
  619. Options might be passed to control expiry heuristics, see the
  620. description of freshness_lifetime().
  621.  
  622. =item $r->fresh_until( %opt )
  623.  
  624. Returns the time (seconds since epoch) when this entity is no longer fresh.
  625.  
  626. Options might be passed to control expiry heuristics, see the
  627. description of freshness_lifetime().
  628.  
  629. =back
  630.  
  631. =head1 SEE ALSO
  632.  
  633. L<HTTP::Headers>, L<HTTP::Message>, L<HTTP::Status>, L<HTTP::Request>
  634.  
  635. =head1 COPYRIGHT
  636.  
  637. Copyright 1995-2004 Gisle Aas.
  638.  
  639. This library is free software; you can redistribute it and/or
  640. modify it under the same terms as Perl itself.
  641.  
  642.