home *** CD-ROM | disk | FTP | other *** search
/ Acorn User 10 / AU_CD10.iso / Updates / Perl / Perl_Libs / site_perl / HTTP / Headers.pm < prev    next >
Text File  |  1997-12-10  |  15KB  |  538 lines

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