1 /*
2  * Copyright (c) 1997-2018 Oracle and/or its affiliates and others.
3  * All rights reserved.
4  * Copyright 2004 The Apache Software Foundation
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */

18
19 package javax.servlet.http;
20
21 import java.io.Serializable;
22 import java.text.MessageFormat;
23 import java.util.Locale;
24 import java.util.ResourceBundle;
25
26 /**
27  *
28  * Creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later
29  * sent back to the server. A cookie's value can uniquely identify a client, so cookies are commonly used for session
30  * management.
31  * 
32  * <p>
33  * A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum
34  * age, and a version number. Some Web browsers have bugs in how they handle the optional attributes, so use them
35  * sparingly to improve the interoperability of your servlets.
36  *
37  * <p>
38  * The servlet sends cookies to the browser by using the {@link HttpServletResponse#addCookie} method, which adds fields
39  * to HTTP response headers to send cookies to the browser, one at a time. The browser is expected to support 20 cookies
40  * for each Web server, 300 cookies total, and may limit cookie size to 4 KB each.
41  * 
42  * <p>
43  * The browser returns cookies to the servlet by adding fields to HTTP request headers. Cookies can be retrieved from a
44  * request by using the {@link HttpServletRequest#getCookies} method. Several cookies might have the same name but
45  * different path attributes.
46  * 
47  * <p>
48  * Cookies affect the caching of the Web pages that use them. HTTP 1.0 does not cache pages that use cookies created
49  * with this class. This class does not support the cache control defined with HTTP 1.1.
50  *
51  * <p>
52  * This class supports both the Version 0 (by Netscape) and Version 1 (by RFC 2109) cookie specifications. By default,
53  * cookies are created using Version 0 to ensure the best interoperability.
54  *
55  * @author Various
56  */

