Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/net/HttpCookie.java
38829 views
/*1* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.net;2627import java.util.List;28import java.util.StringTokenizer;29import java.util.NoSuchElementException;30import java.text.SimpleDateFormat;31import java.util.TimeZone;32import java.util.Calendar;33import java.util.GregorianCalendar;34import java.util.Date;35import java.util.Locale;36import java.util.Objects;3738/**39* An HttpCookie object represents an HTTP cookie, which carries state40* information between server and user agent. Cookie is widely adopted41* to create stateful sessions.42*43* <p> There are 3 HTTP cookie specifications:44* <blockquote>45* Netscape draft<br>46* RFC 2109 - <a href="http://www.ietf.org/rfc/rfc2109.txt">47* <i>http://www.ietf.org/rfc/rfc2109.txt</i></a><br>48* RFC 2965 - <a href="http://www.ietf.org/rfc/rfc2965.txt">49* <i>http://www.ietf.org/rfc/rfc2965.txt</i></a>50* </blockquote>51*52* <p> HttpCookie class can accept all these 3 forms of syntax.53*54* @author Edward Wang55* @since 1.656*/57public final class HttpCookie implements Cloneable {58// ---------------- Fields --------------5960// The value of the cookie itself.61private final String name; // NAME= ... "$Name" style is reserved62private String value; // value of NAME6364// Attributes encoded in the header's cookie fields.65private String comment; // Comment=VALUE ... describes cookie's use66private String commentURL; // CommentURL="http URL" ... describes cookie's use67private boolean toDiscard; // Discard ... discard cookie unconditionally68private String domain; // Domain=VALUE ... domain that sees cookie69private long maxAge = MAX_AGE_UNSPECIFIED; // Max-Age=VALUE ... cookies auto-expire70private String path; // Path=VALUE ... URLs that see the cookie71private String portlist; // Port[="portlist"] ... the port cookie may be returned to72private boolean secure; // Secure ... e.g. use SSL73private boolean httpOnly; // HttpOnly ... i.e. not accessible to scripts74private int version = 1; // Version=1 ... RFC 2965 style7576// The original header this cookie was consructed from, if it was77// constructed by parsing a header, otherwise null.78private final String header;7980// Hold the creation time (in seconds) of the http cookie for later81// expiration calculation82private final long whenCreated;8384// Since the positive and zero max-age have their meanings,85// this value serves as a hint as 'not specify max-age'86private final static long MAX_AGE_UNSPECIFIED = -1;8788// date formats used by Netscape's cookie draft89// as well as formats seen on various sites90private final static String[] COOKIE_DATE_FORMATS = {91"EEE',' dd-MMM-yyyy HH:mm:ss 'GMT'",92"EEE',' dd MMM yyyy HH:mm:ss 'GMT'",93"EEE MMM dd yyyy HH:mm:ss 'GMT'Z",94"EEE',' dd-MMM-yy HH:mm:ss 'GMT'",95"EEE',' dd MMM yy HH:mm:ss 'GMT'",96"EEE MMM dd yy HH:mm:ss 'GMT'Z"97};9899// constant strings represent set-cookie header token100private final static String SET_COOKIE = "set-cookie:";101private final static String SET_COOKIE2 = "set-cookie2:";102103// ---------------- Ctors --------------104105/**106* Constructs a cookie with a specified name and value.107*108* <p> The name must conform to RFC 2965. That means it can contain109* only ASCII alphanumeric characters and cannot contain commas,110* semicolons, or white space or begin with a $ character. The cookie's111* name cannot be changed after creation.112*113* <p> The value can be anything the server chooses to send. Its114* value is probably of interest only to the server. The cookie's115* value can be changed after creation with the116* {@code setValue} method.117*118* <p> By default, cookies are created according to the RFC 2965119* cookie specification. The version can be changed with the120* {@code setVersion} method.121*122*123* @param name124* a {@code String} specifying the name of the cookie125*126* @param value127* a {@code String} specifying the value of the cookie128*129* @throws IllegalArgumentException130* if the cookie name contains illegal characters131* @throws NullPointerException132* if {@code name} is {@code null}133*134* @see #setValue135* @see #setVersion136*/137public HttpCookie(String name, String value) {138this(name, value, null /*header*/);139}140141private HttpCookie(String name, String value, String header) {142name = name.trim();143if (name.length() == 0 || !isToken(name) || name.charAt(0) == '$') {144throw new IllegalArgumentException("Illegal cookie name");145}146147this.name = name;148this.value = value;149toDiscard = false;150secure = false;151152whenCreated = System.currentTimeMillis();153portlist = null;154this.header = header;155}156157/**158* Constructs cookies from set-cookie or set-cookie2 header string.159* RFC 2965 section 3.2.2 set-cookie2 syntax indicates that one header line160* may contain more than one cookie definitions, so this is a static161* utility method instead of another constructor.162*163* @param header164* a {@code String} specifying the set-cookie header. The header165* should start with "set-cookie", or "set-cookie2" token; or it166* should have no leading token at all.167*168* @return a List of cookie parsed from header line string169*170* @throws IllegalArgumentException171* if header string violates the cookie specification's syntax or172* the cookie name contains illegal characters.173* @throws NullPointerException174* if the header string is {@code null}175*/176public static List<HttpCookie> parse(String header) {177return parse(header, false);178}179180// Private version of parse() that will store the original header used to181// create the cookie, in the cookie itself. This can be useful for filtering182// Set-Cookie[2] headers, using the internal parsing logic defined in this183// class.184private static List<HttpCookie> parse(String header, boolean retainHeader) {185186int version = guessCookieVersion(header);187188// if header start with set-cookie or set-cookie2, strip it off189if (startsWithIgnoreCase(header, SET_COOKIE2)) {190header = header.substring(SET_COOKIE2.length());191} else if (startsWithIgnoreCase(header, SET_COOKIE)) {192header = header.substring(SET_COOKIE.length());193}194195List<HttpCookie> cookies = new java.util.ArrayList<>();196// The Netscape cookie may have a comma in its expires attribute, while197// the comma is the delimiter in rfc 2965/2109 cookie header string.198// so the parse logic is slightly different199if (version == 0) {200// Netscape draft cookie201HttpCookie cookie = parseInternal(header, retainHeader);202cookie.setVersion(0);203cookies.add(cookie);204} else {205// rfc2965/2109 cookie206// if header string contains more than one cookie,207// it'll separate them with comma208List<String> cookieStrings = splitMultiCookies(header);209for (String cookieStr : cookieStrings) {210HttpCookie cookie = parseInternal(cookieStr, retainHeader);211cookie.setVersion(1);212cookies.add(cookie);213}214}215216return cookies;217}218219// ---------------- Public operations --------------220221/**222* Reports whether this HTTP cookie has expired or not.223*224* @return {@code true} to indicate this HTTP cookie has expired;225* otherwise, {@code false}226*/227public boolean hasExpired() {228if (maxAge == 0) return true;229230// if not specify max-age, this cookie should be231// discarded when user agent is to be closed, but232// it is not expired.233if (maxAge == MAX_AGE_UNSPECIFIED) return false;234235long deltaSecond = (System.currentTimeMillis() - whenCreated) / 1000;236if (deltaSecond > maxAge)237return true;238else239return false;240}241242/**243* Specifies a comment that describes a cookie's purpose.244* The comment is useful if the browser presents the cookie245* to the user. Comments are not supported by Netscape Version 0 cookies.246*247* @param purpose248* a {@code String} specifying the comment to display to the user249*250* @see #getComment251*/252public void setComment(String purpose) {253comment = purpose;254}255256/**257* Returns the comment describing the purpose of this cookie, or258* {@code null} if the cookie has no comment.259*260* @return a {@code String} containing the comment, or {@code null} if none261*262* @see #setComment263*/264public String getComment() {265return comment;266}267268/**269* Specifies a comment URL that describes a cookie's purpose.270* The comment URL is useful if the browser presents the cookie271* to the user. Comment URL is RFC 2965 only.272*273* @param purpose274* a {@code String} specifying the comment URL to display to the user275*276* @see #getCommentURL277*/278public void setCommentURL(String purpose) {279commentURL = purpose;280}281282/**283* Returns the comment URL describing the purpose of this cookie, or284* {@code null} if the cookie has no comment URL.285*286* @return a {@code String} containing the comment URL, or {@code null}287* if none288*289* @see #setCommentURL290*/291public String getCommentURL() {292return commentURL;293}294295/**296* Specify whether user agent should discard the cookie unconditionally.297* This is RFC 2965 only attribute.298*299* @param discard300* {@code true} indicates to discard cookie unconditionally301*302* @see #getDiscard303*/304public void setDiscard(boolean discard) {305toDiscard = discard;306}307308/**309* Returns the discard attribute of the cookie310*311* @return a {@code boolean} to represent this cookie's discard attribute312*313* @see #setDiscard314*/315public boolean getDiscard() {316return toDiscard;317}318319/**320* Specify the portlist of the cookie, which restricts the port(s)321* to which a cookie may be sent back in a Cookie header.322*323* @param ports324* a {@code String} specify the port list, which is comma separated325* series of digits326*327* @see #getPortlist328*/329public void setPortlist(String ports) {330portlist = ports;331}332333/**334* Returns the port list attribute of the cookie335*336* @return a {@code String} contains the port list or {@code null} if none337*338* @see #setPortlist339*/340public String getPortlist() {341return portlist;342}343344/**345* Specifies the domain within which this cookie should be presented.346*347* <p> The form of the domain name is specified by RFC 2965. A domain348* name begins with a dot ({@code .foo.com}) and means that349* the cookie is visible to servers in a specified Domain Name System350* (DNS) zone (for example, {@code www.foo.com}, but not351* {@code a.b.foo.com}). By default, cookies are only returned352* to the server that sent them.353*354* @param pattern355* a {@code String} containing the domain name within which this356* cookie is visible; form is according to RFC 2965357*358* @see #getDomain359*/360public void setDomain(String pattern) {361if (pattern != null)362domain = pattern.toLowerCase();363else364domain = pattern;365}366367/**368* Returns the domain name set for this cookie. The form of the domain name369* is set by RFC 2965.370*371* @return a {@code String} containing the domain name372*373* @see #setDomain374*/375public String getDomain() {376return domain;377}378379/**380* Sets the maximum age of the cookie in seconds.381*382* <p> A positive value indicates that the cookie will expire383* after that many seconds have passed. Note that the value is384* the <i>maximum</i> age when the cookie will expire, not the cookie's385* current age.386*387* <p> A negative value means that the cookie is not stored persistently388* and will be deleted when the Web browser exits. A zero value causes the389* cookie to be deleted.390*391* @param expiry392* an integer specifying the maximum age of the cookie in seconds;393* if zero, the cookie should be discarded immediately; otherwise,394* the cookie's max age is unspecified.395*396* @see #getMaxAge397*/398public void setMaxAge(long expiry) {399maxAge = expiry;400}401402/**403* Returns the maximum age of the cookie, specified in seconds. By default,404* {@code -1} indicating the cookie will persist until browser shutdown.405*406* @return an integer specifying the maximum age of the cookie in seconds407*408* @see #setMaxAge409*/410public long getMaxAge() {411return maxAge;412}413414/**415* Specifies a path for the cookie to which the client should return416* the cookie.417*418* <p> The cookie is visible to all the pages in the directory419* you specify, and all the pages in that directory's subdirectories.420* A cookie's path must include the servlet that set the cookie,421* for example, <i>/catalog</i>, which makes the cookie422* visible to all directories on the server under <i>/catalog</i>.423*424* <p> Consult RFC 2965 (available on the Internet) for more425* information on setting path names for cookies.426*427* @param uri428* a {@code String} specifying a path429*430* @see #getPath431*/432public void setPath(String uri) {433path = uri;434}435436/**437* Returns the path on the server to which the browser returns this cookie.438* The cookie is visible to all subpaths on the server.439*440* @return a {@code String} specifying a path that contains a servlet name,441* for example, <i>/catalog</i>442*443* @see #setPath444*/445public String getPath() {446return path;447}448449/**450* Indicates whether the cookie should only be sent using a secure protocol,451* such as HTTPS or SSL.452*453* <p> The default value is {@code false}.454*455* @param flag456* If {@code true}, the cookie can only be sent over a secure457* protocol like HTTPS. If {@code false}, it can be sent over458* any protocol.459*460* @see #getSecure461*/462public void setSecure(boolean flag) {463secure = flag;464}465466/**467* Returns {@code true} if sending this cookie should be restricted to a468* secure protocol, or {@code false} if the it can be sent using any469* protocol.470*471* @return {@code false} if the cookie can be sent over any standard472* protocol; otherwise, {@code true}473*474* @see #setSecure475*/476public boolean getSecure() {477return secure;478}479480/**481* Returns the name of the cookie. The name cannot be changed after482* creation.483*484* @return a {@code String} specifying the cookie's name485*/486public String getName() {487return name;488}489490/**491* Assigns a new value to a cookie after the cookie is created.492* If you use a binary value, you may want to use BASE64 encoding.493*494* <p> With Version 0 cookies, values should not contain white space,495* brackets, parentheses, equals signs, commas, double quotes, slashes,496* question marks, at signs, colons, and semicolons. Empty values may not497* behave the same way on all browsers.498*499* @param newValue500* a {@code String} specifying the new value501*502* @see #getValue503*/504public void setValue(String newValue) {505value = newValue;506}507508/**509* Returns the value of the cookie.510*511* @return a {@code String} containing the cookie's present value512*513* @see #setValue514*/515public String getValue() {516return value;517}518519/**520* Returns the version of the protocol this cookie complies with. Version 1521* complies with RFC 2965/2109, and version 0 complies with the original522* cookie specification drafted by Netscape. Cookies provided by a browser523* use and identify the browser's cookie version.524*525* @return 0 if the cookie complies with the original Netscape526* specification; 1 if the cookie complies with RFC 2965/2109527*528* @see #setVersion529*/530public int getVersion() {531return version;532}533534/**535* Sets the version of the cookie protocol this cookie complies536* with. Version 0 complies with the original Netscape cookie537* specification. Version 1 complies with RFC 2965/2109.538*539* @param v540* 0 if the cookie should comply with the original Netscape541* specification; 1 if the cookie should comply with RFC 2965/2109542*543* @throws IllegalArgumentException544* if {@code v} is neither 0 nor 1545*546* @see #getVersion547*/548public void setVersion(int v) {549if (v != 0 && v != 1) {550throw new IllegalArgumentException("cookie version should be 0 or 1");551}552553version = v;554}555556/**557* Returns {@code true} if this cookie contains the <i>HttpOnly</i>558* attribute. This means that the cookie should not be accessible to559* scripting engines, like javascript.560*561* @return {@code true} if this cookie should be considered HTTPOnly562*563* @see #setHttpOnly(boolean)564*/565public boolean isHttpOnly() {566return httpOnly;567}568569/**570* Indicates whether the cookie should be considered HTTP Only. If set to571* {@code true} it means the cookie should not be accessible to scripting572* engines like javascript.573*574* @param httpOnly575* if {@code true} make the cookie HTTP only, i.e. only visible as576* part of an HTTP request.577*578* @see #isHttpOnly()579*/580public void setHttpOnly(boolean httpOnly) {581this.httpOnly = httpOnly;582}583584/**585* The utility method to check whether a host name is in a domain or not.586*587* <p> This concept is described in the cookie specification.588* To understand the concept, some terminologies need to be defined first:589* <blockquote>590* effective host name = hostname if host name contains dot<br>591* 592* or = hostname.local if not593* </blockquote>594* <p>Host A's name domain-matches host B's if:595* <blockquote><ul>596* <li>their host name strings string-compare equal; or</li>597* <li>A is a HDN string and has the form NB, where N is a non-empty598* name string, B has the form .B', and B' is a HDN string. (So,599* x.y.com domain-matches .Y.com but not Y.com.)</li>600* </ul></blockquote>601*602* <p>A host isn't in a domain (RFC 2965 sec. 3.3.2) if:603* <blockquote><ul>604* <li>The value for the Domain attribute contains no embedded dots,605* and the value is not .local.</li>606* <li>The effective host name that derives from the request-host does607* not domain-match the Domain attribute.</li>608* <li>The request-host is a HDN (not IP address) and has the form HD,609* where D is the value of the Domain attribute, and H is a string610* that contains one or more dots.</li>611* </ul></blockquote>612*613* <p>Examples:614* <blockquote><ul>615* <li>A Set-Cookie2 from request-host y.x.foo.com for Domain=.foo.com616* would be rejected, because H is y.x and contains a dot.</li>617* <li>A Set-Cookie2 from request-host x.foo.com for Domain=.foo.com618* would be accepted.</li>619* <li>A Set-Cookie2 with Domain=.com or Domain=.com., will always be620* rejected, because there is no embedded dot.</li>621* <li>A Set-Cookie2 from request-host example for Domain=.local will622* be accepted, because the effective host name for the request-623* host is example.local, and example.local domain-matches .local.</li>624* </ul></blockquote>625*626* @param domain627* the domain name to check host name with628*629* @param host630* the host name in question631*632* @return {@code true} if they domain-matches; {@code false} if not633*/634public static boolean domainMatches(String domain, String host) {635if (domain == null || host == null)636return false;637638// if there's no embedded dot in domain and domain is not .local639boolean isLocalDomain = ".local".equalsIgnoreCase(domain);640int embeddedDotInDomain = domain.indexOf('.');641if (embeddedDotInDomain == 0)642embeddedDotInDomain = domain.indexOf('.', 1);643if (!isLocalDomain644&& (embeddedDotInDomain == -1 ||645embeddedDotInDomain == domain.length() - 1))646return false;647648// if the host name contains no dot and the domain name649// is .local or host.local650int firstDotInHost = host.indexOf('.');651if (firstDotInHost == -1 &&652(isLocalDomain ||653domain.equalsIgnoreCase(host + ".local"))) {654return true;655}656657int domainLength = domain.length();658int lengthDiff = host.length() - domainLength;659if (lengthDiff == 0) {660// if the host name and the domain name are just string-compare euqal661return host.equalsIgnoreCase(domain);662}663else if (lengthDiff > 0) {664// need to check H & D component665String H = host.substring(0, lengthDiff);666String D = host.substring(lengthDiff);667668return (H.indexOf('.') == -1 && D.equalsIgnoreCase(domain));669}670else if (lengthDiff == -1) {671// if domain is actually .host672return (domain.charAt(0) == '.' &&673host.equalsIgnoreCase(domain.substring(1)));674}675676return false;677}678679/**680* Constructs a cookie header string representation of this cookie,681* which is in the format defined by corresponding cookie specification,682* but without the leading "Cookie:" token.683*684* @return a string form of the cookie. The string has the defined format685*/686@Override687public String toString() {688if (getVersion() > 0) {689return toRFC2965HeaderString();690} else {691return toNetscapeHeaderString();692}693}694695/**696* Test the equality of two HTTP cookies.697*698* <p> The result is {@code true} only if two cookies come from same domain699* (case-insensitive), have same name (case-insensitive), and have same path700* (case-sensitive).701*702* @return {@code true} if two HTTP cookies equal to each other;703* otherwise, {@code false}704*/705@Override706public boolean equals(Object obj) {707if (obj == this)708return true;709if (!(obj instanceof HttpCookie))710return false;711HttpCookie other = (HttpCookie)obj;712713// One http cookie equals to another cookie (RFC 2965 sec. 3.3.3) if:714// 1. they come from same domain (case-insensitive),715// 2. have same name (case-insensitive),716// 3. and have same path (case-sensitive).717return equalsIgnoreCase(getName(), other.getName()) &&718equalsIgnoreCase(getDomain(), other.getDomain()) &&719Objects.equals(getPath(), other.getPath());720}721722/**723* Returns the hash code of this HTTP cookie. The result is the sum of724* hash code value of three significant components of this cookie: name,725* domain, and path. That is, the hash code is the value of the expression:726* <blockquote>727* getName().toLowerCase().hashCode()<br>728* + getDomain().toLowerCase().hashCode()<br>729* + getPath().hashCode()730* </blockquote>731*732* @return this HTTP cookie's hash code733*/734@Override735public int hashCode() {736int h1 = name.toLowerCase().hashCode();737int h2 = (domain!=null) ? domain.toLowerCase().hashCode() : 0;738int h3 = (path!=null) ? path.hashCode() : 0;739740return h1 + h2 + h3;741}742743/**744* Create and return a copy of this object.745*746* @return a clone of this HTTP cookie747*/748@Override749public Object clone() {750try {751return super.clone();752} catch (CloneNotSupportedException e) {753throw new RuntimeException(e.getMessage());754}755}756757// ---------------- Private operations --------------758759// Note -- disabled for now to allow full Netscape compatibility760// from RFC 2068, token special case characters761//762// private static final String tspecials = "()<>@,;:\\\"/[]?={} \t";763private static final String tspecials = ",; "; // deliberately includes space764765/*766* Tests a string and returns true if the string counts as a token.767*768* @param value769* the {@code String} to be tested770*771* @return {@code true} if the {@code String} is a token;772* {@code false} if it is not773*/774private static boolean isToken(String value) {775int len = value.length();776777for (int i = 0; i < len; i++) {778char c = value.charAt(i);779780if (c < 0x20 || c >= 0x7f || tspecials.indexOf(c) != -1)781return false;782}783return true;784}785786/*787* Parse header string to cookie object.788*789* @param header790* header string; should contain only one NAME=VALUE pair791*792* @return an HttpCookie being extracted793*794* @throws IllegalArgumentException795* if header string violates the cookie specification796*/797private static HttpCookie parseInternal(String header,798boolean retainHeader)799{800HttpCookie cookie = null;801String namevaluePair = null;802803StringTokenizer tokenizer = new StringTokenizer(header, ";");804805// there should always have at least on name-value pair;806// it's cookie's name807try {808namevaluePair = tokenizer.nextToken();809int index = namevaluePair.indexOf('=');810if (index != -1) {811String name = namevaluePair.substring(0, index).trim();812String value = namevaluePair.substring(index + 1).trim();813if (retainHeader)814cookie = new HttpCookie(name,815stripOffSurroundingQuote(value),816header);817else818cookie = new HttpCookie(name,819stripOffSurroundingQuote(value));820} else {821// no "=" in name-value pair; it's an error822throw new IllegalArgumentException("Invalid cookie name-value pair");823}824} catch (NoSuchElementException ignored) {825throw new IllegalArgumentException("Empty cookie header string");826}827828// remaining name-value pairs are cookie's attributes829while (tokenizer.hasMoreTokens()) {830namevaluePair = tokenizer.nextToken();831int index = namevaluePair.indexOf('=');832String name, value;833if (index != -1) {834name = namevaluePair.substring(0, index).trim();835value = namevaluePair.substring(index + 1).trim();836} else {837name = namevaluePair.trim();838value = null;839}840841// assign attribute to cookie842assignAttribute(cookie, name, value);843}844845return cookie;846}847848/*849* assign cookie attribute value to attribute name;850* use a map to simulate method dispatch851*/852static interface CookieAttributeAssignor {853public void assign(HttpCookie cookie,854String attrName,855String attrValue);856}857static final java.util.Map<String, CookieAttributeAssignor> assignors =858new java.util.HashMap<>();859static {860assignors.put("comment", new CookieAttributeAssignor() {861public void assign(HttpCookie cookie,862String attrName,863String attrValue) {864if (cookie.getComment() == null)865cookie.setComment(attrValue);866}867});868assignors.put("commenturl", new CookieAttributeAssignor() {869public void assign(HttpCookie cookie,870String attrName,871String attrValue) {872if (cookie.getCommentURL() == null)873cookie.setCommentURL(attrValue);874}875});876assignors.put("discard", new CookieAttributeAssignor() {877public void assign(HttpCookie cookie,878String attrName,879String attrValue) {880cookie.setDiscard(true);881}882});883assignors.put("domain", new CookieAttributeAssignor(){884public void assign(HttpCookie cookie,885String attrName,886String attrValue) {887if (cookie.getDomain() == null)888cookie.setDomain(attrValue);889}890});891assignors.put("max-age", new CookieAttributeAssignor(){892public void assign(HttpCookie cookie,893String attrName,894String attrValue) {895try {896long maxage = Long.parseLong(attrValue);897if (cookie.getMaxAge() == MAX_AGE_UNSPECIFIED)898cookie.setMaxAge(maxage);899} catch (NumberFormatException ignored) {900throw new IllegalArgumentException(901"Illegal cookie max-age attribute");902}903}904});905assignors.put("path", new CookieAttributeAssignor(){906public void assign(HttpCookie cookie,907String attrName,908String attrValue) {909if (cookie.getPath() == null)910cookie.setPath(attrValue);911}912});913assignors.put("port", new CookieAttributeAssignor(){914public void assign(HttpCookie cookie,915String attrName,916String attrValue) {917if (cookie.getPortlist() == null)918cookie.setPortlist(attrValue == null ? "" : attrValue);919}920});921assignors.put("secure", new CookieAttributeAssignor(){922public void assign(HttpCookie cookie,923String attrName,924String attrValue) {925cookie.setSecure(true);926}927});928assignors.put("httponly", new CookieAttributeAssignor(){929public void assign(HttpCookie cookie,930String attrName,931String attrValue) {932cookie.setHttpOnly(true);933}934});935assignors.put("version", new CookieAttributeAssignor(){936public void assign(HttpCookie cookie,937String attrName,938String attrValue) {939try {940int version = Integer.parseInt(attrValue);941cookie.setVersion(version);942} catch (NumberFormatException ignored) {943// Just ignore bogus version, it will default to 0 or 1944}945}946});947assignors.put("expires", new CookieAttributeAssignor(){ // Netscape only948public void assign(HttpCookie cookie,949String attrName,950String attrValue) {951if (cookie.getMaxAge() == MAX_AGE_UNSPECIFIED) {952cookie.setMaxAge(cookie.expiryDate2DeltaSeconds(attrValue));953}954}955});956}957private static void assignAttribute(HttpCookie cookie,958String attrName,959String attrValue)960{961// strip off the surrounding "-sign if there's any962attrValue = stripOffSurroundingQuote(attrValue);963964CookieAttributeAssignor assignor = assignors.get(attrName.toLowerCase());965if (assignor != null) {966assignor.assign(cookie, attrName, attrValue);967} else {968// Ignore the attribute as per RFC 2965969}970}971972static {973sun.misc.SharedSecrets.setJavaNetHttpCookieAccess(974new sun.misc.JavaNetHttpCookieAccess() {975public List<HttpCookie> parse(String header) {976return HttpCookie.parse(header, true);977}978979public String header(HttpCookie cookie) {980return cookie.header;981}982}983);984}985986/*987* Returns the original header this cookie was consructed from, if it was988* constructed by parsing a header, otherwise null.989*/990private String header() {991return header;992}993994/*995* Constructs a string representation of this cookie. The string format is996* as Netscape spec, but without leading "Cookie:" token.997*/998private String toNetscapeHeaderString() {999return getName() + "=" + getValue();1000}10011002/*1003* Constructs a string representation of this cookie. The string format is1004* as RFC 2965/2109, but without leading "Cookie:" token.1005*/1006private String toRFC2965HeaderString() {1007StringBuilder sb = new StringBuilder();10081009sb.append(getName()).append("=\"").append(getValue()).append('"');1010if (getPath() != null)1011sb.append(";$Path=\"").append(getPath()).append('"');1012if (getDomain() != null)1013sb.append(";$Domain=\"").append(getDomain()).append('"');1014if (getPortlist() != null)1015sb.append(";$Port=\"").append(getPortlist()).append('"');10161017return sb.toString();1018}10191020static final TimeZone GMT = TimeZone.getTimeZone("GMT");10211022/*1023* @param dateString1024* a date string in one of the formats defined in Netscape cookie spec1025*1026* @return delta seconds between this cookie's creation time and the time1027* specified by dateString1028*/1029private long expiryDate2DeltaSeconds(String dateString) {1030Calendar cal = new GregorianCalendar(GMT);1031for (int i = 0; i < COOKIE_DATE_FORMATS.length; i++) {1032SimpleDateFormat df = new SimpleDateFormat(COOKIE_DATE_FORMATS[i],1033Locale.US);1034cal.set(1970, 0, 1, 0, 0, 0);1035df.setTimeZone(GMT);1036df.setLenient(false);1037df.set2DigitYearStart(cal.getTime());1038try {1039cal.setTime(df.parse(dateString));1040if (!COOKIE_DATE_FORMATS[i].contains("yyyy")) {1041// 2-digit years following the standard set1042// out it rfc 62651043int year = cal.get(Calendar.YEAR);1044year %= 100;1045if (year < 70) {1046year += 2000;1047} else {1048year += 1900;1049}1050cal.set(Calendar.YEAR, year);1051}1052return (cal.getTimeInMillis() - whenCreated) / 1000;1053} catch (Exception e) {1054// Ignore, try the next date format1055}1056}1057return 0;1058}10591060/*1061* try to guess the cookie version through set-cookie header string1062*/1063private static int guessCookieVersion(String header) {1064int version = 0;10651066header = header.toLowerCase();1067if (header.indexOf("expires=") != -1) {1068// only netscape cookie using 'expires'1069version = 0;1070} else if (header.indexOf("version=") != -1) {1071// version is mandatory for rfc 2965/2109 cookie1072version = 1;1073} else if (header.indexOf("max-age") != -1) {1074// rfc 2965/2109 use 'max-age'1075version = 1;1076} else if (startsWithIgnoreCase(header, SET_COOKIE2)) {1077// only rfc 2965 cookie starts with 'set-cookie2'1078version = 1;1079}10801081return version;1082}10831084private static String stripOffSurroundingQuote(String str) {1085if (str != null && str.length() > 2 &&1086str.charAt(0) == '"' && str.charAt(str.length() - 1) == '"') {1087return str.substring(1, str.length() - 1);1088}1089if (str != null && str.length() > 2 &&1090str.charAt(0) == '\'' && str.charAt(str.length() - 1) == '\'') {1091return str.substring(1, str.length() - 1);1092}1093return str;1094}10951096private static boolean equalsIgnoreCase(String s, String t) {1097if (s == t) return true;1098if ((s != null) && (t != null)) {1099return s.equalsIgnoreCase(t);1100}1101return false;1102}11031104private static boolean startsWithIgnoreCase(String s, String start) {1105if (s == null || start == null) return false;11061107if (s.length() >= start.length() &&1108start.equalsIgnoreCase(s.substring(0, start.length()))) {1109return true;1110}11111112return false;1113}11141115/*1116* Split cookie header string according to rfc 2965:1117* 1) split where it is a comma;1118* 2) but not the comma surrounding by double-quotes, which is the comma1119* inside port list or embeded URIs.1120*1121* @param header1122* the cookie header string to split1123*1124* @return list of strings; never null1125*/1126private static List<String> splitMultiCookies(String header) {1127List<String> cookies = new java.util.ArrayList<String>();1128int quoteCount = 0;1129int p, q;11301131for (p = 0, q = 0; p < header.length(); p++) {1132char c = header.charAt(p);1133if (c == '"') quoteCount++;1134if (c == ',' && (quoteCount % 2 == 0)) {1135// it is comma and not surrounding by double-quotes1136cookies.add(header.substring(q, p));1137q = p + 1;1138}1139}11401141cookies.add(header.substring(q));11421143return cookies;1144}1145}114611471148