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.

429 lines
13 KiB

  1. package CGI::Cookie;
  2. # See the bottom of this file for the POD documentation. Search for the
  3. # string '=head'.
  4. # You can run this file through either pod2man or pod2html to produce pretty
  5. # documentation in manual or html file format (these utilities are part of the
  6. # Perl 5 distribution).
  7. # Copyright 1995-1999, Lincoln D. Stein. All rights reserved.
  8. # It may be used and modified freely, but I do request that this copyright
  9. # notice remain attached to the file. You may modify this module as you
  10. # wish, but if you redistribute a modified version, please attach a note
  11. # listing the modifications you have made.
  12. $CGI::Cookie::VERSION='1.18';
  13. use CGI::Util qw(rearrange unescape escape);
  14. use overload '""' => \&as_string,
  15. 'cmp' => \&compare,
  16. 'fallback'=>1;
  17. # fetch a list of cookies from the environment and
  18. # return as a hash. the cookies are parsed as normal
  19. # escaped URL data.
  20. sub fetch {
  21. my $class = shift;
  22. my $raw_cookie = $ENV{HTTP_COOKIE} || $ENV{COOKIE};
  23. return () unless $raw_cookie;
  24. return $class->parse($raw_cookie);
  25. }
  26. # fetch a list of cookies from the environment and
  27. # return as a hash. the cookie values are not unescaped
  28. # or altered in any way.
  29. sub raw_fetch {
  30. my $class = shift;
  31. my $raw_cookie = $ENV{HTTP_COOKIE} || $ENV{COOKIE};
  32. return () unless $raw_cookie;
  33. my %results;
  34. my($key,$value);
  35. my(@pairs) = split("; ?",$raw_cookie);
  36. foreach (@pairs) {
  37. s/\s*(.*?)\s*/$1/;
  38. if (/^([^=]+)=(.*)/) {
  39. $key = $1;
  40. $value = $2;
  41. }
  42. else {
  43. $key = $_;
  44. $value = '';
  45. }
  46. $results{$key} = $value;
  47. }
  48. return \%results unless wantarray;
  49. return %results;
  50. }
  51. sub parse {
  52. my ($self,$raw_cookie) = @_;
  53. my %results;
  54. my(@pairs) = split("; ?",$raw_cookie);
  55. foreach (@pairs) {
  56. s/\s*(.*?)\s*/$1/;
  57. my($key,$value) = split("=");
  58. # Some foreign cookies are not in name=value format, so ignore
  59. # them.
  60. next if !defined($value);
  61. my @values = ();
  62. if ($value ne '') {
  63. @values = map CGI::unescape($_),split(/[&;]/,$value.'&dmy');
  64. pop @values;
  65. }
  66. $key = unescape($key);
  67. # A bug in Netscape can cause several cookies with same name to
  68. # appear. The FIRST one in HTTP_COOKIE is the most recent version.
  69. $results{$key} ||= $self->new(-name=>$key,-value=>\@values);
  70. }
  71. return \%results unless wantarray;
  72. return %results;
  73. }
  74. sub new {
  75. my $class = shift;
  76. $class = ref($class) if ref($class);
  77. my($name,$value,$path,$domain,$secure,$expires) =
  78. rearrange([NAME,[VALUE,VALUES],PATH,DOMAIN,SECURE,EXPIRES],@_);
  79. # Pull out our parameters.
  80. my @values;
  81. if (ref($value)) {
  82. if (ref($value) eq 'ARRAY') {
  83. @values = @$value;
  84. } elsif (ref($value) eq 'HASH') {
  85. @values = %$value;
  86. }
  87. } else {
  88. @values = ($value);
  89. }
  90. bless my $self = {
  91. 'name'=>$name,
  92. 'value'=>[@values],
  93. },$class;
  94. # IE requires the path and domain to be present for some reason.
  95. $path ||= "/";
  96. # however, this breaks networks which use host tables without fully qualified
  97. # names, so we comment it out.
  98. # $domain = CGI::virtual_host() unless defined $domain;
  99. $self->path($path) if defined $path;
  100. $self->domain($domain) if defined $domain;
  101. $self->secure($secure) if defined $secure;
  102. $self->expires($expires) if defined $expires;
  103. return $self;
  104. }
  105. sub as_string {
  106. my $self = shift;
  107. return "" unless $self->name;
  108. my(@constant_values,$domain,$path,$expires,$secure);
  109. push(@constant_values,"domain=$domain") if $domain = $self->domain;
  110. push(@constant_values,"path=$path") if $path = $self->path;
  111. push(@constant_values,"expires=$expires") if $expires = $self->expires;
  112. push(@constant_values,"secure") if $secure = $self->secure;
  113. my($key) = escape($self->name);
  114. my($cookie) = join("=",$key,join("&",map escape($_),$self->value));
  115. return join("; ",$cookie,@constant_values);
  116. }
  117. sub compare {
  118. my $self = shift;
  119. my $value = shift;
  120. return "$self" cmp $value;
  121. }
  122. # accessors
  123. sub name {
  124. my $self = shift;
  125. my $name = shift;
  126. $self->{'name'} = $name if defined $name;
  127. return $self->{'name'};
  128. }
  129. sub value {
  130. my $self = shift;
  131. my $value = shift;
  132. $self->{'value'} = $value if defined $value;
  133. return wantarray ? @{$self->{'value'}} : $self->{'value'}->[0]
  134. }
  135. sub domain {
  136. my $self = shift;
  137. my $domain = shift;
  138. $self->{'domain'} = $domain if defined $domain;
  139. return $self->{'domain'};
  140. }
  141. sub secure {
  142. my $self = shift;
  143. my $secure = shift;
  144. $self->{'secure'} = $secure if defined $secure;
  145. return $self->{'secure'};
  146. }
  147. sub expires {
  148. my $self = shift;
  149. my $expires = shift;
  150. $self->{'expires'} = CGI::Util::expires($expires,'cookie') if defined $expires;
  151. return $self->{'expires'};
  152. }
  153. sub path {
  154. my $self = shift;
  155. my $path = shift;
  156. $self->{'path'} = $path if defined $path;
  157. return $self->{'path'};
  158. }
  159. 1;
  160. =head1 NAME
  161. CGI::Cookie - Interface to Netscape Cookies
  162. =head1 SYNOPSIS
  163. use CGI qw/:standard/;
  164. use CGI::Cookie;
  165. # Create new cookies and send them
  166. $cookie1 = new CGI::Cookie(-name=>'ID',-value=>123456);
  167. $cookie2 = new CGI::Cookie(-name=>'preferences',
  168. -value=>{ font => Helvetica,
  169. size => 12 }
  170. );
  171. print header(-cookie=>[$cookie1,$cookie2]);
  172. # fetch existing cookies
  173. %cookies = fetch CGI::Cookie;
  174. $id = $cookies{'ID'}->value;
  175. # create cookies returned from an external source
  176. %cookies = parse CGI::Cookie($ENV{COOKIE});
  177. =head1 DESCRIPTION
  178. CGI::Cookie is an interface to Netscape (HTTP/1.1) cookies, an
  179. innovation that allows Web servers to store persistent information on
  180. the browser's side of the connection. Although CGI::Cookie is
  181. intended to be used in conjunction with CGI.pm (and is in fact used by
  182. it internally), you can use this module independently.
  183. For full information on cookies see
  184. http://www.ics.uci.edu/pub/ietf/http/rfc2109.txt
  185. =head1 USING CGI::Cookie
  186. CGI::Cookie is object oriented. Each cookie object has a name and a
  187. value. The name is any scalar value. The value is any scalar or
  188. array value (associative arrays are also allowed). Cookies also have
  189. several optional attributes, including:
  190. =over 4
  191. =item B<1. expiration date>
  192. The expiration date tells the browser how long to hang on to the
  193. cookie. If the cookie specifies an expiration date in the future, the
  194. browser will store the cookie information in a disk file and return it
  195. to the server every time the user reconnects (until the expiration
  196. date is reached). If the cookie species an expiration date in the
  197. past, the browser will remove the cookie from the disk file. If the
  198. expiration date is not specified, the cookie will persist only until
  199. the user quits the browser.
  200. =item B<2. domain>
  201. This is a partial or complete domain name for which the cookie is
  202. valid. The browser will return the cookie to any host that matches
  203. the partial domain name. For example, if you specify a domain name
  204. of ".capricorn.com", then Netscape will return the cookie to
  205. Web servers running on any of the machines "www.capricorn.com",
  206. "ftp.capricorn.com", "feckless.capricorn.com", etc. Domain names
  207. must contain at least two periods to prevent attempts to match
  208. on top level domains like ".edu". If no domain is specified, then
  209. the browser will only return the cookie to servers on the host the
  210. cookie originated from.
  211. =item B<3. path>
  212. If you provide a cookie path attribute, the browser will check it
  213. against your script's URL before returning the cookie. For example,
  214. if you specify the path "/cgi-bin", then the cookie will be returned
  215. to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl", and
  216. "/cgi-bin/customer_service/complain.pl", but not to the script
  217. "/cgi-private/site_admin.pl". By default, the path is set to "/", so
  218. that all scripts at your site will receive the cookie.
  219. =item B<4. secure flag>
  220. If the "secure" attribute is set, the cookie will only be sent to your
  221. script if the CGI request is occurring on a secure channel, such as SSL.
  222. =back
  223. =head2 Creating New Cookies
  224. $c = new CGI::Cookie(-name => 'foo',
  225. -value => 'bar',
  226. -expires => '+3M',
  227. -domain => '.capricorn.com',
  228. -path => '/cgi-bin/database'
  229. -secure => 1
  230. );
  231. Create cookies from scratch with the B<new> method. The B<-name> and
  232. B<-value> parameters are required. The name must be a scalar value.
  233. The value can be a scalar, an array reference, or a hash reference.
  234. (At some point in the future cookies will support one of the Perl
  235. object serialization protocols for full generality).
  236. B<-expires> accepts any of the relative or absolute date formats
  237. recognized by CGI.pm, for example "+3M" for three months in the
  238. future. See CGI.pm's documentation for details.
  239. B<-domain> points to a domain name or to a fully qualified host name.
  240. If not specified, the cookie will be returned only to the Web server
  241. that created it.
  242. B<-path> points to a partial URL on the current server. The cookie
  243. will be returned to all URLs beginning with the specified path. If
  244. not specified, it defaults to '/', which returns the cookie to all
  245. pages at your site.
  246. B<-secure> if set to a true value instructs the browser to return the
  247. cookie only when a cryptographic protocol is in use.
  248. =head2 Sending the Cookie to the Browser
  249. Within a CGI script you can send a cookie to the browser by creating
  250. one or more Set-Cookie: fields in the HTTP header. Here is a typical
  251. sequence:
  252. my $c = new CGI::Cookie(-name => 'foo',
  253. -value => ['bar','baz'],
  254. -expires => '+3M');
  255. print "Set-Cookie: $c\n";
  256. print "Content-Type: text/html\n\n";
  257. To send more than one cookie, create several Set-Cookie: fields.
  258. Alternatively, you may concatenate the cookies together with "; " and
  259. send them in one field.
  260. If you are using CGI.pm, you send cookies by providing a -cookie
  261. argument to the header() method:
  262. print header(-cookie=>$c);
  263. Mod_perl users can set cookies using the request object's header_out()
  264. method:
  265. $r->header_out('Set-Cookie',$c);
  266. Internally, Cookie overloads the "" operator to call its as_string()
  267. method when incorporated into the HTTP header. as_string() turns the
  268. Cookie's internal representation into an RFC-compliant text
  269. representation. You may call as_string() yourself if you prefer:
  270. print "Set-Cookie: ",$c->as_string,"\n";
  271. =head2 Recovering Previous Cookies
  272. %cookies = fetch CGI::Cookie;
  273. B<fetch> returns an associative array consisting of all cookies
  274. returned by the browser. The keys of the array are the cookie names. You
  275. can iterate through the cookies this way:
  276. %cookies = fetch CGI::Cookie;
  277. foreach (keys %cookies) {
  278. do_something($cookies{$_});
  279. }
  280. In a scalar context, fetch() returns a hash reference, which may be more
  281. efficient if you are manipulating multiple cookies.
  282. CGI.pm uses the URL escaping methods to save and restore reserved characters
  283. in its cookies. If you are trying to retrieve a cookie set by a foreign server,
  284. this escaping method may trip you up. Use raw_fetch() instead, which has the
  285. same semantics as fetch(), but performs no unescaping.
  286. You may also retrieve cookies that were stored in some external
  287. form using the parse() class method:
  288. $COOKIES = `cat /usr/tmp/Cookie_stash`;
  289. %cookies = parse CGI::Cookie($COOKIES);
  290. =head2 Manipulating Cookies
  291. Cookie objects have a series of accessor methods to get and set cookie
  292. attributes. Each accessor has a similar syntax. Called without
  293. arguments, the accessor returns the current value of the attribute.
  294. Called with an argument, the accessor changes the attribute and
  295. returns its new value.
  296. =over 4
  297. =item B<name()>
  298. Get or set the cookie's name. Example:
  299. $name = $c->name;
  300. $new_name = $c->name('fred');
  301. =item B<value()>
  302. Get or set the cookie's value. Example:
  303. $value = $c->value;
  304. @new_value = $c->value(['a','b','c','d']);
  305. B<value()> is context sensitive. In a list context it will return
  306. the current value of the cookie as an array. In a scalar context it
  307. will return the B<first> value of a multivalued cookie.
  308. =item B<domain()>
  309. Get or set the cookie's domain.
  310. =item B<path()>
  311. Get or set the cookie's path.
  312. =item B<expires()>
  313. Get or set the cookie's expiration time.
  314. =back
  315. =head1 AUTHOR INFORMATION
  316. Copyright 1997-1998, Lincoln D. Stein. All rights reserved.
  317. This library is free software; you can redistribute it and/or modify
  318. it under the same terms as Perl itself.
  319. Address bug reports and comments to: lstein@cshl.org
  320. =head1 BUGS
  321. This section intentionally left blank.
  322. =head1 SEE ALSO
  323. L<CGI::Carp>, L<CGI>
  324. =cut