home *** CD-ROM | disk | FTP | other *** search
/ CLIX - Fazer Clix Custa Nix / CLIX-CD.cdr / mac / lib / HTTP / Headers.pm < prev    next >
Text File  |  1996-10-01  |  14KB  |  491 lines

  1. #
  2. # $Id: Headers.pm,v 1.26 1996/09/16 12:49:47 aas Exp $
  3.  
  4. package HTTP::Headers;
  5.  
  6. =head1 NAME
  7.  
  8. HTTP::Headers - Class encapsulating HTTP Message headers
  9.  
  10. =head1 SYNOPSIS
  11.  
  12.  require HTTP::Headers;
  13.  $request = new HTTP::Headers;
  14.  
  15. =head1 DESCRIPTION
  16.  
  17. The C<HTTP::Headers> class encapsulates HTTP-style message headers.
  18. The headers consist of attribute-value pairs, which may be repeated,
  19. and which are printed in a particular order.
  20.  
  21. Instances of this class are usually created as member variables of the
  22. C<HTTP::Request> and C<HTTP::Response> classes, internal to the
  23. library.
  24.  
  25. =head1 METHODS
  26.  
  27. =cut
  28.  
  29.  
  30. require Carp;
  31.  
  32. # Could not use the AutoLoader becase several of the method names are
  33. # not unique in the first 8 characters.
  34. #use SelfLoader;
  35.  
  36.  
  37. # "Good Practice" order of HTTP message headers:
  38. #    - General-Headers
  39. #    - Request-Headers
  40. #    - Response-Headers
  41. #    - Entity-Headers
  42. #    - Aditional Headers (ß19.6.2)
  43. # (From draft-ietf-http-v11-spec-06, Jul 4, 1996)
  44.  
  45. my @header_order = qw(
  46.    Cache-Control Connection Date Pragma Transfer-Encoding Upgrade Via
  47.  
  48.    Accept Accept-Charset Accept-Encoding Accept-Language
  49.    Authorization From Host
  50.    If-Modified-Since If-Match If-None-Match If-Range If-Unmodified-Since
  51.    Max-Forwards Proxy-Authorization Range Referer User-Agent
  52.  
  53.    Age Location Proxy-Authenticate Public Retry-After Server Vary
  54.    Warning WWW-Authenticate
  55.  
  56.    Allow Content-Base Content-Encoding Content-Language Content-Length
  57.    Content-Location Content-MD5 Content-Range Content-Type
  58.    ETag Expires Last-Modified
  59.  
  60.    Alternates Content-Version Derived-From Link URI
  61. );
  62.  
  63. # Make alternative representations of @header_order.  This is used
  64. # for sorting and case matching.
  65. my $i = 0;
  66. my %header_order;
  67. my %standard_case;
  68. for (@header_order) {
  69.     my $lc = lc $_;
  70.     $header_order{$lc} = $i++;
  71.     $standard_case{$lc} = $_;
  72. }
  73.  
  74.  
  75.  
  76. =head2 $h = new HTTP::Headers
  77.  
  78. Constructs a new C<HTTP::Headers> object.  You might pass some initial
  79. attribute-value pairs as parameters to the constructor.  I<E.g.>:
  80.  
  81.  $h = new HTTP::Headers
  82.      Date         => 'Thu, 03 Feb 1994 00:00:00 GMT',
  83.      Content_Type => 'text/html; version=3.2',
  84.      Content_Base => 'http://www.sn.no/';
  85.  
  86. =cut
  87.  
  88. sub new
  89. {
  90.     my($class) = shift;
  91.     my $self = bless {
  92.     '_header'   => { },
  93.     }, $class;
  94.  
  95.     $self->header(@_); # set up initial headers
  96.     $self;
  97. }
  98.  
  99.  
  100. =head2 $h->header($field [=> $val],...)
  101.  
  102. Get or set the value of a header.  The header field name is not case
  103. sensitive.  To make the life easier for perl users who wants to avoid
  104. quoting before the => operator, you can use '_' as a synonym for '-'
  105. in header names.
  106.  
  107. The value argument may be a scalar or a reference to a list of
  108. scalars. If the value argument is not defined, then the header is not
  109. modified.
  110.  
  111. The header() method accepts multiple ($field => $value) pairs.
  112.  
  113. The list of previous values for the last $field is returned.  Only the
  114. first header value is returned in scalar context.
  115.  
  116.  $header->header(MIME_Version => '1.0',
  117.          User_Agent   => 'My-Web-Client/0.01');
  118.  $header->header(Accept => "text/html, text/plain, image/*");
  119.  $header->header(Accept => [qw(text/html text/plain image/*)]);
  120.  @accepts = $header->header('Accept');
  121.  
  122. =cut
  123.  
  124. sub header
  125. {
  126.     my $self = shift;
  127.     my($field, $val, @old);
  128.     while (($field, $val) = splice(@_, 0, 2)) {
  129.     @old = $self->_header($field, $val);
  130.     }
  131.     wantarray ? @old : $old[0];
  132. }
  133.  
  134. sub _header
  135. {
  136.     my($self, $field, $val, $push) = @_;
  137.     $field =~ tr/_/-/;  # allow use of '_' as alternative to '-' in fields
  138.  
  139.     # $push is only used interally sub push_header
  140.  
  141.     Carp::croak('Need a field name') unless defined $field;
  142.     Carp::croak('Too many parameters') if @_ > 4;
  143.  
  144.     my $lc_field = lc $field;
  145.     unless(defined $standard_case{$lc_field}) {
  146.     # generate a %stadard_case entry for this field
  147.     $field =~ s/\b(\w)/\u$1/g;
  148.     $standard_case{$lc_field} = $field;
  149.     }
  150.  
  151.     my $this_header = \@{$self->{'_header'}{$lc_field}};
  152.  
  153.     my @old = ();
  154.     if (!$push && defined $this_header) {
  155.     @old = @$this_header;  # save it so we can return it
  156.     }
  157.     if (defined $val) {
  158.     @$this_header = () unless $push;
  159.     if (!ref($val)) {
  160.         # scalar: create list with single value
  161.         push(@$this_header, $val);
  162.     } elsif (ref($val) eq 'ARRAY') {
  163.         # list: copy list
  164.         push(@$this_header, @$val);
  165.     } else {
  166.         Carp::croak("Unexpected field value $val");
  167.     }
  168.     }
  169.     @old;
  170. }
  171.  
  172.  
  173. # Compare function which makes it easy to sort headers in the
  174. # recommended "Good Practice" order.
  175. sub _header_cmp
  176. {
  177.     # Unknown headers are assign a large value so that they are
  178.     # sorted last.  This also helps avoiding a warning from -w
  179.     # about comparing undefined values.
  180.     $header_order{$a} = 999 unless defined $header_order{$a};
  181.     $header_order{$b} = 999 unless defined $header_order{$b};
  182.  
  183.     $header_order{$a} <=> $header_order{$b} || $a cmp $b;
  184. }
  185.  
  186.  
  187. =head2 $h->scan(\&doit)
  188.  
  189. Apply a subroutine to each header in turn.  The callback routine is
  190. called with two parameters; the name of the field and a single value.
  191. If the header has more than one value, then the routine is called once
  192. for each value.  The field name passed to the callback routine has
  193. case as suggested by HTTP Spec, and the headers will be visited in the
  194. recommended "Good Practice" order.
  195.  
  196. =cut
  197.  
  198. sub scan
  199. {
  200.     my($self, $sub) = @_;
  201.     my $field;
  202.     foreach $field (sort _header_cmp keys %{$self->{'_header'}} ) {
  203.     my $list = $self->{'_header'}{$field};
  204.     if (defined $list) {
  205.         my $val;
  206.         for $val (@$list) {
  207.         &$sub($standard_case{$field} || $field, $val);
  208.         }
  209.     }
  210.     }
  211. }
  212.  
  213.  
  214. =head2 $h->as_string([$endl])
  215.  
  216. Return the header fields as a formatted MIME header.  Since it
  217. internally uses the C<scan()> method to build the string, the result
  218. will use case as suggested by HTTP Spec, and it will follow
  219. recommended "Good Practice" of ordering the header fieds.  Long header
  220. values are not folded. 
  221.  
  222. The optional parameter specifies the line ending sequence to use.  The
  223. default is C<"\n">.  Embedded "\n" characters in the header will be
  224. substitued with this line ending sequence.
  225.  
  226. =cut
  227.  
  228. sub as_string
  229. {
  230.     my($self, $endl) = @_;
  231.     $endl = "\n" unless defined $endl;
  232.  
  233.     my @result = ();
  234.     $self->scan(sub {
  235.     my($field, $val) = @_;
  236.     if ($val =~ /\n/) {
  237.         # must handle header values with embedded newlines with care
  238.         $val =~ s/\s+$//;          # trailing newlines and space must go
  239.         $val =~ s/\n\n+/\n/g;      # no empty lines
  240.         $val =~ s/\n([^\040\t])/\n $1/g;  # intial space for continuation
  241.         $val =~ s/\n/$endl/g;      # substitute with requested line ending
  242.     }
  243.     push(@result, "$field: $val");
  244.     });
  245.  
  246.     join($endl, @result, '');
  247. }
  248.  
  249.  
  250. # The remaining functions should autoloaded only when needed
  251.  
  252. # A bug in 5.002gamma makes it risky to have POD text inside the
  253. # autoloaded section of the code, so we keep the documentation before
  254. # the __DATA__ token.
  255.  
  256. =head2 $h->push_header($field, $val)
  257.  
  258. Add a new field value of the specified header.  The header field name
  259. is not case sensitive.  The field need not already have a
  260. value. Previous values for the same field are retained.  The argument
  261. may be a scalar or a reference to a list of scalars.
  262.  
  263.  $header->push_header(Accept => 'image/jpeg');
  264.  
  265. =head2 $h->remove_header($field,...)
  266.  
  267. This function removes the headers with the specified names.
  268.  
  269. =head2 $h->clone
  270.  
  271. Returns a copy of this HTTP::Headers object.
  272.  
  273. =head1 CONVENIENCE METHODS
  274.  
  275. The most frequently used headers can also be accessed through the
  276. following convenience methods.  These methods can both be used to read
  277. and to set the value of a header.  The header value is set if you pass
  278. an argument to the method.  The old header value is always returned.
  279.  
  280. Methods that deal with dates/times always convert their value to system
  281. time (seconds since Jan 1, 1970) and they also expect this kind of
  282. value when the header value is set.
  283.  
  284. =head2 $h->date
  285.  
  286. This header represents the date and time at which the message was
  287. originated. I<E.g.>:
  288.  
  289.   $h->date(time);  # set current date
  290.  
  291. =head2 $h->expires
  292.  
  293. This header gives the date and time after which the entity should be
  294. considered stale.
  295.  
  296. =head2 $h->if_modified_since
  297.  
  298. This header is used to make a request conditional.  If the requested
  299. resource has not been modified since the time specified in this field,
  300. then the server will return a C<"304 Not Modified"> response instead of
  301. the document itself.
  302.  
  303. =head2 $h->last_modified
  304.  
  305. This header indicates the date and time at which the resource was last
  306. modified. I<E.g.>:
  307.  
  308.   # check if document is more than 1 hour old
  309.   if ($h->last_modified < time - 60*60) {
  310.     ...
  311.   }
  312.  
  313. =head2 $h->content_type
  314.  
  315. The Content-Type header field indicates the media type of the message
  316. content. I<E.g.>:
  317.  
  318.   $h->content_type('text/html');
  319.  
  320. The value returned will be converted to lower case, and potential
  321. parameters will be chopped off and returned as a separate value if in
  322. an array context.  This makes it safe to do the following:
  323.  
  324.   if ($h->content_type eq 'text/html') {
  325.      # we enter this place even if the real header value happens to
  326.      # be 'TEXT/HTML; version=3.0'
  327.      ...
  328.   }
  329.  
  330. =head2 $h->content_encoding
  331.  
  332. The Content-Encoding header field is used as a modifier to the
  333. media type.  When present, its value indicates what additional
  334. encoding mechanism has been applied to the resource.
  335.  
  336. =head2 $h->content_length
  337.  
  338. A decimal number indicating the size in bytes of the message content.
  339.  
  340. =head2 $h->title
  341.  
  342. The title of the document.  In libwww-perl this header will be
  343. initialized automatically from the E<lt>TITLE>...E<lt>/TITLE> element
  344. of HTML documents.  I<This header is no longer part of the HTTP
  345. standard.>
  346.  
  347. =head2 $h->user_agent
  348.  
  349. This header field is used in request messages and contains information
  350. about the user agent originating the request.  I<E.g.>:
  351.  
  352.   $h->user_agent('Mozilla/1.2');
  353.  
  354. =head2 $h->server
  355.  
  356. The server header field contains information about the software being
  357. used by the originating server program handling the request.
  358.  
  359. =head2 $h->from
  360.  
  361. This header should contain an Internet e-mail address for the human
  362. user who controls the requesting user agent.  The address should be
  363. machine-usable, as defined by RFC822.  E.g.:
  364.  
  365.   $h->from('Gisle Aas <aas@sn.no>');
  366.  
  367. =head2 $h->referer
  368.  
  369. Used to specify the address (URI) of the document from which the
  370. requested resouce address was obtained.
  371.  
  372. =head2 $h->www_authenticate
  373.  
  374. This header must be included as part of a "401 Unauthorized" response.
  375. The field value consist of a challenge that indicates the
  376. authentication scheme and parameters applicable to the requested URI.
  377.  
  378. =head2 $h->authorization
  379.  
  380. A user agent that wishes to authenticate itself with a server, may do
  381. so by including this header.
  382.  
  383. =head2 $h->authorization_basic
  384.  
  385. This method is used to get or set an authorization header that use the
  386. "Basic Authentication Scheme".  In array context it will return two
  387. values; the user name and the password.  In scalar context it will
  388. return I<"uname:password"> as a single string value.
  389.  
  390. When used to set the header value, it expects two arguments.  I<E.g.>:
  391.  
  392.   $h->authorization_basic($uname, $password);
  393.  
  394. =cut
  395.  
  396. 1;
  397.  
  398. #__DATA__
  399.  
  400. sub clone
  401. {
  402.     my $self = shift;
  403.     my $clone = new HTTP::Headers;
  404.     $self->scan(sub { $clone->push_header(@_);} );
  405.     $clone;
  406. }
  407.  
  408. sub push_header
  409. {
  410.     Carp::croak('Usage: $h->push_header($field, $val)') if @_ != 3;
  411.     shift->_header(@_, 'PUSH');
  412. }
  413.  
  414.  
  415. sub remove_header
  416. {
  417.     my($self, @fields) = @_;
  418.     my $field;
  419.     foreach $field (@fields) {
  420.     $field =~ tr/_/-/;
  421.     delete $self->{'_header'}{lc $field};
  422.     }
  423. }
  424.  
  425. # Convenience access functions
  426.  
  427. sub _date_header
  428. {
  429.     require HTTP::Date;
  430.     my($self, $header, $time) = @_;
  431.     my($old) = $self->_header($header);
  432.     if (defined $time) {
  433.     $self->_header($header, HTTP::Date::time2str($time));
  434.     }
  435.     HTTP::Date::str2time($old);
  436. }
  437.  
  438. sub date              { shift->_date_header('Date',              @_); }
  439. sub expires           { shift->_date_header('Expires',           @_); }
  440. sub if_modified_since { shift->_date_header('If-Modified-Since', @_); }
  441. sub last_modified     { shift->_date_header('Last-Modified',     @_); }
  442.  
  443. # This is used as a private LWP extention.  The Client-Date header is
  444. # added as a timestamp to a response when it has been received.
  445. sub client_date       { shift->_date_header('Client-Date',       @_); }
  446.  
  447. # The retry_after field is dual format (can also be a expressed as
  448. # number of seconds from now), so we don't provide an easy way to
  449. # access it until we have know how both these interfaces can be
  450. # addressed.
  451. #sub retry_after       { shift->_date_header('Retry-After',       @_); }
  452.  
  453. sub content_type      {
  454.   my $ct = (shift->_header('Content-Type', @_))[0];
  455.   return '' unless defined $ct;
  456.   my @ct = split(/\s*;\s*/, lc($ct));
  457.   wantarray ? @ct : $ct[0];
  458. }
  459.  
  460. sub title             { (shift->_header('Title',            @_))[0] }
  461. sub content_encoding  { (shift->_header('Content-Encoding', @_))[0] }
  462. sub content_length    { (shift->_header('Content-Length',   @_))[0] }
  463.  
  464. sub user_agent        { (shift->_header('User-Agent',       @_))[0] }
  465. sub server            { (shift->_header('Server',           @_))[0] }
  466.  
  467. sub from              { (shift->_header('From',             @_))[0] }
  468. sub referer           { (shift->_header('Referer',          @_))[0] }
  469.  
  470. sub www_authenticate  { (shift->_header('WWW-Authenticate', @_))[0] }
  471. sub authorization     { (shift->_header('Authorization',    @_))[0] }
  472.  
  473. sub authorization_basic {
  474.     require MIME::Base64;
  475.     my($self, $user, $passwd) = @_;
  476.     my($old) = $self->_header('Authorization');
  477.     if (defined $user) {
  478.     $passwd = '' unless defined $passwd;
  479.     $self->_header('Authorization',
  480.                'Basic ' . MIME::Base64::encode("$user:$passwd", ''));
  481.     }
  482.     if (defined $old && $old =~ s/^\s*Basic\s+//) {
  483.     my $val = MIME::Base64::decode($old);
  484.     return $val unless wantarray;
  485.     return split(/:/, $val, 2);
  486.     }
  487.     undef;
  488. }
  489.  
  490. 1;
  491.