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