Source code of Windows XP (NT5)
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.

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