57 public class Cookie implements Cloneable, Serializable {
58
59     private static final long serialVersionUID = -6454587001725327448L;
60
61     private static final String TSPECIALS;
62
63     private static final String LSTRING_FILE = "javax.servlet.http.LocalStrings";
64
65     private static ResourceBundle lStrings = ResourceBundle.getBundle(LSTRING_FILE);
66
67     static {
68         if (Boolean.valueOf(System.getProperty("org.glassfish.web.rfc2109_cookie_names_enforced""true"))
69                 .booleanValue()) {
70             TSPECIALS = "/()<>@,;:\\\"[]?={} \t";
71         } else {
72             TSPECIALS = ",; ";
73         }
74     }
75
76     //
77     // The value of the cookie itself.
78     //
79
80     private String name; // NAME= ... "$Name" style is reserved
81     private String value; // value of NAME
82
83     //
84     // Attributes encoded in the header's cookie fields.
85     //
86
87     private String comment; // ;Comment=VALUE ... describes cookie's use
88     // ;Discard ... implied by maxAge < 0
89     private String domain; // ;Domain=VALUE ... domain that sees cookie
90     private int maxAge = -1; // ;Max-Age=VALUE ... cookies auto-expire
91     private String path; // ;Path=VALUE ... URLs that see the cookie
92     private boolean secure; // ;Secure ... e.g. use SSL
93     private int version = 0; // ;Version=1 ... means RFC 2109++ style
94     private boolean isHttpOnly = false;
95
96     /**
97      * Constructs a cookie with the specified name and value.
98      *
99      * <p>
100      * The name must conform to RFC 2109. However, vendors may provide a configuration option that allows cookie names
101      * conforming to the original Netscape Cookie Specification to be accepted.
102      *
103      * <p>
104      * The name of a cookie cannot be changed once the cookie has been created.
105      *
106      * <p>
107      * The value can be anything the server chooses to send. Its value is probably of interest only to the server. The
108      * cookie's value can be changed after creation with the <code>setValue</code> method.
109      *
110      * <p>
111      * By default, cookies are created according to the Netscape cookie specification. The version can be changed with
112      * the <code>setVersion</code> method.
113      *
114      * @param name  the name of the cookie
115      *
116      * @param value the value of the cookie
117      *
118      * @throws IllegalArgumentException if the cookie name is null or empty or contains any illegal characters (for
119      *                                  example, a comma, space, or semicolon) or matches a token reserved for use by
120      *                                  the cookie protocol
121      *
122      * @see #setValue
123      * @see #setVersion
124      */

125     public Cookie(String name, String value) {
126         if (name == null || name.length() == 0) {
127             throw new IllegalArgumentException(lStrings.getString("err.cookie_name_blank"));
128         }
129         if (!isToken(name) || name.equalsIgnoreCase("Comment") || // rfc2019
130                 name.equalsIgnoreCase("Discard") || // 2019++
131                 name.equalsIgnoreCase("Domain") || name.equalsIgnoreCase("Expires") || // (old cookies)
132                 name.equalsIgnoreCase("Max-Age") || // rfc2019
133                 name.equalsIgnoreCase("Path") || name.equalsIgnoreCase("Secure") || name.equalsIgnoreCase("Version")
134                 || name.startsWith("$")) {
135             String errMsg = lStrings.getString("err.cookie_name_is_token");
136             Object[] errArgs = new Object[1];
137             errArgs[0] = name;
138             errMsg = MessageFormat.format(errMsg, errArgs);
139             throw new IllegalArgumentException(errMsg);
140         }
141
142         this.name = name;
143         this.value = value;
144     }
145
146     /**
147      * Specifies a comment that describes a cookie's purpose. The comment is useful if the browser presents the cookie
148      * to the user. Comments are not supported by Netscape Version 0 cookies.
149      *
150      * @param purpose a <code>String</code> specifying the comment to display to the user
151      *
152      * @see #getComment
153      */

154     public void setComment(String purpose) {
155         comment = purpose;
156     }
157
158     /**
159      * Returns the comment describing the purpose of this cookie, or <code>null</code> if the cookie has no comment.
160      *
161      * @return the comment of the cookie, or <code>null</code> if unspecified
162      *
163      * @see #setComment
164      */

165     public String getComment() {
166         return comment;
167     }
168
169     /**
170      *
171      * Specifies the domain within which this cookie should be presented.
172      *
173      * <p>
174      * The form of the domain name is specified by RFC 2109. A domain name begins with a dot (<code>.foo.com</code>) and
175      * means that the cookie is visible to servers in a specified Domain Name System (DNS) zone (for example,
176      * <code>www.foo.com</code>, but not <code>a.b.foo.com</code>). By default, cookies are only returned to the server
177      * that sent them.
178      *
179      * @param domain the domain name within which this cookie is visible; form is according to RFC 2109
180      *
181      * @see #getDomain
182      */

183     public void setDomain(String domain) {
184         this.domain = domain.toLowerCase(Locale.ENGLISH); // IE allegedly needs this
185     }
186
187     /**
188      * Gets the domain name of this Cookie.
189      *
190      * <p>
191      * Domain names are formatted according to RFC 2109.
192      *
193      * @return the domain name of this Cookie
194      *
195      * @see #setDomain
196      */

197     public String getDomain() {
198         return domain;
199     }
200
201     /**
202      * Sets the maximum age in seconds for this Cookie.
203      *
204      * <p>
205      * A positive value indicates that the cookie will expire after that many seconds have passed. Note that the value
206      * is the <i>maximum</i> age when the cookie will expire, not the cookie's current age.
207      *
208      * <p>
209      * A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits.
210      * A zero value causes the cookie to be deleted.
211      *
212      * @param expiry an integer specifying the maximum age of the cookie in seconds; if negative, means the cookie is
213      *               not stored; if zero, deletes the cookie
214      *
215      * @see #getMaxAge
216      */

217     public void setMaxAge(int expiry) {
218         maxAge = expiry;
219     }
220
221     /**
222      * Gets the maximum age in seconds of this Cookie.
223      *
224      * <p>
225      * By default, <code>-1</code> is returned, which indicates that the cookie will persist until browser shutdown.
226      *
227      * @return an integer specifying the maximum age of the cookie in seconds; if negative, means the cookie persists
228      *         until browser shutdown
229      *
230      * @see #setMaxAge
231      */

232     public int getMaxAge() {
233         return maxAge;
234     }
235
236     /**
237      * Specifies a path for the cookie to which the client should return the cookie.
238      *
239      * <p>
240      * The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's
241      * subdirectories. A cookie's path must include the servlet that set the cookie, for example, <i>/catalog</i>, which
242      * makes the cookie visible to all directories on the server under <i>/catalog</i>.
243      *
244      * <p>
245      * Consult RFC 2109 (available on the Internet) for more information on setting path names for cookies.
246      *
247      *
248      * @param uri a <code>String</code> specifying a path
249      *
250      * @see #getPath
251      */

252     public void setPath(String uri) {
253         path = uri;
254     }
255
256     /**
257      * Returns the path on the server to which the browser returns this cookie. The cookie is visible to all subpaths on
258      * the server.
259      *
260      * @return a <code>String</code> specifying a path that contains a servlet name, for example, <i>/catalog</i>
261      *
262      * @see #setPath
263      */

264     public String getPath() {
265         return path;
266     }
267
268     /**
269      * Indicates to the browser whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL.
270      *
271      * <p>
272      * The default value is <code>false</code>.
273      *
274      * @param flag if <code>true</code>, sends the cookie from the browser to the server only when using a secure
275      *             protocol; if <code>false</code>, sent on any protocol
276      *
277      * @see #getSecure
278      */

279     public void setSecure(boolean flag) {
280         secure = flag;
281     }
282
283     /**
284      * Returns <code>true</code> if the browser is sending cookies only over a secure protocol, or <code>false</code> if
285      * the browser can send cookies using any protocol.
286      *
287      * @return <code>true</code> if the browser uses a secure protocol, <code>false</code> otherwise
288      *
289      * @see #setSecure
290      */

291     public boolean getSecure() {
292         return secure;
293     }
294
295     /**
296      * Returns the name of the cookie. The name cannot be changed after creation.
297      *
298      * @return the name of the cookie
299      */

300     public String getName() {
301         return name;
302     }
303
304     /**
305      * Assigns a new value to this Cookie.
306      * 
307      * <p>
308      * If you use a binary value, you may want to use BASE64 encoding.
309      *
310      * <p>
311      * With Version 0 cookies, values should not contain white space, brackets, parentheses, equals signs, commas,
312      * double quotes, slashes, question marks, at signs, colons, and semicolons. Empty values may not behave the same
313      * way on all browsers.
314      *
315      * @param newValue the new value of the cookie
316      *
317      * @see #getValue
318      */

319     public void setValue(String newValue) {
320         value = newValue;
321     }
322
323     /**
324      * Gets the current value of this Cookie.
325      *
326      * @return the current value of this Cookie
327      *
328      * @see #setValue
329      */

330     public String getValue() {
331         return value;
332     }
333
334     /**
335      * Returns the version of the protocol this cookie complies with. Version 1 complies with RFC 2109, and version 0
336      * complies with the original cookie specification drafted by Netscape. Cookies provided by a browser use and
337      * identify the browser's cookie version.
338      * 
339      * @return 0 if the cookie complies with the original Netscape specification; 1 if the cookie complies with RFC 2109
340      *
341      * @see #setVersion
342      */

343     public int getVersion() {
344         return version;
345     }
346
347     /**
348      * Sets the version of the cookie protocol that this Cookie complies with.
349      *
350      * <p>
351      * Version 0 complies with the original Netscape cookie specification. Version 1 complies with RFC 2109.
352      *
353      * <p>
354      * Since RFC 2109 is still somewhat new, consider version 1 as experimental; do not use it yet on production sites.
355      *
356      * @param v 0 if the cookie should comply with the original Netscape specification; 1 if the cookie should comply
357      *          with RFC 2109
358      *
359      * @see #getVersion
360      */

361     public void setVersion(int v) {
362         version = v;
363     }
364
365     /*
366      * Tests a string and returns true if the string counts as a reserved token in the Java language.
367      * 
368      * @param value the <code>String</code> to be tested
369      *
370      * @return <code>true</code> if the <code>String</code> is a reserved token; <code>false</code> otherwise
371      */

372     private boolean isToken(String value) {
373         int len = value.length();
374         for (int i = 0; i < len; i++) {
375             char c = value.charAt(i);
376             if (c < 0x20 || c >= 0x7f || TSPECIALS.indexOf(c) != -1) {
377                 return false;
378             }
379         }
380
381         return true;
382     }
383
384     /**
385      * Overrides the standard <code>java.lang.Object.clone</code> method to return a copy of this Cookie.
386      */

387     @Override
388     public Object clone() {
389         try {
390             return super.clone();
391         } catch (CloneNotSupportedException e) {
392             throw new RuntimeException(e.getMessage());
393         }
394     }
395
396     /**
397      * Marks or unmarks this Cookie as <i>HttpOnly</i>.
398      *
399      * <p>
400      * If <tt>isHttpOnly</tt> is set to <tt>true</tt>, this cookie is marked as <i>HttpOnly</i>, by adding the
401      * <tt>HttpOnly</tt> attribute to it.
402      *
403      * <p>
404      * <i>HttpOnly</i> cookies are not supposed to be exposed to client-side scripting code, and may therefore help
405      * mitigate certain kinds of cross-site scripting attacks.
406      *
407      * @param isHttpOnly true if this cookie is to be marked as <i>HttpOnly</i>, false otherwise
408      *
409      * @since Servlet 3.0
410      */

411     public void setHttpOnly(boolean isHttpOnly) {
412         this.isHttpOnly = isHttpOnly;
413     }
414
415     /**
416      * Checks whether this Cookie has been marked as <i>HttpOnly</i>.
417      *
418      * @return true if this Cookie has been marked as <i>HttpOnly</i>, false otherwise
419      *
420      * @since Servlet 3.0
421      */

422     public boolean isHttpOnly() {
423         return isHttpOnly;
424     }
425 }
426