]> WPIA git - gigi.git/blob - lib/servlet-api/javax/servlet/http/Cookie.java
adding servlet api (from tomcat)
[gigi.git] / lib / servlet-api / javax / servlet / http / Cookie.java
1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements.  See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License.  You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 package javax.servlet.http;
18
19 import java.io.Serializable;
20 import java.text.MessageFormat;
21 import java.util.BitSet;
22 import java.util.Locale;
23 import java.util.ResourceBundle;
24
25 /**
26  * Creates a cookie, a small amount of information sent by a servlet to a Web
27  * browser, saved by the browser, and later sent back to the server. A cookie's
28  * value can uniquely identify a client, so cookies are commonly used for
29  * session management.
30  * <p>
31  * A cookie has a name, a single value, and optional attributes such as a
32  * comment, path and domain qualifiers, a maximum age, and a version number.
33  * Some Web browsers have bugs in how they handle the optional attributes, so
34  * use them sparingly to improve the interoperability of your servlets.
35  * <p>
36  * The servlet sends cookies to the browser by using the
37  * {@link HttpServletResponse#addCookie} method, which adds fields to HTTP
38  * response headers to send cookies to the browser, one at a time. The browser
39  * is expected to support 20 cookies for each Web server, 300 cookies total, and
40  * may limit cookie size to 4 KB each.
41  * <p>
42  * The browser returns cookies to the servlet by adding fields to HTTP request
43  * headers. Cookies can be retrieved from a request by using the
44  * {@link HttpServletRequest#getCookies} method. Several cookies might have the
45  * same name but different path attributes.
46  * <p>
47  * Cookies affect the caching of the Web pages that use them. HTTP 1.0 does not
48  * cache pages that use cookies created with this class. This class does not
49  * support the cache control defined with HTTP 1.1.
50  * <p>
51  * This class supports both the Version 0 (by Netscape) and Version 1 (by RFC
52  * 2109) cookie specifications. By default, cookies are created using Version 0
53  * to ensure the best interoperability.
54  */
55 public class Cookie implements Cloneable, Serializable {
56
57     private static final CookieNameValidator validation;
58     static {
59         boolean strictNaming;
60         String prop = System.getProperty("org.apache.tomcat.util.http.ServerCookie.STRICT_NAMING");
61         if (prop != null) {
62             strictNaming = Boolean.parseBoolean(prop);
63         } else {
64             strictNaming = Boolean.getBoolean("org.apache.catalina.STRICT_SERVLET_COMPLIANCE");
65         }
66
67         if (strictNaming) {
68             validation = new RFC2109Validator();
69         }
70         else {
71             validation = new NetscapeValidator();
72         }
73     }
74
75     private static final long serialVersionUID = 1L;
76
77     private final String name;
78     private String value;
79
80     private int version = 0; // ;Version=1 ... means RFC 2109 style
81
82     //
83     // Attributes encoded in the header's cookie fields.
84     //
85     private String comment; // ;Comment=VALUE ... describes cookie's use
86     private String domain; // ;Domain=VALUE ... domain that sees cookie
87     private int maxAge = -1; // ;Max-Age=VALUE ... cookies auto-expire
88     private String path; // ;Path=VALUE ... URLs that see the cookie
89     private boolean secure; // ;Secure ... e.g. use SSL
90     private boolean httpOnly; // Not in cookie specs, but supported by browsers
91
92     /**
93      * Constructs a cookie with a specified name and value.
94      * <p>
95      * The name must conform to RFC 2109. That means it can contain only ASCII
96      * alphanumeric characters and cannot contain commas, semicolons, or white
97      * space or begin with a $ character. The cookie's name cannot be changed
98      * after creation.
99      * <p>
100      * The value can be anything the server chooses to send. Its value is
101      * probably of interest only to the server. The cookie's value can be
102      * changed after creation with the <code>setValue</code> method.
103      * <p>
104      * By default, cookies are created according to the Netscape cookie
105      * specification. The version can be changed with the
106      * <code>setVersion</code> method.
107      *
108      * @param name
109      *            a <code>String</code> specifying the name of the cookie
110      * @param value
111      *            a <code>String</code> specifying the value of the cookie
112      * @throws IllegalArgumentException
113      *             if the cookie name contains illegal characters (for example,
114      *             a comma, space, or semicolon) or it is one of the tokens
115      *             reserved for use by the cookie protocol
116      * @see #setValue
117      * @see #setVersion
118      */
119     public Cookie(String name, String value) {
120         validation.validate(name);
121         this.name = name;
122         this.value = value;
123     }
124
125     /**
126      * Specifies a comment that describes a cookie's purpose. The comment is
127      * useful if the browser presents the cookie to the user. Comments are not
128      * supported by Netscape Version 0 cookies.
129      *
130      * @param purpose
131      *            a <code>String</code> specifying the comment to display to the
132      *            user
133      * @see #getComment
134      */
135     public void setComment(String purpose) {
136         comment = purpose;
137     }
138
139     /**
140      * Returns the comment describing the purpose of this cookie, or
141      * <code>null</code> if the cookie has no comment.
142      *
143      * @return a <code>String</code> containing the comment, or
144      *         <code>null</code> if none
145      * @see #setComment
146      */
147     public String getComment() {
148         return comment;
149     }
150
151     /**
152      * Specifies the domain within which this cookie should be presented.
153      * <p>
154      * The form of the domain name is specified by RFC 2109. A domain name
155      * begins with a dot (<code>.foo.com</code>) and means that the cookie is
156      * visible to servers in a specified Domain Name System (DNS) zone (for
157      * example, <code>www.foo.com</code>, but not <code>a.b.foo.com</code>). By
158      * default, cookies are only returned to the server that sent them.
159      *
160      * @param pattern
161      *            a <code>String</code> containing the domain name within which
162      *            this cookie is visible; form is according to RFC 2109
163      * @see #getDomain
164      */
165     public void setDomain(String pattern) {
166         domain = pattern.toLowerCase(Locale.ENGLISH); // IE allegedly needs this
167     }
168
169     /**
170      * Returns the domain name set for this cookie. The form of the domain name
171      * is set by RFC 2109.
172      *
173      * @return a <code>String</code> containing the domain name
174      * @see #setDomain
175      */
176     public String getDomain() {
177         return domain;
178     }
179
180     /**
181      * Sets the maximum age of the cookie in seconds.
182      * <p>
183      * A positive value indicates that the cookie will expire after that many
184      * seconds have passed. Note that the value is the <i>maximum</i> age when
185      * the cookie will expire, not the cookie's current age.
186      * <p>
187      * A negative value means that the cookie is not stored persistently and
188      * will be deleted when the Web browser exits. A zero value causes the
189      * cookie to be deleted.
190      *
191      * @param expiry
192      *            an integer specifying the maximum age of the cookie in
193      *            seconds; if negative, means the cookie is not stored; if zero,
194      *            deletes the cookie
195      * @see #getMaxAge
196      */
197     public void setMaxAge(int expiry) {
198         maxAge = expiry;
199     }
200
201     /**
202      * Returns the maximum age of the cookie, specified in seconds, By default,
203      * <code>-1</code> indicating the cookie will persist until browser
204      * shutdown.
205      *
206      * @return an integer specifying the maximum age of the cookie in seconds; if
207      *         negative, means the cookie persists until browser shutdown
208      * @see #setMaxAge
209      */
210     public int getMaxAge() {
211         return maxAge;
212     }
213
214     /**
215      * Specifies a path for the cookie to which the client should return the
216      * cookie.
217      * <p>
218      * The cookie is visible to all the pages in the directory you specify, and
219      * all the pages in that directory's subdirectories. A cookie's path must
220      * include the servlet that set the cookie, for example, <i>/catalog</i>,
221      * which makes the cookie visible to all directories on the server under
222      * <i>/catalog</i>.
223      * <p>
224      * Consult RFC 2109 (available on the Internet) for more information on
225      * setting path names for cookies.
226      *
227      * @param uri
228      *            a <code>String</code> specifying a path
229      * @see #getPath
230      */
231     public void setPath(String uri) {
232         path = uri;
233     }
234
235     /**
236      * Returns the path on the server to which the browser returns this cookie.
237      * The cookie is visible to all subpaths on the server.
238      *
239      * @return a <code>String</code> specifying a path that contains a servlet
240      *         name, for example, <i>/catalog</i>
241      * @see #setPath
242      */
243     public String getPath() {
244         return path;
245     }
246
247     /**
248      * Indicates to the browser whether the cookie should only be sent using a
249      * secure protocol, such as HTTPS or SSL.
250      * <p>
251      * The default value is <code>false</code>.
252      *
253      * @param flag
254      *            if <code>true</code>, sends the cookie from the browser to the
255      *            server only when using a secure protocol; if
256      *            <code>false</code>, sent on any protocol
257      * @see #getSecure
258      */
259     public void setSecure(boolean flag) {
260         secure = flag;
261     }
262
263     /**
264      * Returns <code>true</code> if the browser is sending cookies only over a
265      * secure protocol, or <code>false</code> if the browser can send cookies
266      * using any protocol.
267      *
268      * @return <code>true</code> if the browser uses a secure protocol;
269      *         otherwise, <code>true</code>
270      * @see #setSecure
271      */
272     public boolean getSecure() {
273         return secure;
274     }
275
276     /**
277      * Returns the name of the cookie. The name cannot be changed after
278      * creation.
279      *
280      * @return a <code>String</code> specifying the cookie's name
281      */
282     public String getName() {
283         return name;
284     }
285
286     /**
287      * Assigns a new value to a cookie after the cookie is created. If you use a
288      * binary value, you may want to use BASE64 encoding.
289      * <p>
290      * With Version 0 cookies, values should not contain white space, brackets,
291      * parentheses, equals signs, commas, double quotes, slashes, question
292      * marks, at signs, colons, and semicolons. Empty values may not behave the
293      * same way on all browsers.
294      *
295      * @param newValue
296      *            a <code>String</code> specifying the new value
297      * @see #getValue
298      * @see Cookie
299      */
300     public void setValue(String newValue) {
301         value = newValue;
302     }
303
304     /**
305      * Returns the value of the cookie.
306      *
307      * @return a <code>String</code> containing the cookie's present value
308      * @see #setValue
309      * @see Cookie
310      */
311     public String getValue() {
312         return value;
313     }
314
315     /**
316      * Returns the version of the protocol this cookie complies with. Version 1
317      * complies with RFC 2109, and version 0 complies with the original cookie
318      * specification drafted by Netscape. Cookies provided by a browser use and
319      * identify the browser's cookie version.
320      *
321      * @return 0 if the cookie complies with the original Netscape specification;
322      *         1 if the cookie complies with RFC 2109
323      * @see #setVersion
324      */
325     public int getVersion() {
326         return version;
327     }
328
329     /**
330      * Sets the version of the cookie protocol this cookie complies with.
331      * Version 0 complies with the original Netscape cookie specification.
332      * Version 1 complies with RFC 2109.
333      * <p>
334      * Since RFC 2109 is still somewhat new, consider version 1 as experimental;
335      * do not use it yet on production sites.
336      *
337      * @param v
338      *            0 if the cookie should comply with the original Netscape
339      *            specification; 1 if the cookie should comply with RFC 2109
340      * @see #getVersion
341      */
342     public void setVersion(int v) {
343         version = v;
344     }
345
346     /**
347      * Overrides the standard <code>java.lang.Object.clone</code> method to
348      * return a copy of this cookie.
349      */
350     @Override
351     public Object clone() {
352         try {
353             return super.clone();
354         } catch (CloneNotSupportedException e) {
355             throw new RuntimeException(e.getMessage());
356         }
357     }
358
359     /**
360      * Sets the flag that controls if this cookie will be hidden from scripts on
361      * the client side.
362      *
363      * @param httpOnly  The new value of the flag
364      *
365      * @since Servlet 3.0
366      */
367     public void setHttpOnly(boolean httpOnly) {
368         this.httpOnly = httpOnly;
369     }
370
371     /**
372      * Gets the flag that controls if this cookie will be hidden from scripts on
373      * the client side.
374      *
375      * @return  <code>true</code> if the cookie is hidden from scripts, else
376      *          <code>false</code>
377      * @since Servlet 3.0
378      */
379     public boolean isHttpOnly() {
380         return httpOnly;
381     }
382 }
383
384
385 class CookieNameValidator {
386     private static final String LSTRING_FILE = "javax.servlet.http.LocalStrings";
387     private static final ResourceBundle lStrings = ResourceBundle.getBundle(LSTRING_FILE);
388
389     protected final BitSet allowed;
390
391     protected CookieNameValidator(String separators) {
392         allowed = new BitSet(128);
393         allowed.set(0x20, 0x7f); // any CHAR except CTLs or separators
394         for (int i = 0; i < separators.length(); i++) {
395             char ch = separators.charAt(i);
396             allowed.clear(ch);
397         }
398     }
399
400     void validate(String name) {
401         if (name == null || name.length() == 0) {
402             throw new IllegalArgumentException(lStrings.getString("err.cookie_name_blank"));
403         }
404         if (!isToken(name) ||
405                 name.equalsIgnoreCase("Comment") ||
406                 name.equalsIgnoreCase("Discard") ||
407                 name.equalsIgnoreCase("Domain") ||
408                 name.equalsIgnoreCase("Expires") ||
409                 name.equalsIgnoreCase("Max-Age") ||
410                 name.equalsIgnoreCase("Path") ||
411                 name.equalsIgnoreCase("Secure") ||
412                 name.equalsIgnoreCase("Version") ||
413                 name.startsWith("$")) {
414             String errMsg = lStrings.getString("err.cookie_name_is_token");
415             throw new IllegalArgumentException(MessageFormat.format(errMsg, name));
416         }
417     }
418
419     private boolean isToken(String possibleToken) {
420         int len = possibleToken.length();
421
422         for (int i = 0; i < len; i++) {
423             char c = possibleToken.charAt(i);
424             if (!allowed.get(c)) {
425                 return false;
426             }
427         }
428         return true;
429     }
430 }
431
432 class NetscapeValidator extends CookieNameValidator {
433     private static final String NETSCAPE_SEPARATORS = ",; ";
434
435     NetscapeValidator() {
436         super(NETSCAPE_SEPARATORS);
437     }
438 }
439
440 class RFC2109Validator extends CookieNameValidator {
441     private static final String RFC2616_SEPARATORS = "()<>@,;:\\\"/[]?={} \t";
442
443     RFC2109Validator() {
444         super(RFC2616_SEPARATORS);
445
446         // special treatment to allow for FWD_SLASH_IS_SEPARATOR property
447         boolean allowSlash;
448         String prop = System.getProperty("org.apache.tomcat.util.http.ServerCookie.FWD_SLASH_IS_SEPARATOR");
449         if (prop != null) {
450             allowSlash = !Boolean.parseBoolean(prop);
451         } else {
452             allowSlash = !Boolean.getBoolean("org.apache.catalina.STRICT_SERVLET_COMPLIANCE");
453         }
454         if (allowSlash) {
455             allowed.set('/');
456         }
457     }
458 }