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.

541 lines
16 KiB

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