1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.  Oracle designates this
9  * particular file as subject to the "Classpath" exception as provided
10  * by Oracle in the LICENSE file that accompanied this code.
11  *
12  * This code is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15  * version 2 for more details (a copy is included in the LICENSE file that
16  * accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License version
19  * 2 along with this work; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23  * or visit www.oracle.com if you need additional information or have any
24  * questions.
25  */
26 
27 package java.net;
28 
29 import java.util.Date;
30 import java.util.HashSet;
31 import java.util.List;
32 import java.util.Locale;
33 import java.util.NoSuchElementException;
34 import java.util.Objects;
35 import java.util.Set;
36 import java.util.StringTokenizer;
37 import java.util.TimeZone;
38 import libcore.net.http.HttpDate;
39 
40 /**
41  * An HttpCookie object represents an HTTP cookie, which carries state
42  * information between server and user agent. Cookie is widely adopted
43  * to create stateful sessions.
44  *
45  * <p> There are 3 HTTP cookie specifications:
46  * <blockquote>
47  *   Netscape draft<br>
48  *   RFC 2109 - <a href="http://www.ietf.org/rfc/rfc2109.txt">
49  * <i>http://www.ietf.org/rfc/rfc2109.txt</i></a><br>
50  *   RFC 2965 - <a href="http://www.ietf.org/rfc/rfc2965.txt">
51  * <i>http://www.ietf.org/rfc/rfc2965.txt</i></a>
52  * </blockquote>
53  *
54  * <p> HttpCookie class can accept all these 3 forms of syntax.
55  *
56  * @author Edward Wang
57  * @since 1.6
58  */
59 public final class HttpCookie implements Cloneable {
60     // BEGIN Android-added: Reserved name can't be HttpCookie name
61     private static final Set<String> RESERVED_NAMES = new HashSet<String>();
62 
63     static {
64         RESERVED_NAMES.add("comment");    //           RFC 2109  RFC 2965  RFC 6265
65         RESERVED_NAMES.add("commenturl"); //                     RFC 2965  RFC 6265
66         RESERVED_NAMES.add("discard");    //                     RFC 2965  RFC 6265
67         RESERVED_NAMES.add("domain");     // Netscape  RFC 2109  RFC 2965  RFC 6265
68         RESERVED_NAMES.add("expires");    // Netscape
69         RESERVED_NAMES.add("httponly");   //                               RFC 6265
70         RESERVED_NAMES.add("max-age");    //           RFC 2109  RFC 2965  RFC 6265
71         RESERVED_NAMES.add("path");       // Netscape  RFC 2109  RFC 2965  RFC 6265
72         RESERVED_NAMES.add("port");       //                     RFC 2965  RFC 6265
73         RESERVED_NAMES.add("secure");     // Netscape  RFC 2109  RFC 2965  RFC 6265
74         RESERVED_NAMES.add("version");    //           RFC 2109  RFC 2965  RFC 6265
75     }
76     // END Android-added: Reserved name can't be HttpCookie name
77 
78     // ---------------- Fields --------------
79 
80     // The value of the cookie itself.
81     private final String name;  // NAME= ... "$Name" style is reserved
82     private String value;       // value of NAME
83 
84     // Attributes encoded in the header's cookie fields.
85     private String comment;     // Comment=VALUE ... describes cookie's use
86     private String commentURL;  // CommentURL="http URL" ... describes cookie's use
87     private boolean toDiscard;  // Discard ... discard cookie unconditionally
88     private String domain;      // Domain=VALUE ... domain that sees cookie
89     private long maxAge = MAX_AGE_UNSPECIFIED;  // Max-Age=VALUE ... cookies auto-expire
90     private String path;        // Path=VALUE ... URLs that see the cookie
91     private String portlist;    // Port[="portlist"] ... the port cookie may be returned to
92     private boolean secure;     // Secure ... e.g. use SSL
93     private boolean httpOnly;   // HttpOnly ... i.e. not accessible to scripts
94     private int version = 1;    // Version=1 ... RFC 2965 style
95 
96     // The original header this cookie was consructed from, if it was
97     // constructed by parsing a header, otherwise null.
98     private final String header;
99 
100     //
101     // Android-changed: Fixed units, s/seconds/milliseconds/, in comment below.
102     // Hold the creation time (in milliseconds) of the http cookie for later
103     // expiration calculation
104     private final long whenCreated;
105 
106     // Since the positive and zero max-age have their meanings,
107     // this value serves as a hint as 'not specify max-age'
108     private final static long MAX_AGE_UNSPECIFIED = -1;
109 
110     // BEGIN Android-removed: Use libcore.net.http.HttpDate for parsing.
111     // date formats used by Netscape's cookie draft
112     // as well as formats seen on various sites
113     /*
114     private final static String[] COOKIE_DATE_FORMATS = {
115         "EEE',' dd-MMM-yyyy HH:mm:ss 'GMT'",
116         "EEE',' dd MMM yyyy HH:mm:ss 'GMT'",
117         "EEE MMM dd yyyy HH:mm:ss 'GMT'Z",
118         "EEE',' dd-MMM-yy HH:mm:ss 'GMT'",
119         "EEE',' dd MMM yy HH:mm:ss 'GMT'",
120         "EEE MMM dd yy HH:mm:ss 'GMT'Z"
121     };
122     */
123     // END Android-removed: Use libcore.net.http.HttpDate for parsing.
124 
125     // constant strings represent set-cookie header token
126     private final static String SET_COOKIE = "set-cookie:";
127     private final static String SET_COOKIE2 = "set-cookie2:";
128 
129     // ---------------- Ctors --------------
130 
131     /**
132      * Constructs a cookie with a specified name and value.
133      *
134      * <p> The name must conform to RFC 2965. That means it can contain
135      * only ASCII alphanumeric characters and cannot contain commas,
136      * semicolons, or white space or begin with a $ character. The cookie's
137      * name cannot be changed after creation.
138      *
139      * <p> The value can be anything the server chooses to send. Its
140      * value is probably of interest only to the server. The cookie's
141      * value can be changed after creation with the
142      * {@code setValue} method.
143      *
144      * <p> By default, cookies are created according to the RFC 2965
145      * cookie specification. The version can be changed with the
146      * {@code setVersion} method.
147      *
148      *
149      * @param  name
150      *         a {@code String} specifying the name of the cookie
151      *
152      * @param  value
153      *         a {@code String} specifying the value of the cookie
154      *
155      * @throws  IllegalArgumentException
156      *          if the cookie name contains illegal characters
157      * @throws  NullPointerException
158      *          if {@code name} is {@code null}
159      *
160      * @see #setValue
161      * @see #setVersion
162      */
HttpCookie(String name, String value)163     public HttpCookie(String name, String value) {
164         this(name, value, null /*header*/);
165     }
166 
HttpCookie(String name, String value, String header)167     private HttpCookie(String name, String value, String header) {
168         name = name.trim();
169         if (name.length() == 0 || !isToken(name) || name.charAt(0) == '$') {
170             throw new IllegalArgumentException("Illegal cookie name");
171         }
172 
173         this.name = name;
174         this.value = value;
175         toDiscard = false;
176         secure = false;
177 
178         whenCreated = System.currentTimeMillis();
179         portlist = null;
180         this.header = header;
181     }
182 
183     /**
184      * Constructs cookies from set-cookie or set-cookie2 header string.
185      * RFC 2965 section 3.2.2 set-cookie2 syntax indicates that one header line
186      * may contain more than one cookie definitions, so this is a static
187      * utility method instead of another constructor.
188      *
189      * @param  header
190      *         a {@code String} specifying the set-cookie header. The header
191      *         should start with "set-cookie", or "set-cookie2" token; or it
192      *         should have no leading token at all.
193      *
194      * @return  a List of cookie parsed from header line string
195      *
196      * @throws  IllegalArgumentException
197      *          if header string violates the cookie specification's syntax or
198      *          the cookie name contains illegal characters.
199      * @throws  NullPointerException
200      *          if the header string is {@code null}
201      */
parse(String header)202     public static List<HttpCookie> parse(String header) {
203         return parse(header, false);
204     }
205 
206     // Private version of parse() that will store the original header used to
207     // create the cookie, in the cookie itself. This can be useful for filtering
208     // Set-Cookie[2] headers, using the internal parsing logic defined in this
209     // class.
parse(String header, boolean retainHeader)210     private static List<HttpCookie> parse(String header, boolean retainHeader) {
211 
212         int version = guessCookieVersion(header);
213 
214         // if header start with set-cookie or set-cookie2, strip it off
215         if (startsWithIgnoreCase(header, SET_COOKIE2)) {
216             header = header.substring(SET_COOKIE2.length());
217         } else if (startsWithIgnoreCase(header, SET_COOKIE)) {
218             header = header.substring(SET_COOKIE.length());
219         }
220 
221         List<HttpCookie> cookies = new java.util.ArrayList<>();
222         // The Netscape cookie may have a comma in its expires attribute, while
223         // the comma is the delimiter in rfc 2965/2109 cookie header string.
224         // so the parse logic is slightly different
225         if (version == 0) {
226             // Netscape draft cookie
227             HttpCookie cookie = parseInternal(header, retainHeader);
228             cookie.setVersion(0);
229             cookies.add(cookie);
230         } else {
231             // rfc2965/2109 cookie
232             // if header string contains more than one cookie,
233             // it'll separate them with comma
234             List<String> cookieStrings = splitMultiCookies(header);
235             for (String cookieStr : cookieStrings) {
236                 HttpCookie cookie = parseInternal(cookieStr, retainHeader);
237                 cookie.setVersion(1);
238                 cookies.add(cookie);
239             }
240         }
241 
242         return cookies;
243     }
244 
245     // ---------------- Public operations --------------
246 
247     /**
248      * Reports whether this HTTP cookie has expired or not.
249      *
250      * @return  {@code true} to indicate this HTTP cookie has expired;
251      *          otherwise, {@code false}
252      */
hasExpired()253     public boolean hasExpired() {
254         if (maxAge == 0) return true;
255 
256         // if not specify max-age, this cookie should be
257         // discarded when user agent is to be closed, but
258         // it is not expired.
259         if (maxAge == MAX_AGE_UNSPECIFIED) return false;
260 
261         long deltaSecond = (System.currentTimeMillis() - whenCreated) / 1000;
262         if (deltaSecond > maxAge)
263             return true;
264         else
265             return false;
266     }
267 
268     /**
269      * Specifies a comment that describes a cookie's purpose.
270      * The comment is useful if the browser presents the cookie
271      * to the user. Comments are not supported by Netscape Version 0 cookies.
272      *
273      * @param  purpose
274      *         a {@code String} specifying the comment to display to the user
275      *
276      * @see  #getComment
277      */
setComment(String purpose)278     public void setComment(String purpose) {
279         comment = purpose;
280     }
281 
282     /**
283      * Returns the comment describing the purpose of this cookie, or
284      * {@code null} if the cookie has no comment.
285      *
286      * @return  a {@code String} containing the comment, or {@code null} if none
287      *
288      * @see  #setComment
289      */
getComment()290     public String getComment() {
291         return comment;
292     }
293 
294     /**
295      * Specifies a comment URL that describes a cookie's purpose.
296      * The comment URL is useful if the browser presents the cookie
297      * to the user. Comment URL is RFC 2965 only.
298      *
299      * @param  purpose
300      *         a {@code String} specifying the comment URL to display to the user
301      *
302      * @see  #getCommentURL
303      */
setCommentURL(String purpose)304     public void setCommentURL(String purpose) {
305         commentURL = purpose;
306     }
307 
308     /**
309      * Returns the comment URL describing the purpose of this cookie, or
310      * {@code null} if the cookie has no comment URL.
311      *
312      * @return  a {@code String} containing the comment URL, or {@code null}
313      *          if none
314      *
315      * @see  #setCommentURL
316      */
getCommentURL()317     public String getCommentURL() {
318         return commentURL;
319     }
320 
321     /**
322      * Specify whether user agent should discard the cookie unconditionally.
323      * This is RFC 2965 only attribute.
324      *
325      * @param  discard
326      *         {@code true} indicates to discard cookie unconditionally
327      *
328      * @see  #getDiscard
329      */
setDiscard(boolean discard)330     public void setDiscard(boolean discard) {
331         toDiscard = discard;
332     }
333 
334     /**
335      * Returns the discard attribute of the cookie
336      *
337      * @return  a {@code boolean} to represent this cookie's discard attribute
338      *
339      * @see  #setDiscard
340      */
getDiscard()341     public boolean getDiscard() {
342         return toDiscard;
343     }
344 
345     /**
346      * Specify the portlist of the cookie, which restricts the port(s)
347      * to which a cookie may be sent back in a Cookie header.
348      *
349      * @param  ports
350      *         a {@code String} specify the port list, which is comma separated
351      *         series of digits
352      *
353      * @see  #getPortlist
354      */
setPortlist(String ports)355     public void setPortlist(String ports) {
356         portlist = ports;
357     }
358 
359     /**
360      * Returns the port list attribute of the cookie
361      *
362      * @return  a {@code String} contains the port list or {@code null} if none
363      *
364      * @see  #setPortlist
365      */
getPortlist()366     public String getPortlist() {
367         return portlist;
368     }
369 
370     /**
371      * Specifies the domain within which this cookie should be presented.
372      *
373      * <p> The form of the domain name is specified by RFC 2965. A domain
374      * name begins with a dot ({@code .foo.com}) and means that
375      * the cookie is visible to servers in a specified Domain Name System
376      * (DNS) zone (for example, {@code www.foo.com}, but not
377      * {@code a.b.foo.com}). By default, cookies are only returned
378      * to the server that sent them.
379      *
380      * @param  pattern
381      *         a {@code String} containing the domain name within which this
382      *         cookie is visible; form is according to RFC 2965
383      *
384      * @see  #getDomain
385      */
setDomain(String pattern)386     public void setDomain(String pattern) {
387         if (pattern != null)
388             domain = pattern.toLowerCase();
389         else
390             domain = pattern;
391     }
392 
393     /**
394      * Returns the domain name set for this cookie. The form of the domain name
395      * is set by RFC 2965.
396      *
397      * @return  a {@code String} containing the domain name
398      *
399      * @see  #setDomain
400      */
getDomain()401     public String getDomain() {
402         return domain;
403     }
404 
405     /**
406      * Sets the maximum age of the cookie in seconds.
407      *
408      * <p> A positive value indicates that the cookie will expire
409      * after that many seconds have passed. Note that the value is
410      * the <i>maximum</i> age when the cookie will expire, not the cookie's
411      * current age.
412      *
413      * <p> A negative value means that the cookie is not stored persistently
414      * and will be deleted when the Web browser exits. A zero value causes the
415      * cookie to be deleted.
416      *
417      * @param  expiry
418      *         an integer specifying the maximum age of the cookie in seconds;
419      *         if zero, the cookie should be discarded immediately; otherwise,
420      *         the cookie's max age is unspecified.
421      *
422      * @see  #getMaxAge
423      */
setMaxAge(long expiry)424     public void setMaxAge(long expiry) {
425         maxAge = expiry;
426     }
427 
428     /**
429      * Returns the maximum age of the cookie, specified in seconds. By default,
430      * {@code -1} indicating the cookie will persist until browser shutdown.
431      *
432      * @return  an integer specifying the maximum age of the cookie in seconds
433      *
434      * @see  #setMaxAge
435      */
getMaxAge()436     public long getMaxAge() {
437         return maxAge;
438     }
439 
440     /**
441      * Specifies a path for the cookie to which the client should return
442      * the cookie.
443      *
444      * <p> The cookie is visible to all the pages in the directory
445      * you specify, and all the pages in that directory's subdirectories.
446      * A cookie's path must include the servlet that set the cookie,
447      * for example, <i>/catalog</i>, which makes the cookie
448      * visible to all directories on the server under <i>/catalog</i>.
449      *
450      * <p> Consult RFC 2965 (available on the Internet) for more
451      * information on setting path names for cookies.
452      *
453      * @param  uri
454      *         a {@code String} specifying a path
455      *
456      * @see  #getPath
457      */
setPath(String uri)458     public void setPath(String uri) {
459         path = uri;
460     }
461 
462     /**
463      * Returns the path on the server to which the browser returns this cookie.
464      * The cookie is visible to all subpaths on the server.
465      *
466      * @return  a {@code String} specifying a path that contains a servlet name,
467      *          for example, <i>/catalog</i>
468      *
469      * @see  #setPath
470      */
getPath()471     public String getPath() {
472         return path;
473     }
474 
475     /**
476      * Indicates whether the cookie should only be sent using a secure protocol,
477      * such as HTTPS or SSL.
478      *
479      * <p> The default value is {@code false}.
480      *
481      * @param  flag
482      *         If {@code true}, the cookie can only be sent over a secure
483      *         protocol like HTTPS. If {@code false}, it can be sent over
484      *         any protocol.
485      *
486      * @see  #getSecure
487      */
setSecure(boolean flag)488     public void setSecure(boolean flag) {
489         secure = flag;
490     }
491 
492     /**
493      * Returns {@code true} if sending this cookie should be restricted to a
494      * secure protocol, or {@code false} if the it can be sent using any
495      * protocol.
496      *
497      * @return  {@code false} if the cookie can be sent over any standard
498      *          protocol; otherwise, {@code true}
499      *
500      * @see  #setSecure
501      */
getSecure()502     public boolean getSecure() {
503         return secure;
504     }
505 
506     /**
507      * Returns the name of the cookie. The name cannot be changed after
508      * creation.
509      *
510      * @return  a {@code String} specifying the cookie's name
511      */
getName()512     public String getName() {
513         return name;
514     }
515 
516     /**
517      * Assigns a new value to a cookie after the cookie is created.
518      * If you use a binary value, you may want to use BASE64 encoding.
519      *
520      * <p> With Version 0 cookies, values should not contain white space,
521      * brackets, parentheses, equals signs, commas, double quotes, slashes,
522      * question marks, at signs, colons, and semicolons. Empty values may not
523      * behave the same way on all browsers.
524      *
525      * @param  newValue
526      *         a {@code String} specifying the new value
527      *
528      * @see  #getValue
529      */
setValue(String newValue)530     public void setValue(String newValue) {
531         value = newValue;
532     }
533 
534     /**
535      * Returns the value of the cookie.
536      *
537      * @return  a {@code String} containing the cookie's present value
538      *
539      * @see  #setValue
540      */
getValue()541     public String getValue() {
542         return value;
543     }
544 
545     /**
546      * Returns the version of the protocol this cookie complies with. Version 1
547      * complies with RFC 2965/2109, and version 0 complies with the original
548      * cookie specification drafted by Netscape. Cookies provided by a browser
549      * use and identify the browser's cookie version.
550      *
551      * @return  0 if the cookie complies with the original Netscape
552      *          specification; 1 if the cookie complies with RFC 2965/2109
553      *
554      * @see  #setVersion
555      */
getVersion()556     public int getVersion() {
557         return version;
558     }
559 
560     /**
561      * Sets the version of the cookie protocol this cookie complies
562      * with. Version 0 complies with the original Netscape cookie
563      * specification. Version 1 complies with RFC 2965/2109.
564      *
565      * @param  v
566      *         0 if the cookie should comply with the original Netscape
567      *         specification; 1 if the cookie should comply with RFC 2965/2109
568      *
569      * @throws  IllegalArgumentException
570      *          if {@code v} is neither 0 nor 1
571      *
572      * @see  #getVersion
573      */
setVersion(int v)574     public void setVersion(int v) {
575         if (v != 0 && v != 1) {
576             throw new IllegalArgumentException("cookie version should be 0 or 1");
577         }
578 
579         version = v;
580     }
581 
582     /**
583      * Returns {@code true} if this cookie contains the <i>HttpOnly</i>
584      * attribute. This means that the cookie should not be accessible to
585      * scripting engines, like javascript.
586      *
587      * @return  {@code true} if this cookie should be considered HTTPOnly
588      *
589      * @see  #setHttpOnly(boolean)
590      */
isHttpOnly()591     public boolean isHttpOnly() {
592         return httpOnly;
593     }
594 
595     /**
596      * Indicates whether the cookie should be considered HTTP Only. If set to
597      * {@code true} it means the cookie should not be accessible to scripting
598      * engines like javascript.
599      *
600      * @param  httpOnly
601      *         if {@code true} make the cookie HTTP only, i.e. only visible as
602      *         part of an HTTP request.
603      *
604      * @see  #isHttpOnly()
605      */
setHttpOnly(boolean httpOnly)606     public void setHttpOnly(boolean httpOnly) {
607         this.httpOnly = httpOnly;
608     }
609 
610     /**
611      * The utility method to check whether a host name is in a domain or not.
612      *
613      * <p> This concept is described in the cookie specification.
614      * To understand the concept, some terminologies need to be defined first:
615      * <blockquote>
616      * effective host name = hostname if host name contains dot<br>
617      * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
618      * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;or = hostname.local if not
619      * </blockquote>
620      * <p>Host A's name domain-matches host B's if:
621      * <blockquote><ul>
622      *   <li>their host name strings string-compare equal; or</li>
623      *   <li>A is a HDN string and has the form NB, where N is a non-empty
624      *   name string, B has the form .B', and B' is a HDN string.  (So,
625      *   x.y.com domain-matches .Y.com but not Y.com.)</li>
626      * </ul></blockquote>
627      *
628      * <p>A host isn't in a domain (RFC 2965 sec. 3.3.2) if:
629      * <blockquote><ul>
630      *   <li>The value for the Domain attribute contains no embedded dots,
631      *   and the value is not .local.</li>
632      *   <li>The effective host name that derives from the request-host does
633      *   not domain-match the Domain attribute.</li>
634      *   <li>The request-host is a HDN (not IP address) and has the form HD,
635      *   where D is the value of the Domain attribute, and H is a string
636      *   that contains one or more dots.</li>
637      * </ul></blockquote>
638      *
639      * <p>Examples:
640      * <blockquote><ul>
641      *   <li>A Set-Cookie2 from request-host y.x.foo.com for Domain=.foo.com
642      *   would be rejected, because H is y.x and contains a dot.</li>
643      *   <li>A Set-Cookie2 from request-host x.foo.com for Domain=.foo.com
644      *   would be accepted.</li>
645      *   <li>A Set-Cookie2 with Domain=.com or Domain=.com., will always be
646      *   rejected, because there is no embedded dot.</li>
647      *   <li>A Set-Cookie2 from request-host example for Domain=.local will
648      *   be accepted, because the effective host name for the request-
649      *   host is example.local, and example.local domain-matches .local.</li>
650      * </ul></blockquote>
651      *
652      * @param  domain
653      *         the domain name to check host name with
654      *
655      * @param  host
656      *         the host name in question
657      *
658      * @return  {@code true} if they domain-matches; {@code false} if not
659      */
domainMatches(String domain, String host)660     public static boolean domainMatches(String domain, String host) {
661         if (domain == null || host == null)
662             return false;
663 
664         // if there's no embedded dot in domain and domain is not .local
665         boolean isLocalDomain = ".local".equalsIgnoreCase(domain);
666         int embeddedDotInDomain = domain.indexOf('.');
667         if (embeddedDotInDomain == 0)
668             embeddedDotInDomain = domain.indexOf('.', 1);
669         if (!isLocalDomain
670             && (embeddedDotInDomain == -1 ||
671                 embeddedDotInDomain == domain.length() - 1))
672             return false;
673 
674         // if the host name contains no dot and the domain name
675         // is .local or host.local
676         int firstDotInHost = host.indexOf('.');
677         if (firstDotInHost == -1 &&
678             (isLocalDomain ||
679              domain.equalsIgnoreCase(host + ".local"))) {
680             return true;
681         }
682 
683         int domainLength = domain.length();
684         int lengthDiff = host.length() - domainLength;
685         if (lengthDiff == 0) {
686             // if the host name and the domain name are just string-compare euqal
687             return host.equalsIgnoreCase(domain);
688         }
689         else if (lengthDiff > 0) {
690             // need to check H & D component
691             String H = host.substring(0, lengthDiff);
692             String D = host.substring(lengthDiff);
693 
694             // BEGIN Android-changed: App compat reason
695             // 1) Disregard RFC 2965 sec. 3.3.2, the "The request-host is a HDN..."
696             // 2) match "foo.local" for domain ".local".
697             // return (H.indexOf('.') == -1 && D.equalsIgnoreCase(domain));
698             return D.equalsIgnoreCase(domain) && ((domain.startsWith(".") && isFullyQualifiedDomainName(domain, 1))
699                 || isLocalDomain);
700             // END Android-changed: App compat reason
701         }
702         else if (lengthDiff == -1) {
703             // if domain is actually .host
704             return (domain.charAt(0) == '.' &&
705                         host.equalsIgnoreCase(domain.substring(1)));
706         }
707 
708         return false;
709     }
710 
711     // BEGIN Android-added: App compat reason
isFullyQualifiedDomainName(String s, int firstCharacter)712     private static boolean isFullyQualifiedDomainName(String s, int firstCharacter) {
713         int dotPosition = s.indexOf('.', firstCharacter + 1);
714         return dotPosition != -1 && dotPosition < s.length() - 1;
715     }
716     // END Android-added: App compat reason
717 
718     /**
719      * Constructs a cookie header string representation of this cookie,
720      * which is in the format defined by corresponding cookie specification,
721      * but without the leading "Cookie:" token.
722      *
723      * @return  a string form of the cookie. The string has the defined format
724      */
725     @Override
toString()726     public String toString() {
727         if (getVersion() > 0) {
728             return toRFC2965HeaderString();
729         } else {
730             return toNetscapeHeaderString();
731         }
732     }
733 
734     /**
735      * Test the equality of two HTTP cookies.
736      *
737      * <p> The result is {@code true} only if two cookies come from same domain
738      * (case-insensitive), have same name (case-insensitive), and have same path
739      * (case-sensitive).
740      *
741      * @return  {@code true} if two HTTP cookies equal to each other;
742      *          otherwise, {@code false}
743      */
744     @Override
equals(Object obj)745     public boolean equals(Object obj) {
746         if (obj == this)
747             return true;
748         if (!(obj instanceof HttpCookie))
749             return false;
750         HttpCookie other = (HttpCookie)obj;
751 
752         // One http cookie equals to another cookie (RFC 2965 sec. 3.3.3) if:
753         //   1. they come from same domain (case-insensitive),
754         //   2. have same name (case-insensitive),
755         //   3. and have same path (case-sensitive).
756         return equalsIgnoreCase(getName(), other.getName()) &&
757                equalsIgnoreCase(getDomain(), other.getDomain()) &&
758                Objects.equals(getPath(), other.getPath());
759     }
760 
761     /**
762      * Returns the hash code of this HTTP cookie. The result is the sum of
763      * hash code value of three significant components of this cookie: name,
764      * domain, and path. That is, the hash code is the value of the expression:
765      * <blockquote>
766      * getName().toLowerCase().hashCode()<br>
767      * + getDomain().toLowerCase().hashCode()<br>
768      * + getPath().hashCode()
769      * </blockquote>
770      *
771      * @return  this HTTP cookie's hash code
772      */
773     @Override
hashCode()774     public int hashCode() {
775         int h1 = name.toLowerCase().hashCode();
776         int h2 = (domain!=null) ? domain.toLowerCase().hashCode() : 0;
777         int h3 = (path!=null) ? path.hashCode() : 0;
778 
779         return h1 + h2 + h3;
780     }
781 
782     /**
783      * Create and return a copy of this object.
784      *
785      * @return  a clone of this HTTP cookie
786      */
787     @Override
clone()788     public Object clone() {
789         try {
790             return super.clone();
791         } catch (CloneNotSupportedException e) {
792             throw new RuntimeException(e.getMessage());
793         }
794     }
795 
796     // ---------------- Private operations --------------
797 
798     // Note -- disabled for now to allow full Netscape compatibility
799     // from RFC 2068, token special case characters
800     //
801     // private static final String tspecials = "()<>@,;:\\\"/[]?={} \t";
802     // Android-changed: App compat reason. Disallow "=\t" as token
803     // private static final String tspecials = ",; ";  // deliberately includes space
804     private static final String tspecials = ",;= \t";
805 
806     /*
807      * Tests a string and returns true if the string counts as a token.
808      *
809      * @param  value
810      *         the {@code String} to be tested
811      *
812      * @return  {@code true} if the {@code String} is a token;
813      *          {@code false} if it is not
814      */
isToken(String value)815     private static boolean isToken(String value) {
816         // Android-added: Reserved name can't be a token
817         if (RESERVED_NAMES.contains(value.toLowerCase(Locale.US))) {
818             return false;
819         }
820 
821         int len = value.length();
822 
823         for (int i = 0; i < len; i++) {
824             char c = value.charAt(i);
825 
826             if (c < 0x20 || c >= 0x7f || tspecials.indexOf(c) != -1)
827                 return false;
828         }
829         return true;
830     }
831 
832     /*
833      * Parse header string to cookie object.
834      *
835      * @param  header
836      *         header string; should contain only one NAME=VALUE pair
837      *
838      * @return  an HttpCookie being extracted
839      *
840      * @throws  IllegalArgumentException
841      *          if header string violates the cookie specification
842      */
parseInternal(String header, boolean retainHeader)843     private static HttpCookie parseInternal(String header,
844                                             boolean retainHeader)
845     {
846         HttpCookie cookie = null;
847         String namevaluePair = null;
848 
849         StringTokenizer tokenizer = new StringTokenizer(header, ";");
850 
851         // there should always have at least on name-value pair;
852         // it's cookie's name
853         try {
854             namevaluePair = tokenizer.nextToken();
855             int index = namevaluePair.indexOf('=');
856             if (index != -1) {
857                 String name = namevaluePair.substring(0, index).trim();
858                 String value = namevaluePair.substring(index + 1).trim();
859                 if (retainHeader)
860                     cookie = new HttpCookie(name,
861                                             stripOffSurroundingQuote(value),
862                                             header);
863                 else
864                     cookie = new HttpCookie(name,
865                                             stripOffSurroundingQuote(value));
866             } else {
867                 // no "=" in name-value pair; it's an error
868                 throw new IllegalArgumentException("Invalid cookie name-value pair");
869             }
870         } catch (NoSuchElementException ignored) {
871             throw new IllegalArgumentException("Empty cookie header string");
872         }
873 
874         // remaining name-value pairs are cookie's attributes
875         while (tokenizer.hasMoreTokens()) {
876             namevaluePair = tokenizer.nextToken();
877             int index = namevaluePair.indexOf('=');
878             String name, value;
879             if (index != -1) {
880                 name = namevaluePair.substring(0, index).trim();
881                 value = namevaluePair.substring(index + 1).trim();
882             } else {
883                 name = namevaluePair.trim();
884                 value = null;
885             }
886 
887             // assign attribute to cookie
888             assignAttribute(cookie, name, value);
889         }
890 
891         return cookie;
892     }
893 
894     /*
895      * assign cookie attribute value to attribute name;
896      * use a map to simulate method dispatch
897      */
898     static interface CookieAttributeAssignor {
assign(HttpCookie cookie, String attrName, String attrValue)899             public void assign(HttpCookie cookie,
900                                String attrName,
901                                String attrValue);
902     }
903     static final java.util.Map<String, CookieAttributeAssignor> assignors =
904             new java.util.HashMap<>();
905     static {
906         assignors.put("comment", new CookieAttributeAssignor() {
907                 public void assign(HttpCookie cookie,
908                                    String attrName,
909                                    String attrValue) {
910                     if (cookie.getComment() == null)
911                         cookie.setComment(attrValue);
912                 }
913             });
914         assignors.put("commenturl", new CookieAttributeAssignor() {
915                 public void assign(HttpCookie cookie,
916                                    String attrName,
917                                    String attrValue) {
918                     if (cookie.getCommentURL() == null)
919                         cookie.setCommentURL(attrValue);
920                 }
921             });
922         assignors.put("discard", new CookieAttributeAssignor() {
923                 public void assign(HttpCookie cookie,
924                                    String attrName,
925                                    String attrValue) {
926                     cookie.setDiscard(true);
927                 }
928             });
929         assignors.put("domain", new CookieAttributeAssignor(){
930                 public void assign(HttpCookie cookie,
931                                    String attrName,
932                                    String attrValue) {
933                     if (cookie.getDomain() == null)
934                         cookie.setDomain(attrValue);
935                 }
936             });
937         assignors.put("max-age", new CookieAttributeAssignor(){
938                 public void assign(HttpCookie cookie,
939                                    String attrName,
940                                    String attrValue) {
941                     try {
942                         long maxage = Long.parseLong(attrValue);
943                         if (cookie.getMaxAge() == MAX_AGE_UNSPECIFIED)
944                             cookie.setMaxAge(maxage);
945                     } catch (NumberFormatException ignored) {
946                         throw new IllegalArgumentException(
947                                 "Illegal cookie max-age attribute");
948                     }
949                 }
950             });
951         assignors.put("path", new CookieAttributeAssignor(){
952                 public void assign(HttpCookie cookie,
953                                    String attrName,
954                                    String attrValue) {
955                     if (cookie.getPath() == null)
956                         cookie.setPath(attrValue);
957                 }
958             });
959         assignors.put("port", new CookieAttributeAssignor(){
960                 public void assign(HttpCookie cookie,
961                                    String attrName,
962                                    String attrValue) {
963                     if (cookie.getPortlist() == null)
964                         cookie.setPortlist(attrValue == null ? "" : attrValue);
965                 }
966             });
967         assignors.put("secure", new CookieAttributeAssignor(){
968                 public void assign(HttpCookie cookie,
969                                    String attrName,
970                                    String attrValue) {
971                     cookie.setSecure(true);
972                 }
973             });
974         assignors.put("httponly", new CookieAttributeAssignor(){
975                 public void assign(HttpCookie cookie,
976                                    String attrName,
977                                    String attrValue) {
978                     cookie.setHttpOnly(true);
979                 }
980             });
981         assignors.put("version", new CookieAttributeAssignor(){
982                 public void assign(HttpCookie cookie,
983                                    String attrName,
984                                    String attrValue) {
985                     try {
986                         int version = Integer.parseInt(attrValue);
987                         cookie.setVersion(version);
988                     } catch (NumberFormatException ignored) {
989                         // Just ignore bogus version, it will default to 0 or 1
990                     }
991                 }
992             });
993         assignors.put("expires", new CookieAttributeAssignor(){ // Netscape only
994                 public void assign(HttpCookie cookie,
995                                    String attrName,
996                                    String attrValue) {
997                     if (cookie.getMaxAge() == MAX_AGE_UNSPECIFIED) {
998                         // BEGIN Android-changed: Use HttpDate for date parsing.
999                         // it accepts broader set of date formats.
1000                         // cookie.setMaxAge(cookie.expiryDate2DeltaSeconds(attrValue));
1001                         // Android-changed: Altered max age calculation to avoid setting
1002                         // it to MAX_AGE_UNSPECIFIED (-1) if "expires" is one second in past.
1003                         Date date = HttpDate.parse(attrValue);
1004                         long maxAgeInSeconds = 0;
1005                         if (date != null) {
1006                             maxAgeInSeconds = (date.getTime() - cookie.whenCreated) / 1000;
1007                             // Avoid MAX_AGE_UNSPECIFIED
1008                             if (maxAgeInSeconds == MAX_AGE_UNSPECIFIED) {
1009                                 maxAgeInSeconds = 0;
1010                             }
1011                         }
1012                         cookie.setMaxAge(maxAgeInSeconds);
1013                         // END Android-changed: Use HttpDate for date parsing.
1014                     }
1015                 }
1016             });
1017     }
assignAttribute(HttpCookie cookie, String attrName, String attrValue)1018     private static void assignAttribute(HttpCookie cookie,
1019                                         String attrName,
1020                                         String attrValue)
1021     {
1022         // strip off the surrounding "-sign if there's any
1023         attrValue = stripOffSurroundingQuote(attrValue);
1024 
1025         CookieAttributeAssignor assignor = assignors.get(attrName.toLowerCase());
1026         if (assignor != null) {
1027             assignor.assign(cookie, attrName, attrValue);
1028         } else {
1029             // Ignore the attribute as per RFC 2965
1030         }
1031     }
1032 
1033     // BEGIN Android-removed: Android doesn't use JavaNetHttpCookieAccess
1034     /*
1035     static {
1036         sun.misc.SharedSecrets.setJavaNetHttpCookieAccess(
1037             new sun.misc.JavaNetHttpCookieAccess() {
1038                 public List<HttpCookie> parse(String header) {
1039                     return HttpCookie.parse(header, true);
1040                 }
1041 
1042                 public String header(HttpCookie cookie) {
1043                     return cookie.header;
1044                 }
1045             }
1046         );
1047     }
1048     */
1049     // END Android-removed: Android doesn't use JavaNetHttpCookieAccess
1050 
1051     /*
1052      * Returns the original header this cookie was consructed from, if it was
1053      * constructed by parsing a header, otherwise null.
1054      */
header()1055     private String header() {
1056         return header;
1057     }
1058 
1059     /*
1060      * Constructs a string representation of this cookie. The string format is
1061      * as Netscape spec, but without leading "Cookie:" token.
1062      */
toNetscapeHeaderString()1063     private String toNetscapeHeaderString() {
1064         return getName() + "=" + getValue();
1065     }
1066 
1067     /*
1068      * Constructs a string representation of this cookie. The string format is
1069      * as RFC 2965/2109, but without leading "Cookie:" token.
1070      */
toRFC2965HeaderString()1071     private String toRFC2965HeaderString() {
1072         StringBuilder sb = new StringBuilder();
1073 
1074         sb.append(getName()).append("=\"").append(getValue()).append('"');
1075         if (getPath() != null)
1076             sb.append(";$Path=\"").append(getPath()).append('"');
1077         if (getDomain() != null)
1078             sb.append(";$Domain=\"").append(getDomain()).append('"');
1079         if (getPortlist() != null)
1080             sb.append(";$Port=\"").append(getPortlist()).append('"');
1081 
1082         return sb.toString();
1083     }
1084 
1085     static final TimeZone GMT = TimeZone.getTimeZone("GMT");
1086 
1087     // BEGIN Android-removed: not used.
1088     /*
1089      * @param  dateString
1090      *         a date string in one of the formats defined in Netscape cookie spec
1091      *
1092      * @return  delta seconds between this cookie's creation time and the time
1093      *          specified by dateString
1094      *
1095     private long expiryDate2DeltaSeconds(String dateString) {
1096         Calendar cal = new GregorianCalendar(GMT);
1097         for (int i = 0; i < COOKIE_DATE_FORMATS.length; i++) {
1098             SimpleDateFormat df = new SimpleDateFormat(COOKIE_DATE_FORMATS[i],
1099                                                        Locale.US);
1100             cal.set(1970, 0, 1, 0, 0, 0);
1101             df.setTimeZone(GMT);
1102             df.setLenient(false);
1103             df.set2DigitYearStart(cal.getTime());
1104             try {
1105                 cal.setTime(df.parse(dateString));
1106                 if (!COOKIE_DATE_FORMATS[i].contains("yyyy")) {
1107                     // 2-digit years following the standard set
1108                     // out it rfc 6265
1109                     int year = cal.get(Calendar.YEAR);
1110                     year %= 100;
1111                     if (year < 70) {
1112                         year += 2000;
1113                     } else {
1114                         year += 1900;
1115                     }
1116                     cal.set(Calendar.YEAR, year);
1117                 }
1118                 return (cal.getTimeInMillis() - whenCreated) / 1000;
1119             } catch (Exception e) {
1120                 // Ignore, try the next date format
1121             }
1122         }
1123         return 0;
1124     }
1125     */
1126     // END Android-removed: not used.
1127 
1128     /*
1129      * try to guess the cookie version through set-cookie header string
1130      */
guessCookieVersion(String header)1131     private static int guessCookieVersion(String header) {
1132         int version = 0;
1133 
1134         header = header.toLowerCase();
1135         if (header.indexOf("expires=") != -1) {
1136             // only netscape cookie using 'expires'
1137             version = 0;
1138         } else if (header.indexOf("version=") != -1) {
1139             // version is mandatory for rfc 2965/2109 cookie
1140             version = 1;
1141         } else if (header.indexOf("max-age") != -1) {
1142             // rfc 2965/2109 use 'max-age'
1143             version = 1;
1144         } else if (startsWithIgnoreCase(header, SET_COOKIE2)) {
1145             // only rfc 2965 cookie starts with 'set-cookie2'
1146             version = 1;
1147         }
1148 
1149         return version;
1150     }
1151 
stripOffSurroundingQuote(String str)1152     private static String stripOffSurroundingQuote(String str) {
1153         if (str != null && str.length() > 2 &&
1154             str.charAt(0) == '"' && str.charAt(str.length() - 1) == '"') {
1155             return str.substring(1, str.length() - 1);
1156         }
1157         if (str != null && str.length() > 2 &&
1158             str.charAt(0) == '\'' && str.charAt(str.length() - 1) == '\'') {
1159             return str.substring(1, str.length() - 1);
1160         }
1161         return str;
1162     }
1163 
equalsIgnoreCase(String s, String t)1164     private static boolean equalsIgnoreCase(String s, String t) {
1165         if (s == t) return true;
1166         if ((s != null) && (t != null)) {
1167             return s.equalsIgnoreCase(t);
1168         }
1169         return false;
1170     }
1171 
startsWithIgnoreCase(String s, String start)1172     private static boolean startsWithIgnoreCase(String s, String start) {
1173         if (s == null || start == null) return false;
1174 
1175         if (s.length() >= start.length() &&
1176                 start.equalsIgnoreCase(s.substring(0, start.length()))) {
1177             return true;
1178         }
1179 
1180         return false;
1181     }
1182 
1183     /*
1184      * Split cookie header string according to rfc 2965:
1185      *   1) split where it is a comma;
1186      *   2) but not the comma surrounding by double-quotes, which is the comma
1187      *      inside port list or embeded URIs.
1188      *
1189      * @param  header
1190      *         the cookie header string to split
1191      *
1192      * @return  list of strings; never null
1193      */
splitMultiCookies(String header)1194     private static List<String> splitMultiCookies(String header) {
1195         List<String> cookies = new java.util.ArrayList<String>();
1196         int quoteCount = 0;
1197         int p, q;
1198 
1199         for (p = 0, q = 0; p < header.length(); p++) {
1200             char c = header.charAt(p);
1201             if (c == '"') quoteCount++;
1202             if (c == ',' && (quoteCount % 2 == 0)) {
1203                 // it is comma and not surrounding by double-quotes
1204                 cookies.add(header.substring(q, p));
1205                 q = p + 1;
1206             }
1207         }
1208 
1209         cookies.add(header.substring(q));
1210 
1211         return cookies;
1212     }
1213 }
1214