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.

504 lines
16 KiB

  1. # $Id: Negotiate.pm,v 1.7 1999/03/20 07:37:35 gisle Exp $
  2. #
  3. package HTTP::Negotiate;
  4. $VERSION = sprintf("%d.%02d", q$Revision: 1.7 $ =~ /(\d+)\.(\d+)/);
  5. sub Version { $VERSION; }
  6. require 5.002;
  7. require Exporter;
  8. @ISA = qw(Exporter);
  9. @EXPORT = qw(choose);
  10. require HTTP::Headers;
  11. $DEBUG = 0;
  12. sub choose ($;$)
  13. {
  14. my($variants, $request) = @_;
  15. my(%accept);
  16. unless (defined $request) {
  17. # Create a request object from the CGI envirionment variables
  18. $request = new HTTP::Headers;
  19. $request->header('Accept', $ENV{HTTP_ACCEPT})
  20. if $ENV{HTTP_ACCEPT};
  21. $request->header('Accept-Charset', $ENV{HTTP_ACCEPT_CHARSET})
  22. if $ENV{HTTP_ACCEPT_CHARSET};
  23. $request->header('Accept-Encoding', $ENV{HTTP_ACCEPT_ENCODING})
  24. if $ENV{HTTP_ACCEPT_ENCODING};
  25. $request->header('Accept-Language', $ENV{HTTP_ACCEPT_LANGUAGE})
  26. if $ENV{HTTP_ACCEPT_LANGUAGE};
  27. }
  28. # Get all Accept values from the request. Build a hash initialized
  29. # like this:
  30. #
  31. # %accept = ( type => { 'audio/*' => { q => 0.2, mbx => 20000 },
  32. # 'audio/basic' => { q => 1 },
  33. # },
  34. # language => { 'no' => { q => 1 },
  35. # }
  36. # );
  37. $request->scan(sub {
  38. my($key, $val) = @_;
  39. return unless $key =~ s/^Accept-?//;
  40. my $type = lc $key;
  41. $type = "type" unless length $key;
  42. $val =~ s/\s+//g;
  43. my $name;
  44. for $name (split(/,/, $val)) {
  45. my(%param, $param);
  46. if ($name =~ s/;(.*)//) {
  47. for $param (split(/;/, $1)) {
  48. my ($pk, $pv) = split(/=/, $param, 2);
  49. $param{$pk} = $pv;
  50. }
  51. }
  52. $name = lc $name;
  53. if (defined $param{'q'}) {
  54. $param{'q'} = 1 if $param{'q'} > 1;
  55. $param{'q'} = 0 if $param{'q'} < 0;
  56. } else {
  57. $param{'q'} = 1;
  58. }
  59. $param{'q'} = 1 unless defined $param{'q'};
  60. $accept{$type}{$name} = \%param;
  61. }
  62. });
  63. # Check if any of the variants specify a language. We do this
  64. # because it influence how we treat those without (they default to
  65. # 0.5 instead of 1).
  66. my $any_lang = 0;
  67. for $var (@$variants) {
  68. if ($var->[5]) {
  69. $any_lang = 1;
  70. last;
  71. }
  72. }
  73. if ($DEBUG) {
  74. print "Negotiation parameters in the request\n";
  75. for $type (keys %accept) {
  76. print " $type:\n";
  77. for $name (keys %{$accept{$type}}) {
  78. print " $name\n";
  79. for $pv (keys %{$accept{$type}{$name}}) {
  80. print " $pv = $accept{$type}{$name}{$pv}\n";
  81. }
  82. }
  83. }
  84. }
  85. my @Q = (); # This is where we collect the results of the
  86. # quality calcualtions
  87. # Calculate quality for all the variant's that are available.
  88. for (@$variants) {
  89. my($id, $qs, $ct, $enc, $cs, $lang, $bs) = @$_;
  90. $qs = 1 unless defined $qs;
  91. $bs = 0 unless defined $bs;
  92. if ($DEBUG) {
  93. print "\nEvaluating $id ($ct)\n";
  94. printf " qs = %.3f\n", $qs;
  95. print " enc = $enc\n" if $enc && !ref($enc);
  96. print " enc = @$enc\n" if $enc && ref($enc);
  97. print " cs = $cs\n" if $cs;
  98. print " lang = $lang\n" if $lang;
  99. print " bs = $bs\n" if $bs;
  100. }
  101. # Calculate encoding quality
  102. my $qe = 1;
  103. # If the variant has no assignes Content-Encoding, or if no
  104. # Accept-Encoding field is present, then the value assigned
  105. # is "qe=1". If *all* of the variant's content encoddings
  106. # are listed in the Accept-Encoding field, then the value
  107. # assigned is "qw=1". If *any* of the variant's content
  108. # encodings are not listed in the provided Accept-Encoding
  109. # field, then the value assigned is "qe=0"
  110. if (exists $accept{'encoding'} && $enc) {
  111. my @enc = ref($enc) ? @$enc : ($enc);
  112. for (@enc) {
  113. print "Is encoding $_ accepted? " if $DEBUG;
  114. unless(exists $accept{'encoding'}{$_}) {
  115. print "no\n" if $DEBUG;
  116. $qe = 0;
  117. last;
  118. } else {
  119. print "yes\n" if $DEBUG;
  120. }
  121. }
  122. }
  123. # Calculate charset quality
  124. my $qc = 1;
  125. # If the variant's media-type has not charset parameter,
  126. # or the variant's charset is US-ASCII, or if no Accept-Charset
  127. # field is present, then the value assigned is "qc=1". If the
  128. # variant's charset is listed in the Accept-Charset field,
  129. # then the value assigned is "qc=1. Otherwise, if the variant's
  130. # charset is not listed in the provided Accept-Encoding field,
  131. # then the value assigned is "qc=0".
  132. if (exists $accept{'charset'} && $cs && $cs ne 'us-ascii' ) {
  133. $qc = 0 unless $accept{'charset'}{$cs};
  134. }
  135. # Calculate language quality
  136. my $ql = 1;
  137. if ($lang && exists $accept{'language'}) {
  138. my @lang = ref($lang) ? @$lang : ($lang);
  139. # If any of the variant's content languages are listed
  140. # in the Accept-Language field, the the value assigned is
  141. # the maximus of the "q" paramet values for thos language
  142. # tags.
  143. my $q = undef;
  144. for (@lang) {
  145. next unless exists $accept{'language'}{$_};
  146. my $this_q = $accept{'language'}{$_}{'q'};
  147. $q = $this_q unless defined $q;
  148. $q = $this_q if $this_q > $q;
  149. }
  150. unless (defined $q) {
  151. # If there was no exact match and at least one of
  152. # the Accept-Language field values is a complete
  153. # subtag prefix of the content language tag(s), then
  154. # the "q" parameter value of the largest matching
  155. # prefix is used.
  156. my $selected = undef;
  157. for $al (keys %{ $accept{'language'} }) {
  158. if (substr($lang, 0, length($al)) eq $al) {
  159. $selected = $al unless defined $selected;
  160. $selected = $al if length($al) > length($selected);
  161. }
  162. }
  163. $q = $accept{'language'}{$selected}{'q'} if $selected;
  164. # If none of the variant's content language tags or
  165. # tag prefixes are listed in the provided
  166. # Accept-Language field, then the value assigned
  167. # is "ql=0.001"
  168. $q = 0.001 unless defined $q;
  169. }
  170. $ql = $q;
  171. } else {
  172. $ql = 0.5 if $any_lang && exists $accept{'language'};
  173. }
  174. my $q = 1;
  175. my $mbx = undef;
  176. # If no Accept field is given, then the value assigned is "q=1".
  177. # If at least one listed media range matches the variant's media
  178. # type, then the "q" parameter value assigned to the most specific
  179. # of those matched is used (e.g. "text/html;version=3.0" is more
  180. # specific than "text/html", which is more specific than "text/*",
  181. # which in turn is more specific than "*/*"). If not media range
  182. # in the provided Accept field matches the variant's media type,
  183. # then the value assigned is "q=0".
  184. if (exists $accept{'type'} && $ct) {
  185. # First we clean up our content-type
  186. $ct =~ s/\s+//g;
  187. my $params = "";
  188. $params = $1 if $ct =~ s/;(.*)//;
  189. my($type, $subtype) = split("/", $ct, 2);
  190. my %param = ();
  191. for $param (split(/;/, $params)) {
  192. my($pk,$pv) = split(/=/, $param, 2);
  193. $param{$pk} = $pv;
  194. }
  195. my $sel_q = undef;
  196. my $sel_mbx = undef;
  197. my $sel_specificness = 0;
  198. ACCEPT_TYPE:
  199. for $at (keys %{ $accept{'type'} }) {
  200. print "Consider $at...\n" if $DEBUG;
  201. my($at_type, $at_subtype) = split("/", $at, 2);
  202. # Is it a match on the type
  203. next if $at_type ne '*' && $at_type ne $type;
  204. next if $at_subtype ne '*' && $at_subtype ne $subtype;
  205. my $specificness = 0;
  206. $specificness++ if $at_type ne '*';
  207. $specificness++ if $at_subtype ne '*';
  208. # Let's see if content-type parameters also match
  209. while (($pk, $pv) = each %param) {
  210. print "Check if $pk = $pv is true\n" if $DEBUG;
  211. next unless exists $accept{'type'}{$at}{$pk};
  212. next ACCEPT_TYPE
  213. unless $accept{'type'}{$at}{$pk} eq $pv;
  214. print "yes it is!!\n" if $DEBUG;
  215. $specificness++;
  216. }
  217. print "Hurray, type match with specificness = $specificness\n"
  218. if $DEBUG;
  219. if (!defined($sel_q) || $sel_specificness < $specificness) {
  220. $sel_q = $accept{'type'}{$at}{'q'};
  221. $sel_mbx = $accept{'type'}{$at}{'mbx'};
  222. $sel_specificness = $specificness;
  223. }
  224. }
  225. $q = $sel_q || 0;
  226. $mbx = $sel_mbx;
  227. }
  228. my $Q;
  229. if (!defined($mbx) || $mbx >= $bs) {
  230. $Q = $qs * $qe * $qc * $ql * $q;
  231. } else {
  232. $Q = 0;
  233. print "Variant's size is too large ==> Q=0\n" if $DEBUG;
  234. }
  235. if ($DEBUG) {
  236. $mbx = "undef" unless defined $mbx;
  237. printf "Q=%.3f", $Q;
  238. print " (q=$q, mbx=$mbx, qe=$qe, qc=$qc, ql=$ql, qs=$qs)\n";
  239. }
  240. push(@Q, [$id, $Q, $bs]);
  241. }
  242. @Q = sort { $b->[1] <=> $a->[1] || $a->[2] <=> $b->[2] } @Q;
  243. return @Q if wantarray;
  244. return undef unless @Q;
  245. return undef if $Q[0][1] == 0;
  246. $Q[0][0];
  247. }
  248. 1;
  249. __END__
  250. =head1 NAME
  251. choose - choose a variant of a document to serve (HTTP content negotiation)
  252. =head1 SYNOPSIS
  253. use HTTP::Negotiate;
  254. # ID QS Content-Type Encoding Char-Set Lang Size
  255. $variants =
  256. [['var1', 1.000, 'text/html', undef, 'iso-8859-1', 'en', 3000],
  257. ['var2', 0.950, 'text/plain', 'gzip', 'us-ascii', 'no', 400],
  258. ['var3', 0.3, 'image/gif', undef, undef, undef, 43555],
  259. ];
  260. @prefered = choose($variants, $request_headers);
  261. $the_one = choose($variants);
  262. =head1 DESCRIPTION
  263. This module provides a complete implementation of the HTTP content
  264. negotiation algorithm specified in F<draft-ietf-http-v11-spec-00.ps>
  265. chapter 12. Content negotiation allows for the selection of a
  266. preferred content representation based upon attributes of the
  267. negotiable variants and the value of the various Accept* header fields
  268. in the request.
  269. The variants are ordered by preference by calling the function
  270. choose().
  271. The first parameter is reference to an array of the variants to
  272. choose among.
  273. Each element in this array is an array with the values [$id, $qs,
  274. $content_type, $content_encoding, $charset, $content_language,
  275. $content_length] whose meanings are described
  276. below. The $content_encoding and $content_language can be either a
  277. single scalar value or an array reference if there are several values.
  278. The second optional parameter is either a HTTP::Headers or a HTTP::Request
  279. object which is searched for "Accept*" headers. If this
  280. parameter is missing, then the accept specification is initialized
  281. from the CGI environment variables HTTP_ACCEPT, HTTP_ACCEPT_CHARSET,
  282. HTTP_ACCEPT_ENCODING and HTTP_ACCEPT_LANGUAGE.
  283. In an array context, choose() returns a list of variant
  284. identifier/calculated quality pairs. The values are sorted by
  285. quality, highest quality first. If the calculated quality is the same
  286. for two variants, then they are sorted by size (smallest first). I<E.g.>:
  287. (['var1' => 1], ['var2', 0.3], ['var3' => 0]);
  288. Note that also zero quality variants are included in the return list
  289. even if these should never be served to the client.
  290. In a scalar context, it returns the identifier of the variant with the
  291. highest score or C<undef> if none have non-zero quality.
  292. If the $HTTP::Negotiate::DEBUG variable is set to TRUE, then a lot of
  293. noise is generated on STDOUT during evaluation of choose().
  294. =head1 VARIANTS
  295. A variant is described by a list of the following values. If the
  296. attribute does not make sense or is unknown for a variant, then use
  297. C<undef> instead.
  298. =over 3
  299. =item identifier
  300. This is a string that you use as the name for the variant. This
  301. identifier for the preferred variants returned by choose().
  302. =item qs
  303. This is a number between 0.000 and 1.000 that describes the "source
  304. quality". This is what F<draft-ietf-http-v11-spec-00.ps> says about this
  305. value:
  306. Source quality is measured by the content provider as representing the
  307. amount of degradation from the original source. For example, a
  308. picture in JPEG form would have a lower qs when translated to the XBM
  309. format, and much lower qs when translated to an ASCII-art
  310. representation. Note, however, that this is a function of the source
  311. - an original piece of ASCII-art may degrade in quality if it is
  312. captured in JPEG form. The qs values should be assigned to each
  313. variant by the content provider; if no qs value has been assigned, the
  314. default is generally "qs=1".
  315. =item content-type
  316. This is the media type of the variant. The media type does not
  317. include a charset attribute, but might contain other parameters.
  318. Examples are:
  319. text/html
  320. text/html;version=2.0
  321. text/plain
  322. image/gif
  323. image/jpg
  324. =item content-encoding
  325. This is one or more content encodings that has been applied to the
  326. variant. The content encoding is generally used as a modifier to the
  327. content media type. The most common content encodings are:
  328. gzip
  329. compress
  330. =item content-charset
  331. This is the character set used when the variant contains text.
  332. The charset value should generally be C<undef> or one of these:
  333. us-ascii
  334. iso-8859-1 ... iso-8859-9
  335. iso-2022-jp
  336. iso-2022-jp-2
  337. iso-2022-kr
  338. unicode-1-1
  339. unicode-1-1-utf-7
  340. unicode-1-1-utf-8
  341. =item content-language
  342. This describes one or more languages that are used in the variant.
  343. Language is described like this in F<draft-ietf-http-v11-spec-00.ps>: A
  344. language is in this context a natural language spoken, written, or
  345. otherwise conveyed by human beings for communication of information to
  346. other human beings. Computer languages are explicitly excluded.
  347. The language tags are defined by RFC-1766. Examples
  348. are:
  349. no Norwegian
  350. en International English
  351. en-US US English
  352. en-cockney
  353. =item content-length
  354. This is the number of bytes used to represent the content.
  355. =back
  356. =head1 ACCEPT HEADERS
  357. The following Accept* headers can be used for describing content
  358. preferences in a request (This description is an edited extract from
  359. F<draft-ietf-http-v11-spec-00.ps>):
  360. =over 3
  361. =item Accept
  362. This header can be used to indicate a list of media ranges which are
  363. acceptable as a reponse to the request. The "*" character is used to
  364. group media types into ranges, with "*/*" indicating all media types
  365. and "type/*" indicating all subtypes of that type.
  366. The parameter q is used to indicate the quality factor, which
  367. represents the user's preference for that range of media types. The
  368. parameter mbx gives the maximum acceptable size of the response
  369. content. The default values are: q=1 and mbx=infinity. If no Accept
  370. header is present, then the client accepts all media types with q=1.
  371. For example:
  372. Accept: audio/*;q=0.2;mbx=200000, audio/basic
  373. would mean: "I prefer audio/basic (of any size), but send me any audio
  374. type if it is the best available after an 80% mark-down in quality and
  375. its size is less than 200000 bytes"
  376. =item Accept-Charset
  377. Used to indicate what character sets are acceptable for the response.
  378. The "us-ascii" character set is assumed to be acceptable for all user
  379. agents. If no Accept-Charset field is given, the default is that any
  380. charset is acceptable. Example:
  381. Accept-Charset: iso-8859-1, unicode-1-1
  382. =item Accept-Encoding
  383. Restricts the Content-Encoding values which are acceptable in the
  384. response. If no Accept-Encoding field is present, the server may
  385. assume that the client will accept any content encoding. An empty
  386. Accept-Encoding means that no content encoding is acceptable. Example:
  387. Accept-Encoding: compress, gzip
  388. =item Accept-Language
  389. This field is similar to Accept, but restricts the set of natural
  390. languages that are preferred in a response. Each language may be
  391. given an associated quality value which represents an estimate of the
  392. user's comprehension of that language. For example:
  393. Accept-Language: no, en-gb;q=0.8, de;q=0.55
  394. would mean: "I prefer Norwegian, but will accept British English (with
  395. 80% comprehension) or German (with 55% comprehension).
  396. =back
  397. =head1 COPYRIGHT
  398. Copyright 1996, Gisle Aas.
  399. This library is free software; you can redistribute it and/or
  400. modify it under the same terms as Perl itself.
  401. =head1 AUTHOR
  402. Gisle Aas <[email protected]>
  403. =cut