001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one
003     * or more contributor license agreements.  See the NOTICE file
004     * distributed with this work for additional information
005     * regarding copyright ownership.  The ASF licenses this file
006     * to you under the Apache License, Version 2.0 (the
007     * "License"); you may not use this file except in compliance
008     * with the License.  You may obtain a copy of the License at
009     *
010     *  http://www.apache.org/licenses/LICENSE-2.0
011     *
012     * Unless required by applicable law or agreed to in writing,
013     * software distributed under the License is distributed on an
014     * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015     * KIND, either express or implied.  See the License for the
016     * specific language governing permissions and limitations
017     * under the License.
018     */
019    
020    package javax.servlet.http;
021    
022    import java.io.Serializable;
023    import java.text.MessageFormat;
024    import java.util.ResourceBundle;
025    
026    /**
027     * Creates a cookie, a small amount of information sent by a servlet to
028     * a Web browser, saved by the browser, and later sent back to the server.
029     * A cookie's value can uniquely
030     * identify a client, so cookies are commonly used for session management.
031     * <p/>
032     * <p>A cookie has a name, a single value, and optional attributes
033     * such as a comment, path and domain qualifiers, a maximum age, and a
034     * version number. Some Web browsers have bugs in how they handle the
035     * optional attributes, so use them sparingly to improve the interoperability
036     * of your servlets.
037     * <p/>
038     * <p>The servlet sends cookies to the browser by using the
039     * {@link HttpServletResponse#addCookie} method, which adds
040     * fields to HTTP response headers to send cookies to the
041     * browser, one at a time. The browser is expected to
042     * support 20 cookies for each Web server, 300 cookies total, and
043     * may limit cookie size to 4 KB each.
044     * <p/>
045     * <p>The browser returns cookies to the servlet by adding
046     * fields to HTTP request headers. Cookies can be retrieved
047     * from a request by using the {@link HttpServletRequest#getCookies} method.
048     * Several cookies might have the same name but different path attributes.
049     * <p/>
050     * <p>Cookies affect the caching of the Web pages that use them.
051     * HTTP 1.0 does not cache pages that use cookies created with
052     * this class. This class does not support the cache control
053     * defined with HTTP 1.1.
054     * <p/>
055     * <p>This class supports both the Version 0 (by Netscape) and Version 1
056     * (by RFC 2109) cookie specifications. By default, cookies are
057     * created using Version 0 to ensure the best interoperability.
058     *
059     * @version $Rev: 901916 $ $Date: 2010-01-21 18:12:17 -0500 (Thu, 21 Jan 2010) $
060     */
061    
062    public class Cookie implements Cloneable, Serializable {
063        private static final long serialVersionUID = -6454587001725327448L;
064    
065        private static final String LSTRING_FILE =
066                "javax.servlet.http.LocalStrings";
067        private static ResourceBundle lStrings =
068                ResourceBundle.getBundle(LSTRING_FILE);
069    
070        // Note -- disabled for now to allow full Netscape compatibility
071        // from RFC 2068, token special case characters
072        //
073        // private static final String tspecials = "()<>@,;:\\\"/[]?={} \t";
074    
075        private static final String tspecials = ",; ";
076    
077        //
078        // The value of the cookie itself.
079        //
080    
081        private String name;        // NAME= ... "$Name" style is reserved
082        private String value;        // value of NAME
083    
084        //
085        // Attributes encoded in the header's cookie fields.
086        //
087    
088        private String comment;        // ;Comment=VALUE ... describes cookie's use
089        // ;Discard ... implied by maxAge < 0
090        private String domain;        // ;Domain=VALUE ... domain that sees cookie
091        private int maxAge = -1;        // ;Max-Age=VALUE ... cookies auto-expire
092        private String path;        // ;Path=VALUE ... URLs that see the cookie
093        private boolean secure;        // ;Secure ... e.g. use SSL
094        private int version = 0;        // ;Version=1 ... means RFC 2109++ style
095        private boolean httpOnly;
096    
097        /**
098         * Constructs a cookie with a specified name and value.
099         * <p/>
100         * <p>The name must conform to RFC 2109. That means it can contain
101         * only ASCII alphanumeric characters and cannot contain commas,
102         * semicolons, or white space or begin with a $ character. The cookie's
103         * name cannot be changed after creation.
104         * <p/>
105         * <p>The value can be anything the server chooses to send. Its
106         * value is probably of interest only to the server. The cookie's
107         * value can be changed after creation with the
108         * <code>setValue</code> method.
109         * <p/>
110         * <p>By default, cookies are created according to the Netscape
111         * cookie specification. The version can be changed with the
112         * <code>setVersion</code> method.
113         *
114         * @param name  a <code>String</code> specifying the name of the cookie
115         * @param value a <code>String</code> specifying the value of the cookie
116         * @throws IllegalArgumentException if the cookie name contains illegal characters
117         *                                  (for example, a comma, space, or semicolon)
118         *                                  or it is one of the tokens reserved for use
119         *                                  by the cookie protocol
120         * @see #setValue
121         * @see #setVersion
122         */
123        public Cookie(String name, String value) {
124            if (!isToken(name)
125                    || name.equalsIgnoreCase("Comment")        // rfc2019
126                    || name.equalsIgnoreCase("Discard")        // 2019++
127                    || name.equalsIgnoreCase("Domain")
128                    || name.equalsIgnoreCase("Expires")        // (old cookies)
129                    || name.equalsIgnoreCase("Max-Age")        // rfc2019
130                    || name.equalsIgnoreCase("Path")
131                    || name.equalsIgnoreCase("Secure")
132                    || name.equalsIgnoreCase("Version")
133                    || name.startsWith("$")
134                    ) {
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.
148         * The comment is useful if the browser presents the cookie
149         * to the user. Comments
150         * are not supported by Netscape Version 0 cookies.
151         *
152         * @param purpose a <code>String</code> specifying the comment
153         *                to display to the user
154         * @see #getComment
155         */
156        public void setComment(String purpose) {
157            comment = purpose;
158        }
159    
160        /**
161         * Returns the comment describing the purpose of this cookie, or
162         * <code>null</code> if the cookie has no comment.
163         *
164         * @return a <code>String</code> containing the comment,
165         * or <code>null</code> if none
166         * @see #setComment
167         */
168        public String getComment() {
169            return comment;
170        }
171    
172        /**
173         * Specifies the domain within which this cookie should be presented.
174         * <p/>
175         * <p>The form of the domain name is specified by RFC 2109. A domain
176         * name begins with a dot (<code>.foo.com</code>) and means that
177         * the cookie is visible to servers in a specified Domain Name System
178         * (DNS) zone (for example, <code>www.foo.com</code>, but not
179         * <code>a.b.foo.com</code>). By default, cookies are only returned
180         * to the server that sent them.
181         *
182         * @param pattern a <code>String</code> containing the domain name
183         *                within which this cookie is visible;
184         *                form is according to RFC 2109
185         * @see #getDomain
186         */
187        public void setDomain(String pattern) {
188            domain = pattern.toLowerCase();        // IE allegedly needs this
189        }
190    
191        /**
192         * Returns the domain name set for this cookie. The form of
193         * the domain name is set by RFC 2109.
194         *
195         * @return a <code>String</code> containing the domain name
196         * @see #setDomain
197         */
198        public String getDomain() {
199            return domain;
200        }
201    
202        /**
203         * Sets the maximum age of the cookie in seconds.
204         * <p/>
205         * <p>A positive value indicates that the cookie will expire
206         * after that many seconds have passed. Note that the value is
207         * the <i>maximum</i> age when the cookie will expire, not the cookie's
208         * current age.
209         * <p/>
210         * <p>A negative value means
211         * that the cookie is not stored persistently and will be deleted
212         * when the Web browser exits. A zero value causes the cookie
213         * to be deleted.
214         *
215         * @param expiry an integer specifying the maximum age of the
216         *               cookie in seconds; if negative, means
217         *               the cookie is not stored; if zero, deletes
218         *               the cookie
219         * @see #getMaxAge
220         */
221        public void setMaxAge(int expiry) {
222            maxAge = expiry;
223        }
224    
225        /**
226         * Returns the maximum age of the cookie, specified in seconds,
227         * By default, <code>-1</code> indicating the cookie will persist
228         * until browser shutdown.
229         *
230         * @return an integer specifying the maximum age of the
231         * cookie in seconds; if negative, means
232         * the cookie persists until browser shutdown
233         * @see #setMaxAge
234         */
235        public int getMaxAge() {
236            return maxAge;
237        }
238    
239        /**
240         * Specifies a path for the cookie
241         * to which the client should return the cookie.
242         * <p/>
243         * <p>The cookie is visible to all the pages in the directory
244         * you specify, and all the pages in that directory's subdirectories.
245         * A cookie's path must include the servlet that set the cookie,
246         * for example, <i>/catalog</i>, which makes the cookie
247         * visible to all directories on the server under <i>/catalog</i>.
248         * <p/>
249         * <p>Consult RFC 2109 (available on the Internet) for more
250         * information on setting path names for cookies.
251         *
252         * @param uri a <code>String</code> specifying a path
253         * @see #getPath
254         */
255        public void setPath(String uri) {
256            path = uri;
257        }
258    
259        /**
260         * Returns the path on the server
261         * to which the browser returns this cookie. The
262         * cookie is visible to all subpaths on the server.
263         *
264         * @return a <code>String</code> specifying a path that contains
265         * a servlet name, for example, <i>/catalog</i>
266         * @see #setPath
267         */
268        public String getPath() {
269            return path;
270        }
271    
272        /**
273         * Indicates to the browser whether the cookie should only be sent
274         * using a secure protocol, such as HTTPS or SSL.
275         * <p/>
276         * <p>The default value is <code>false</code>.
277         *
278         * @param flag if <code>true</code>, sends the cookie from the browser
279         *             to the server only when using a secure protocol;
280         *             if <code>false</code>, sent on any protocol
281         * @see #getSecure
282         */
283        public void setSecure(boolean flag) {
284            secure = flag;
285        }
286    
287        /**
288         * Returns <code>true</code> if the browser is sending cookies
289         * only over a secure protocol, or <code>false</code> if the
290         * browser can send cookies using any protocol.
291         *
292         * @return                <code>true</code> if the browser uses a secure protocol;
293         * otherwise, <code>true</code>
294         * @see #setSecure
295         */
296        public boolean getSecure() {
297            return secure;
298        }
299    
300        /**
301         * Returns the name of the cookie. The name cannot be changed after
302         * creation.
303         *
304         * @return a <code>String</code> specifying the cookie's name
305         */
306        public String getName() {
307            return name;
308        }
309    
310        /**
311         * Assigns a new value to a cookie after the cookie is created.
312         * If you use a binary value, you may want to use BASE64 encoding.
313         * <p/>
314         * <p>With Version 0 cookies, values should not contain white
315         * space, brackets, parentheses, equals signs, commas,
316         * double quotes, slashes, question marks, at signs, colons,
317         * and semicolons. Empty values may not behave the same way
318         * on all browsers.
319         *
320         * @param newValue a <code>String</code> specifying the new value
321         * @see #getValue
322         * @see Cookie
323         */
324        public void setValue(String newValue) {
325            value = newValue;
326        }
327    
328        /**
329         * Returns the value of the cookie.
330         *
331         * @return a <code>String</code> containing the cookie's
332         * present value
333         * @see #setValue
334         * @see Cookie
335         */
336        public String getValue() {
337            return value;
338        }
339    
340        /**
341         * Returns the version of the protocol this cookie complies
342         * with. Version 1 complies with RFC 2109,
343         * and version 0 complies with the original
344         * cookie specification drafted by Netscape. Cookies provided
345         * by a browser use and identify the browser's cookie version.
346         *
347         * @return 0 if the cookie complies with the
348         * original Netscape specification; 1
349         * if the cookie complies with RFC 2109
350         * @see #setVersion
351         */
352        public int getVersion() {
353            return version;
354        }
355    
356        /**
357         * Sets the version of the cookie protocol this cookie complies
358         * with. Version 0 complies with the original Netscape cookie
359         * specification. Version 1 complies with RFC 2109.
360         * <p/>
361         * <p>Since RFC 2109 is still somewhat new, consider
362         * version 1 as experimental; do not use it yet on production sites.
363         *
364         * @param v 0 if the cookie should comply with
365         *          the original Netscape specification;
366         *          1 if the cookie should comply with RFC 2109
367         * @see #getVersion
368         */
369        public void setVersion(int v) {
370            version = v;
371        }
372    
373        /*
374         * Tests a string and returns true if the string counts as a 
375         * reserved token in the Java language.
376         * 
377         * @param value             the <code>String</code> to be tested
378         *
379         * @return                  <code>true</code> if the <code>String</code> is
380         *                          a reserved token; <code>false</code>
381         *                          if it is not                    
382         */
383        private boolean isToken(String value) {
384            int len = value.length();
385    
386            for (int i = 0; i < len; i++) {
387                char c = value.charAt(i);
388    
389                if (c < 0x20 || c >= 0x7f || tspecials.indexOf(c) != -1)
390                    return false;
391            }
392            return true;
393        }
394    
395        /**
396         * Overrides the standard <code>java.lang.Object.clone</code>
397         * method to return a copy of this cookie.
398         */
399        public Object clone() {
400            try {
401                return super.clone();
402            } catch (CloneNotSupportedException e) {
403                throw new RuntimeException(e.getMessage());
404            }
405        }
406    
407        /**
408         * @return whether cookie is http only
409         * @since servlet 3.0
410         */
411        public boolean isHttpOnly() {
412            return httpOnly;
413        }
414    
415        /**
416         * @param httpOnly httpOnly setting
417         * @since servlet 3.0
418         */
419        public void setHttpOnly(boolean httpOnly) {
420            this.httpOnly = httpOnly;
421        }
422    }
423